Exercise to create an insertString function to linked-list

I'm not sure if your insertEntry function is correct. It seems to be hardcoded to add an entry at the end of the linked list; you want to be able to add an entry anywhere (except at the start of the list which is the object of the next exercise in the book).

Here's my solution to this exercise.

/* Exercise 10.2

   Write a function called insertEntry() to insert a new entry into a linked
   list. Have the procedure take as arguments a pointer to the list entry to
   be inserted (of type struct entry as defined in this chapter), and a
   pointer to an element in the list *after* which the new entry is to be
   inserted.

   note: inserts n2_5 after n2
*/

#include <stdio.h>

struct entry
{
    int value;
    struct entry *next;
};

void insertEntry (struct entry *new, struct entry *follow)
{
    new->next = follow->next;
    follow->next = new;
}

int main (void)
{
    void insertEntry (struct entry *new, struct entry *follow);

    struct entry n1, n2, n3, n4, n5, n2_5, *listPtr;

    n1.value = 100;
    n1.next = &n2;

    n2.value = 200;
    n2.next = &n3;

    n3.value = 300;
    n3.next = &n4;

    n4.value = 400;
    n4.next = &n5;

    n5.value = 500;
    n5.next = (struct entry *) 0;

    printf ("\nlinked list: ");

    listPtr = &n1;

    while ( listPtr != (struct entry *) 0 ) {
        printf ("%i ", listPtr->value);
        listPtr = listPtr->next;
    }

    printf ("\n");

    // insert new entry

    n2_5.value = 250;

    printf ("inserting new entry %i ...\n", n2_5.value);

    insertEntry (&n2_5, &n2);

    printf ("linked list: ");

    listPtr = &n1;

    while ( listPtr != (struct entry *) 0 ) {
        printf ("%i ", listPtr->value);
        listPtr = listPtr->next;
    }

    printf ("\n");

    return 0;
}


Before reviewing the code, I want to point out that this kind of functionality already exists in the core Java libraries. A ScheduledExecutorService will run an arbitrary Runnable on a fixed time schedule. Instead of extending RapidExecutor, you just implement the interface and pass it into the service.

Some thoughts on your code:

In my opinion, your code is violating the Single Responsibility Principle. It’s doing three things: defining the interface for something that executes every tick, defining a new type of Thread, and controlling the frequency that this new type of thread executes code. As mentioned above, I’d strongly suggest using ScheduledExecutorService, Thread, and implement Runnable for the code that is currently in subclasses of RapidExecutor.

Your Application app should be private, tick() should be tick(Application app), and run() should call tick(this.app). Keep variables contained in scope.

Don’t use UPPERCASE for abbreviations. It’s considered better to use camelCase (tps or tpsCount). And don’t abbreviate when you don’t need to. It took me a bit to figure out that TPS was ticksPerSecond.

Please don’t throw an exception just to catch it to get the stack trace to print it out. Let the caller figure out what to do when you tell them they gave you bad input. They might not care about the error message being written to System.err, or they might actively not want that to happen. And don’t use a generic Exception. IllegalArgumentException, thrown from the constructor, would be better.

tick() should be protected, not public. You only want it called from inside RapidExecutor.

run() must be final. If it isn’t, anybody who extends RapidExecutor can change what it means for run() to be executed.

It’s considered better form to declare variables on separate lines.

Variables should be declared in the tightest scope possible to reduce cognitive load on readers of your code. startTime, now, and delta should all be declared inside your while loop.

There’s no need to cast delta back to an int. And perhaps sleepTime would be a better variable name than delta? It’s good for variables to clearly express what the represent.

Perhaps storing final long tickDuration = System.currentTimeMillis() - startTime would be better than now.

Perhaps renaming TPSCount to millisecondsPerTick would make it more clear what was being stored.

Again, don’t randomly catch Exception. And if you do handle an exception, reset the state of RapidExecutor to something appropriate. Right now execution stops but this.running is still true. Are you trying to handle the InterruptedException? If so, declare that try-catch block immediately around sleep(). There are well-understood ways to correctly handle InterruptedException, and you should look into them. Are you trying to handle exceptions coming from tick()? If so, put a tight block around this.tick(). Maybe even declaring your own checked exception in this case would be a good idea.

It’s unclear why you stop execution when it takes longer than TPSCount to run a tick(). I’m not convinced that’s a good design. Would it be better to skip a tick and get a choppy frame rate rather than just failing silently? Make sure that this is clearly documented.

Don’t ever synchronize a method using the synchronized keyword. Locking on yourself is never a good idea because somebody else could take out a lock on you, and then stopThread() will never be able to execute. Use a private Object lock along with synchronized(this.lock), or a more complex approach when warranted.

I also don’t see why you need to synchronize either of the method calls inside stopThread(). Are you sure that’s necessary?

You’ll need to make stopThread() final to prevent subclasses from changing what it means to stop a thread.

Again, make the exception block in stopThread() as tight as possible and handle the most specific exception possible.

If you applied all my suggestions to your code, it might look something like:

public abstract class RapidExecutor extends Thread {

    private final Object lock = new Object();
    private final Application application;
    private final int ticksPerSecond;

    private boolean running;

    public RapidExecutor(final Application application, final int ticksPerSecond) {

        this.application = application;
        this.ticksPerSecond = ticksPerSecond;

        if (ticksPerSecond > 1000 || ticksPerSecond < 1) {
            throw new IllegalArgumentException("ticksPerSecond must be between 1 and 1000, was " + ticksPerSecond);
        }

    }

    protected abstract void tick(final Application application) throws TickFailedException;

    @Override
    public void run() {

        this.running = true;
        final int millisecondsPerTick = 1000 / this.ticksPerSecond;

        while (this.running) {

            final long startTime = System.currentTimeMillis();

            try {
                this.tick(this.application);
            } catch (final TickFailedException | RuntimeException e) {
                this.running = false;
                // log the exception ?
            }

            final long tickDuration = System.currentTimeMillis() - startTime;
            final long sleepTime = millisecondsPerTick - tickDuration;
            if (sleepTime < 0) {
                this.stopThread();
            }

            try {
                sleep(sleepTime);
            } catch (final InterruptedException e) {
                this.running = false;
                this.interrupt();
                // log the exception?
            }
        }
    }

    public final void stopThread() {

        synchronized (this.lock) {
            this.running = false;
            try {
                this.join();
            } catch (final InterruptedException e) {
                this.interrupt();
                e.printStackTrace();
            }
        }

    }

}


A few points first.

Avoid any like the plague. You can nearly always figure out a better type. When dealing with a JSON serialized data, I like to have a function similar to this to get rid of any as soon as possible:

function verify<T>(obj: any, fallback: T, isT: (obj: any) => obj is T): T {
  return isT(obj) ? obj : fallback;
}

Object.keys and Object.entries are a better fit for looping through an object if you are going to check hasOwnProperty. I prefer Object.entries when possible, if you have the browser support.
Choose const or let, don't mix them without good reason. const can result in better type inference so I prefer to use it when possible.

Here is how I would implement this function.

function convertObjectToMap<In, Out>(
  obj: { [K: string]: In } | undefined | null,
  classOfIn: new (v: In) => Out
): Map<string, Out> {
  const result = new Map<string, Out>();

  for (const [key, val] of Object.entries(obj || {})) {
    result.set(key, new classOfIn(val));
  }

  return result;
}


Firstly, for...in is used to enumerate over object properties, not to iterate through arrays.  You should use a traditional for loop for this.

Secondly, you could probably refine your console logging portion a bit. It may not have any impact to application performance, but it would make your console look prettier.

$('body').on('click', '#logReport', function() {
    var i, j, k, l;

    console.group("Live Links:");
    for (i=0, j=liveLinks.length; i<j; i++) {
        console.log(liveLinks[i]);
    }
    console.groupEnd();
    console.group("Dead Links:");
    for (k=0, l=deadLinks.length; k<l; k++) {
        console.log(deadLinks[k]);
    }
    console.groupEnd();
});

As far as I know, this works for both Google Chrome and Mozilla Firefox (FireBug).  See here for more information.


Implementation of Luhn credit card algorithm

Style

Python has a style guide called PEP 8. It is a good habit to try to follow it.

In your case, that would mean fixing the missing whitespaces, removing parenthesis in if(result).

Also, you could get rid of old commented code and add a proper docstring if you want to describe the behavior of the function.

Tests

It could be a good idea to write tests before trying to improve your code.

I wrote a very simple code but you could get this chance to dive into unit testing frameworks:

TESTS = [
    (1456734512345698, False),
    (4539869650133101, True),
    (1456734512345698, False),
    (5239512608615007, True),
]

for (card_number, expected_valid) in TESTS:
    valid = validate_credit_card_number(card_number)
    assert valid == expected_valid

Useless test

At the end of the function, you can return directly:

return final_sum % 10 == 0

Useless variables

The my_list variable is not required.

Also, we can take this chance to get rid of the variables at the end of the function:

return (sum(t_list) + sum(list2)) % 10 == 0

Conversion of card_number

At the beginning of the function, you could convert the parts of card_number directly to integer so that you do it in a single place.
Also, that removed the need to the call of list. We just have:

temp_list = [int(c) for c in str(card_number)]

And we can get rid of the line:

list2 = [int (n) for n in list2]

At this stage, the code looks like:

def validate_credit_card_number(card_number):
    temp_list = [int(c) for c in str(card_number)]

    list1 = temp_list[-2::-2]
    list1 = [2 * n for n in list1]

    list2 = temp_list[::-2]

    t_list = list1

    for el in list1:
        sum_res = 0

        if el > 9:
            idx = list1.index(el)
            t_list.pop(idx)

            while el:
                rem = el % 10
                sum_res += rem
                el = el // 10
            t_list.insert(idx, sum_res)

    return (sum(t_list) + sum(list2)) % 10 == 0

Yet another useless variable

t_list aliases list1 (I am not sure if this is intended if if you were planning to have a copy of list1). Whenever you update the list through one variable, the other is affected as well. I highly recommend Ned Batchelder's talk about names and values.

In your case, we can get rid of t_list completely without changing the behavior of the function.

Simplify list logic

You go through multiple steps to modify list1 (or t_list) : index, pop, index. These steps are more expensive/complicated than required. At the end of the day, you do not care about list1, you just want its final sum. You could keep track of the sum directly:

sum1 = 0
for el in list1:
    if el > 9:
        sum_res = 0
        while el:
            rem = el % 10
            sum_res += rem
            el = el // 10
        sum1 += sum_res
    else:
        sum1 += el

return (sum1 + sum(list2)) % 10 == 0

We can take this chance to perform the multiplication in the loop to remove a list comprehension.

Also, we can initialise the sum with sum(list2) so that we don't have to add them at the end:

def validate_credit_card_number(card_number):
    temp_list = [int(c) for c in str(card_number)]

    list1 = temp_list[-2::-2]
    list2 = temp_list[::-2]

    total_sum = sum(list2)
    for el in list1:
        el *= 2
        if el > 9:
            sum_res = 0
            while el:
                rem = el % 10
                sum_res += rem
                el = el // 10
            total_sum += sum_res
        else:
            total_sum += el

    return total_sum % 10 == 0

Math logic

The code uses 10 (the base used for computations) everywhere except for one 9 which seems unexpected. You could write: el >= 10 instead.

Also, that check is not required because the logic applies exactly the same way for elements smaller than 10:

for el in list1:
    el *= 2
    sum_res = 0
    while el:
        rem = el % 10
        sum_res += rem
        el = el // 10
    total_sum += sum_res

Also, you could use el //= 10 but you can get the best ouf of the Python builtins by using divmod returning both the quotient and the remainder:

    while el:
        el, rem = divmod(el, 10)
        sum_res += rem
    total_sum += sum_res

Then, it becomes clear that the variable sum_res is not really required as we could use total_sum instead:

    while el:
        el, rem = divmod(el, 10)
        total_sum += rem

"Final" code

def validate_credit_card_number(card_number):
    temp_list = [int(c) for c in str(card_number)]

    list1 = temp_list[-2::-2]
    list2 = temp_list[::-2]

    total_sum = sum(list2)
    for el in list1:
        el *= 2
        while el:
            el, rem = divmod(el, 10)
            total_sum += rem

    return total_sum % 10 == 0

TESTS = [
    (1456734512345698, False),
    (4539869650133101, True),
    (1456734512345698, False),
    (5239512608615007, True),
]

for (card_number, expected_valid) in TESTS:
    valid = validate_credit_card_number(card_number)
    assert valid == expected_valid

More simplification

Thinking about it, things can still be simplified a lot.
What you are doing with the while loop can be performed using str conversion:

total_sum = sum(list2)
for el in list1:
    total_sum += sum(int(c) for c in str(2 * el))

Going further (too far?), this leads to:

def validate_credit_card_number(card_number):
    temp_list = [int(c) for c in str(card_number)]

    list1 = temp_list[-2::-2]
    list2 = temp_list[::-2]

    total_sum = sum(list2) + sum(sum(int(c) for c in str(2 * el)) for el in list1)
    return total_sum % 10 == 0

Edit:

More simplification

We are using str and int to get the digits of a number... which is known to be smaller than 18 (2 * 9).
A trick could be, once again, to use divmod returning the quotient and remainder and use sum on it.

total_sum = sum(list2)
for el in list1:
    total_sum += sum(divmod(2 * el, 10))

or

total_sum = sum(list2) + sum(sum(divmod(2 * el, 10)) for el in list1)

Playing with indices

Instead of splitting the list into 2 lists, we could iterate over the (reversed) list once and handle differently elements at odd positions and elements at even positions.

We'd get something like:

def validate_credit_card_number(card_number):
    temp_list = [int(c) for c in str(card_number)]

    total_sum = 0
    for i, e in enumerate(reversed(temp_list)):
        if i % 2 == 0:
            total_sum += e
        else:
            total_sum += sum(divmod(2 * e, 10))

    return total_sum % 10 == 0

Or the more concise solution taking advantage of the fact that the divmod trick works for both cases:

def validate_credit_card_number(card_number):
    total_sum = 0
    for i, c in enumerate(reversed(str(card_number))):
        e = int(c) * (2 if i % 2 else 1)
        total_sum += sum(divmod(e, 10))
    return total_sum % 10 == 0

or

def validate_credit_card_number(card_number):
    return sum(sum(divmod(int(c) * (2 if i % 2 else 1), 10))
               for i, c in enumerate(reversed(str(card_number)))) % 10 == 0


Simple Flask API backend to maintain a word list

Obligatory reference to the style guide. You have incorrect whitespace, for example, and (worse) it's inconsistent:

@app.route("/getWord", methods=['GET'])
                    # ^ yes
@app.route("/postWord",methods=["GET","POST"])
                     # ^ preferably not, but *definitely* be consistent

if 'long' in request.args and 'lat' in request.args and 'radius' in request.args and 'ids' in request.args:

Would be neater as:

if all(arg in request.args for arg in ['long', 'lat', 'radius', 'ids']):

This also allows you to extract a REQUIRED_ARGS constant if you wish.

Your exception handling is too broad. For example:

try:
    lat = float(request.args['lat'])
    lng = float(request.args['long'])
    word = str(request.args['word'])
    definition = str(request.args['definition'])
    return pword(lat,lng,word,definition)
except Exception as e:
    logging.info(str(e))

You should have as little as possible inside the try block, and avoid bare except.

What could actually go wrong inside the try block? E.g. for the first two lines, given that you've already checked for the keys, only a ValueError would get thrown. And as you have similarly broad error handling in pword, you'd only get an error out of that line if the logger itself failed.

Also note that there's a logging.exception that actually takes an error object and deals with the traceback correctly.

You note correctly that the naming is poor. It is also, again, inconsistent:

def fword(lon,lat,...
def pword(lat,lng,...

These parameters have the same meaning, so should have the same name (and ideally the same order). Given that you'd always expect the pair, you could even use a (latitude, longitude) tuple as e.g. a coords argument. Also:

def pword(...):
def postWord():

Finally you have a bunch of functions that all create a cursor and connection, and two of them are almost identical but for the query string and arguments. Look into whether you could reduce duplication by abstracting those similarities out.


These lines appear to be out of order:

extract_entries = lambda url: feedparser.parse(url).entries
addEntries = lambda entries: [feed.items.append(entry) for entry in entries]
merg = lambda urls: [addEntries(extract_entries(url)) for url in urls]
shuffle(feed.entries)
save = lambda outfile: feed.format_rss2_file(outfile)
merg(urls)

In particular, when that shuffle runs, the feed has no entries yet, so there's nothing to shuffle. I think you meant this way:

extract_entries = lambda url: feedparser.parse(url).entries
addEntries = lambda entries: [feed.items.append(entry) for entry in entries]
merg = lambda urls: [addEntries(extract_entries(url)) for url in urls]
merg(urls)
shuffle(feed.entries)

More importantly, I think you're overusing lambdas for no benefit at all. The flow of the logic would be a lot easier to read if you used loops instead:

urls = list(set(open('urls.txt', 'r').readlines()))
shuffle(urls)
for url in urls:
    for entry in feedparser.parse(url).entries:
        feed.items.append(entry)
shuffle(feed.entries)
feed.format_rss2_file('feed.xml')


From the looks of this, you should be using a Stored Procedure, not entirely familiar with how that works in MySQL but I imagine it is similar to SQL Server Stored Procedures.

Using a Stored Procedure would be the easiest way to do this.

You create the stored procedure with the parameters that you need, then in the C# you call the stored procedure giving it the parameters in the specified manner.  I haven't tried to do with with MySQL but I imagine it is much the same as with SQL Server ( I know I said that once already )

You are trying to do the Database's work with C#,  keep them separate.

Cleanse the input, create a command for the Stored Procedure, give it the parameters, execute the command.

This way you can loop through a list of names in C# sending the names to the stored procedure, or create the stored procedure to accept a list of names.

Creating the Stored Procedure will also allow you to use it other places in the C# application, and if you need to change the Query, it is easily maintainable, you change the query and don't have to recompile the application as long as the input stays the same.


Static wcf client to make multiple request with one object

I think you should consider inverting control and moving ServiceClient instantiation outside the repository class. Whether or not ServiceClient is a singleton (in single-instance sense) or not is not something that repository should manage or care about:

public class Conector : IConector
{
    private IRepository Repository { get; }

    public Conector(IRepository repository)
    {
         Repository = repository;
    }
    ...
}

public class Repository : IRepository
{
    protected ServiceClient Client { get; }

    public Repository(ServiceClient client)
    {
        Client = client;
    }

    ...
}


Your method certainly works, but I agree that using nested/multiple loops and inner if/else blocks is inelegant, if only because it makes following the code somewhat harder. Also, as you point out in a comment, hard-coding the structure is a nightmare if you suddenly want a pyramid which is 46 stars high.

As an alternative, I've rewritten the code to break it out into separate methods which hopefully make the code easier to understand, and also to allow a variable pyramid height (any value from zero or above).

public static void main(String[] args) {
    drawStarPyramid2(8);
}

private static void drawStarPyramid2(int height) {
    if (height < 0) {
        throw new IllegalArgumentException("Height cannot be negative.");
    }
    StringBuilder sb = new StringBuilder(height * height);
    appendSides(sb, height);
    appendBaseline(sb, height);
    System.out.println(sb.toString());
}

private static void appendSides(StringBuilder sb, int height) {
    int baselineWidth = height * 2 - 1;
    int midLine = baselineWidth / 2;
    for (int rowIndex = 0; rowIndex < height - 1; ++rowIndex) {
        int leftStarOffset = midLine - rowIndex;
        appendSpacesThenStar(sb, leftStarOffset);
        if (rowIndex > 0) {
            int rightStarOffset = midLine + rowIndex - 1;
            appendSpacesThenStar(sb, rightStarOffset - leftStarOffset);
        }
        sb.append("\n");
    }
}

private static void appendSpacesThenStar(StringBuilder sb, int spaces) {
    for (int spaceIndex = 0; spaceIndex < spaces; ++spaceIndex) {
        sb.append(' ');
    }
    sb.append('*');
}

private static void appendBaseline(StringBuilder sb, int stars) {
    boolean first = true;
    for (int starIndex = 0; starIndex < stars; ++starIndex) {
        if (!first) {
            sb.append(' ');
        }
        sb.append('*');
        first = false;
    }
}

Because the sides need to be rendered differently to the baseline, each chunk of code goes into its own method, with a name which clearly describes the different purpose of each.

The appendSides method is responsible only for drawing the left and right sides of the triangle. This calculates the baseline width (the number of characters on the console counting stars and spaces) and this will be equal to height stars (because the number of stars on the baseline must equal the number of stars along the height of each side) plus height - 1 spaces, which gives 2 * height - 1. Then it calculates the mid-way point (in terms of characters on the console line) and then places the first star at this point.

For all subsequent lines, the "left" side star is simply placed at the position which is one additional character further left of the previous position (starting at the mid-way position), and the "right" side star at the position which is one additional character further right of the previous position. The rowIndex is a convenient way to calculate how many places to move away from the mid-way point on each line. The mathematics being used to calculate all of these offsets is fairly simple, but I recommend you sketch it out on a bit of paper, one line at a time, to get a feel for how the numbers work together.

The appendSpacesThenStar method simply appends the specified number of space characters to the StringBuilder and then a star. This method does not append a newline, because this method is often called twice for the same line, to write the "left" and then the "right" stars.

The appendBaseline method just appends (to the StringBuilder) the required number of stars, separated by spaces.

A StringBuilder is being used to make assembly of the final string sequence more efficient, allowing the building of each line to be split across multiple method calls, rather than trying to finish each line in a single statement.

(Also note that the initial capacity passed to the StringBuilder constructor can be improved by giving exactly the number of characters that will be needed, once spaces, stars, and newlines have been taken into consideration, but I'll leave this as an exercise for you.)


Printing a nested data structure in Clojure

Separate impure IO from data transformations

  I wrote the following code which transforms a nested data structure ... into a printable form

Not only does your code transform the data into a printable form, it also prints it.

To better isolate the side effects of printing, you should separate these two operations: first assemble a formatted string, then you can do whatever you want with it -- print it with a single call to println, save it, send it over the network, etc.

(defn format-board
  [board]
  (->> (board->icons board)
       (map (partial str/join " "))
       (str/join "\n")))

(def print-board
  (comp println format-board))

doseq

As a side note, instead of (doall (map println seq-to-print)) it is common to see

(doseq [line seq-to-print]
  (println line))

which is usually what you want, since

doseq does not hold onto the return value of println, whereas doall builds up an entire return sequence in memory (important when the sequence is big!) -- which is why your original print-board returns (nil nil nil) instead of nil; and
this makes it more visually clear that you are doing something with each item in the sequence, instead of generating a new sequence with map


Generic dataloader for redux-thunk using axios

This is one of the problems with async actions in redux-thunk. As you point out you have to create constants for "APARTMENT_FETCH_STATUS" and manually dispatch actions of this type before and after the request has been done.

The redux-promise-middleware library actually does all this for you. You simply create an action like so:

const foo = () => ({
  type: 'FOO',
  payload: new Promise()
});

and the library will take care of dispatching an action of type "FOO_PENDING", and then of type "FOO_FULFILLED" when the promise has resolved. With redux-promise-middleware your actions would become something like this:

const showResultOfApartment = () => ({
    type: "FETCH_APARTMENT",
    payload: axios.get("http://api.com/apartments").then(result => result.data)
})

In your reducer you would create handlers for "FETCH_APARTMENT_PENDING", "FETCH_APARTMENT_FULFILLED" and "FETCH_APARTMENT_REJECTED". In the case where the promise fulfills or rejects, you also get the result of the promise by accessing action.payload. An example of what it could look like:

function apartmentReducer(state, action){
    if(action.type === "FETCH_APARTMENT_PENDING"){
        return Object.assign({}, state, { loading: true })
    }
    else if(action.type === "FETCH_APARTMENT_FULFILLED"){
        return Object.assign({}, state, { loading: false, apartment: action.payload })
    }
    else if(action.type === "FETCH_APARTMENT_REJECTED"){
        return Object.assign({}, state, { loading: false, error: action.payload })
    }
    return state;
}

redux-promise-middleware

Introduction to redux-promise-middleware


Overall it looks like you are in the right track, though I think you have overcomplicated things a bit with that custom state flag and constants. C99 gives you the bool type, which could be used instead. Failing that, I would have settled with an integer. The defines seem overkill for such a tiny program.

You can omit the return 0 at the end of main, it is implicit (C99 standard).

_tmain and _TCHAR are Microsoft extensions, added by Visual Studio when you create a project with it. Be advised that this is a compiler extension and is therefore non-portable. The standard C entry point function is called just main and it should take no arguments, unless you need to process the command line.

Prefer exposing your #include dependencies instead of relying on the auto-generated stdafx.h that Visual Studio adds for you. Your program needs at least <stdio.h>.

This is how I would have written it, using a simple bool to keep track of the state, and, as @Loki suggested, using isspace() to test the character (always avoid reinventing the wheel, unless you really mean to):

#include <stdio.h>   // getchar() & friends
#include <ctype.h>   // isspace()
#include <stdbool.h> // bool, true, false

int main(void)
{
    int c;
    bool needNewLine = false;

    while ((c = getchar()) != EOF) {

        if (isspace(c)) {
            needNewLine = true;
            continue;
        }

        if (needNewLine) {
            putchar('\n');
            needNewLine = false;
        }

        putchar(c);
    }
}


Running async tasks and cancelling after a timeout if necessary

Can't you replace

protected abstract Task StartCore(CancellationToken cancellationToken);

with

protected abstract void StartCore(CancellationToken cancellationToken);

and call it as

Task.Run(() => {
                  try
                  {
                      StartCore(cancellationToken);
                  }
                  catch
                  {
                     //logging
                     throw;
                  }
                });

? Why do you need async/await?

You don't really need a timer, you can use WaitAll overload that takes TimeSpan:

var tasks = processors.Select(p => p.Start(token.Token)).ToArray();
if (!Task.WaitAll(tasks, TimeSpan.FromSeconds(5)))
{
    token.Cancel();
    // wait for cancellation, if necessary
    // Task.WaitAll(tasks);
}

You don't show your business logic and you don't say what kind of processing you are doing, so it's hard to tell whether inheritance is the best approach. It doesn't look like it based on your examples. Maybe it is better to have a single Processor class that would contain all the boiler-plate code you require (similar to BackgroundWorker) and inject StartCore as delegate/interface instead.


Command-query segregation principle for an authenticator

Since it's been several days and this question has not been answered, I will give it a go. I'm saying this not because making Authenticate follow Command-Query Separation Principle is hard, but rather I think this design may indicate a more serious problem with security configuration, and I'm not up to date with ASP.NET.

Command Query Separation

  The Authenticate method violates the command-query segregation principle no?

Since you seem to be familiar with Fowler's terminology, let's look at his definition of Command/Query Separation.

  The fundamental idea is that we should divide an object's methods into
  two sharply separated categories:

  Queries: Return a result and do not change the observable state of the system (are free of side effects).
  Commands: Change the state of a system but do not return a value.

Since in this case Authenticate definitely changes state, specifically the session state by setting a cookie, it is a command and should not return a value. You can achieve this, as suggested by @svick:

  you [can] just make Authenticate() return void and then use Authenticated instead.

That is:

public void Authenticate(string username, string password)
{
    // unused `authenticated` can be inlined
    if (FormsAuthentication.Authenticate(username, password))
        FormsAuthentication.SetAuthCookie(username, false);
}

And why not following CQS is a problem? Because Authenticate() returns a value, it is not immediately clear to the reader of the code if the writer of the code just checks the validity of the username/password pair or does what it does now, thus makes understanding the code harder.
Similarly someone looking at the IAuthenticator, which should look like this as you stated that it's a Header Interface:

public interface IAuthenticator
{
    bool Authenticated {get;}
    bool Authenticate(string username, string password);
    void Logout();
}

faces similar dilemma: Do I use Authenticate to just check for the validity of username/password, or does it do something more?

There is also another problem with returning bool from Authenticate(...), because Authenticate is an imperative word, and an Autheticated getter (read-only property) is also present, it could be that bool return value is an error code for the Authenticate command, that is you MUST check it immediately after calling the method and do something with it other than what you would to with the return value of Authenticated. For example Authenticated == false implies wrong password whereas Authenticate(username, password) == false could mean "Membership database is down". Of course error codes are a no-no.

Now I should also state that apparently MS APIs do not always follow CQS principle, as seen here.

But Command Query Separation should also make us reevaluate if the method underneath follows Single Responsibility Principle. A method like this would be used like this:

if (Authenticator.Authenticate(credentials)) {
   // continue to secured content
} else {
   // return to login page
}

We see that the if in Authenticate is duplicate, and increases the complexity of the code unnecessarily:

if (Authenticator.Validate(credentials)) {
   Authenticator.Login();
   // continue to secured content
} else {
   // return to login page
}

This division requires some further points to be made:

Currently Authenticator has two separate responsibilities: Checking if username/password pairs are valid, and keep user logged in across multiple requests.
FormsAuthentication.SetAuthCookie requires username, but you do not use it after checking whether username/password is valid, i.e. Authenticator.Login does not need it.
However your current implementation would need the username to be passed to Authenticator.Login, therefore you would need to modify the interface because of an implementation detail. That is IAuthenticator would not be a proper abstraction over FormsAuthentication.
This is rightly so, because even though Authenticator pretends it's not a static class, it does not encapsulate it's own state. You can observe this, as it does not have any state of its own and all the methods it calls from FormsAuthentication are static methods:

// Note that the no-argument constructor hides its dependency
// to `Thread`, `HttpContext` or something.
IAuthenticator authenticatorOne = new Authenticator();
IAuthenticator authenticatorTwo = new Authenticator();
authenticatorOne.Authenticate("Alice", "4L1(3'5 p455\/\/0rD");
authenticatorTwo.Authenticate("Bob", "808'5 p455\/\/0rD");
authenticatorTwo.Logout();

As seen here, having multiple instances of Authenticator (in a request? thread?) does not make any sense.

Naming Side Note

It is hard to parse Authenticator.Authenticated mentally, as the object of the Authenticate is absent. For example in IIdentity.IsAuthenticated it is clear that the identity is the authenticated thing. If we change members of IAuthenticator as follows:

public interface IAuthenticator
{
    bool Validate(string username, string password);

    bool SomeUserIsLoggedin {get;}
    void Login();
    void Logout();
}

Now it is clear that Login/Logout are opposite commands. SomeUserIsLoggedin checks whether Login has been called and Logout has not been called yet. And Login/Logut having no parameter matches with Some User being the object of Is Logged In, which altogether indicate that you do not care who the user is and care just that he logged in.

This way Validate is more clearly seen to be separable from the rest of the IAuthenticator members.

Header Interfaces Side Note

If you mean Header Interface as in the Fowler's dichotomy of Header/Role interfaces, it is rather an anti pattern, as they violate the ISP:

  Robert Martin talks about this topic as the Interface Segregation
  Principle: role interfaces follow that principle but header interfaces
  do not.


Finding the 20th percentile pixel of an image using a histogram instead of std::sort

Well, index=std::floor(0.2*(srcSor.size())/100 is equivalent to the much simpler index = srcSor.size() / 500, ignoring some inaccuracy in representing 0.2.
Lose the fixed-size std::vectors. You don't depend on any of the benefits of using dynamic memory, so a simple array is sufficient and far more efficient.
Next, you really don't need the cumulative counts in sumHH at all. Just test whether you have reached the target immediately.
Don't cast unless you have to. Casting means overriding the type-system, and is thus error-prone.
Don't use obscure abbreviations.

Resulting code:

unsigned histogram[256] = {};
for (auto j = src.rows; j--;)
    for (auto i = src.cols; i--;)
        ++histogram[src.at<uchar>(j,i)];
int A = 255;
for (auto index = src.rows * src.cols / 500; index > histogram[A]; --A)
    index -= histogram[A];


Multiplying 2 numbers without using * operator in Java

The challenge only requires you to work with integers. This technique would not actually be able to multiply two floating-point numbers, so don't use double. A proper solution for integers would not have a failure node that requires you to return -1.

A better algorithm to use would be the Russian peasant method which can be done by bitwise operations and addition.


Everything looks good over here, however, I would like to mention some points which cover some of your questions.

I can see your methods are dependent on the global variable connectionString.

Global variables creates confusion when code grows.
It harder to maintain.
The code which uses global variables gets tightly coupled.

I suggest you to create a class to handle all database connections. This will make your code more flexible:

It allows to use same connection in other classes.
It allows to use different database connections.

public class ConnectionManager
{
    public static SqlConnection GetSqlConnection()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
        var connection = new SqlConnection(connectionString);
        connection.Open();
        return connection;
    }

    public static OleDbConnection GetOleDbConnection()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["OleDbConnectionString"].ConnectionString;
        var connection = new OleDbConnection(connectionString);
        connection.Open();
        return connection;
    }
}

Above method returns open connection so you don't have to open it.
It force to implement using, try-catch-finally or IDisposable to make sure you always close connection which is a good thing.
No need to have constructor for each class which use database.

It is not a good practise to ignore return value. Your method ExecuteNonQuery has return type void which ignores the return value of command.ExecuteNonQuery();
You should use {} to make code more readable.

Before:

public void ExecuteNonQuery(string commandText, CommandType commandType, params SqlParameter[] commandParameters)
{
    using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(commandText, connection))
    {
        command.CommandType = commandType;
        command.Parameters.AddRange(commandParameters);
        connection.Open();
        command.ExecuteNonQuery();
    }
}

After:

public int ExecuteNonQuery(string commandText, CommandType commandType, params SqlParameter[] commandParameters)
{
    int affectedRows = 0;
    using (var connection = ConnectionManager.GetSqlConnection())
    {
        using (var command = new SqlCommand(commandText, connection))
        {
            command.CommandType = commandType;
            command.Parameters.AddRange(commandParameters);
            affectedRows = command.ExecuteNonQuery();
        }
    }
    return affectedRows;
}

Hope this helps.


Overall, everything seems fine. Some minor nits and suggestions:

Stylistically, you should have:

trailing commas
spaces on struct literals (Post { content: self.content }

PublishResult makes me think it's a type alias of std::result::Result. I'd advocate for picking a different name.
Instead of matching in your tests and having the not-very-useful assert!(true) and assert!(false), add some helper methods to PublishResult to convert to an expected variant. This is a common pattern for this style of enum. Then you can expect with text in your tests
Dnt ndlssly abbr mthds (Don't needlessly abbreviate methods). Call it request_review instead of req_review.
It's strange to have a test (reject_workflow) with no assertions. I don't think anything's wrong with it, as it's testing the methods and types, it's just a bit implicit.

struct Post {
    content: String,
}

struct DraftPost {
    content: String,
}

struct PendingPost {
    content: String,
    approvals: u32,
}

impl Post {
    fn new() -> DraftPost {
        DraftPost { content: String::new() }
    }

    fn content(&self) -> &str {
        &self.content
    }
}

impl DraftPost {
    fn request_review(self) -> PendingPost {
        PendingPost {
            content: self.content,
            approvals: 0,
        }
    }

    fn add_text(&mut self, content: &str) {
        self.content.push_str(content);
    }
}

enum PublishResult {
    PendingPost(PendingPost),
    Post(Post),
}

impl PublishResult {
    fn into_pending_post(self) -> Option<PendingPost> {
        use PublishResult::*;
        match self {
            PendingPost(v) => Some(v),
            _ => None,
        }
    }

    fn into_post(self) -> Option<Post> {
        use PublishResult::*;
        match self {
            Post(v) => Some(v),
            _ => None,
        }
    }
}

impl PendingPost {
    fn approve(&mut self) {
        self.approvals += 1;
    }
    fn reject(self) -> DraftPost {
        DraftPost { content: self.content }
    }
    fn publish(self) -> PublishResult {
        if self.approvals > 1 {
            PublishResult::Post(Post { content: self.content })
        } else {
            PublishResult::PendingPost(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn publish_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.request_review();
        pending.approve();
        pending.approve();
        let post = pending.publish().into_post().expect("not a post");
        assert_eq!(post.content(), "ashish first post");
    }

    #[test]
    fn reject_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let pending = draft.request_review();
        let mut again_draft = pending.reject();
        again_draft.add_text(".. after first one..");
    }

    #[test]
    fn two_approvals_workflow() {
        let mut draft = Post::new();
        draft.add_text("ashish first post");
        let mut pending = draft.request_review();
        pending.approve();
        pending
            .publish()
            .into_pending_post()
            .expect("Not a pending post");
    }
}


As your code presently stands, you don't need the derived Factory classes.  They don't do anything different from each other, so they can all be handled by a concrete base class.
class PlayerFactory:

    def __init__(self, goal_keeper_class, defender_class):
        self._goal_keeper_class = goal_keeper_class
        self._defender_class = defender_class

    def create_goalkeeper(self):
        return self._goal_keeper_class()

    def create_defender(self):
        return self._defender_class()

player_factory = {
    "Football": PlayerFactory(FootballGoalkeeper, FootballDefender),
    "Hockey": PlayerFactory(HockeyGoalkeeper, HockeyDefender),
}

Example Usage:
>>> player = player_factory["Hockey"].create_defender()
>>> type(player)
<class '__main__.HockeyDefender'>
>>> player.play()
I'm playing hockey!
>>>

If there is some aspect of the factories which actually do something different, and thus necessitate separated derived classes, you'll need to include that in your question.


Performing an ID check on a person and saving the result

You can use a mocking library, like MOQ, to "intercept" calls to _identityAuthenticationRepository, thus removing the physical database from the equation. And you want to do this because you do not want to be testing the Web Service. All you care about is what this code does with a given returned response.

It is troubling that you have catch (SqlException ex) at this level. Why is this not done in the repository? Besides separation of concerns, it blows the whole idea of an abstract repository out of the water.

Your concerns about "too long" methods seems arbitrary to me. LogAndDoCheck() may be "too long", but why? It's not so much "too long" as it is not understandable. Not without reading all the code carefully. It needs to be structured to express what's happening "at this level of abstraction". In other words, Your "Description of..." suggests what the method should look like:

 public ... LogAndDoCheck() {
     var identityThingy = VerifyLocally();

     if(!identityThing.Verified)
         identityThingy = VerifyRemotely();

     if(!identityThingy.Verified)
         throw new InvalidUserException(identityThingy.ToString());
 }

The method is not arbitrary made short. It's short because of the layering of abstract functional details.

It is also shorter because we got the repository out of the way. Of course you gotta call the repository eventually, but that method is now shorter too. And put the SqlException catching there too. That obviously is the best place to capture any available details like parameter values.

And exception handling might better be done by try { LogAndDoCheck(); } catch ....

P.S.

Instead of setting the IdentityCheck to null, have a property or other way of asking the object if the identity is invalid. That way you have the properties it was built with - user entry stuff I imagine - at hand and that can be included in Exception.Data.


This looks a bit unclear:

const int one = 1;

It's primarily used as the option_value argument of setsockopt().  Consider renaming this to something more clear so that it doesn't leave readers confused.
In addition to your other error-checking, you can also check the return value of socket() and print its error in case it fails.
A little nit-picky, but you can just initialize fd after the command line check instead of declaring it first and then assigning to it:

int fd = setup_socket();


I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)

var tree = data.reduce(function(tree, item) {
    var tempTree = tree;
    for(var i=0;i<item.length;i++){
        if(!tempTree[item[i]])
            tempTree[item[i]] = {};
        tempTree = tempTree[item[i]];
    }
    return tree;
}, {});


Just some things that jump out at me:

Standard VBA Naming conventions have camelCase for local variables, and PascalCase only for sub/function names and Module/Global Variables. This allows you to tell at a glance if the variable you're looking at is local to your procedure, or coming from somewhere else.

I would probably use EncryptUsingCaesarCypher as your function name. It's more descriptive and closer to what it actually does.

`Text = CaesarCypher(text)

versus

`Text = EncryptUsingCaesarCypher(text)

Other than that, your naming is pretty solid.

Why separate functions for ShiftLeft and ShiftRight? The code in both is heavily-repeated and could be easily combined into a Shift(ByVal shiftValue as Long) function that handles positive and negative. This also lets you cut out all that messing around with isPositve and Abs(shift)


Just a simple idea: From each pair, you generate both the smaller and the bigger prime. You're using a Set in order to assure that you don't output both. But this can be done much simpler:

Instead of

            long revrse = reversePrime(prime);
            if ((!(prime == revrse))
                    && (!reversedCheckedPrime.contains(revrse))
                    && (reversedCheckedPrime.size() <= MAXLISTSIZE)) {
                reversedCheckedPrime.add(prime);
            }

use

            long revrse = reversePrime(prime);
            if (prime < revrse) {
                reversedCheckedPrime.add(prime);
            }

You simply add the smaller one only (which also handles the case of -self-reversed numbers). The test

 reversedCheckedPrime.size() <= MAXLISTSIZE

was both wrong (should be <) and useless (as there's a break later).

Now you can replace the Set by a List and gain some speed. You can gain even more, if you use a long[] of length MAXLISTSIZE (which should be called MAX_LIST_SIZE) as you avoid autoboxing.


My implementation of FixedSizedPriorityQueue

The following is used multiple times and it could be extracted out:

if (!sorted) {
    Collections.sort(list, comparator);
    sorted = true;
}

to a helper method:

private void sortIfNeccessary() {
    if (sorted) {
        return;
    }
    Collections.sort(list, comparator);
    sorted = true;
}

Note the guard clause.
List.remove returns the removed elements.

Double value = list.get(0);
list.remove(0);

The code above could be simplified to this:

final Double value = list.remove(0);

The comparator could be substituted with the reverseOrder method/comparator:

Collections.sort(list, Collections.reverseOrder());

The list could be final. final helps readers, because they know that the reference always points to the same instance and it doesn't change later. https://softwareengineering.stackexchange.com/questions/115690/why-declare-final-variables-inside-methods but you can find other questions on Programmers.SE in the topic.
Furthermore, its type could be only List<Double> instead of ArrayList<Double>. See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces
The print method violates the single responsibility principle. Other clients may want to write the elements to a log file or a network socket so you shouldn't mix the queue logic with the printing. I'd consider creating a List<Double> getElements method (which would return a copy or unmodifiable version of list to make sure that malicious clients does not modify the inner state of the queue) or providing an iterator to clients and move the print method to another class.
Does it make sense to create a queue with negative capacity? If not, check it and throw an IllegalArgumentException.
Actually, it does not work with capacities less than 2. It throws a java.lang.ArrayIndexOutOfBoundsException: -1 when the capacity is 1 because of the list.get(capacity - 2) call. (Effective Java, Second Edition, Item 38: Check parameters for validity)

public FixedSizedPriorityQueue(final int capacity) {
    if (capacity < 2) {
        throw new IllegalArgumentException("Illegal capacity: " + capacity);
    }
    ...
}

Instead of

if (list.size() == 0) ...

you could use

if (list.isEmpty()) ...

It's the same but easier to read.


Removing unneeded objects from an array before rendering

I think the current code is just fine from an efficiency standpoint. The overhead of a single small object is essentially nothing. Even if 1000 such objects were created and then got GC'd every time the button was clicked, on any remotely modern device, the performance impact would almost certainly be imperceptible.
If you really wanted to be more efficient, it might be very slightly more efficient to use a rotating modulo index that gets used to assign the new object instead of re-shuffling the array indicies with unshift, but with only 5 elements in the array, it's not something worth worrying about. Better to worry about performance tweaks only if

The improvement is easy to implement and doesn't make the code harder to read, or
You've tested the script on a low-end device and know that something isn't running as fast as it should - in which case you should run a check to see what section(s) of the code are causing the bottleneck(s), and then work on improving only those bottlenecks.

IMO, anything else is premature optimization - your efforts are better spent elsewhere, such as making the code clean and readable, which usually matters far more than performance.
And there are a number of improvements you could make on the code quality front:
Use const by default - only use let when you must reassign the variable name. Using const makes the code more readable when one can identify at a glance that something isn't going to be reassigned.
Avoid inline handlers - they have a whole bunch of problems, including a demented scope chain which virtually requires global pollution, mixing page content with presentation, and ugly escaping issues. When you have an event listener you want to attach to an element, better to use addEventListener.
Abstract iteration When iterating, unless you actually need to work with the index, it's more abstract and more readable to work with the element being iterated over directly instead. For example, rather than particles[i].width, it'd be nicer to use particle.width, or even just width extracted from the particle. You can do this by invoking Array#forEach or the array's iterator.
ID You have <canvas id="context" width="800" height="500"></canvas>. But the canvas is not the 2d context - giving the element an ID of context is somewhat misleading. Also, IDs create global variables by default, unfortunately, which can sometimes lead to hard-to-understand bugs. You can select the canvas with querySelector('canvas') instead. (If you had a larger page and collisions were possible, you could give the element unique classes instead; classes do not create global identifiers.)

const button = document.querySelector('button');
button.addEventListener('click', addParticle);

const ctx = document.querySelector('canvas').getContext("2d");
const particles = [];

function addParticle() {
  particles.push({
    x: Math.random() * 800,
    y: Math.random() * 500,
    width: Math.random() * 100 + 50,
    height: Math.random() * 100 + 50,
    color: '#' + Math.floor(Math.random() * 16777215).toString(16)
  });

  if (particles.length > 5) particles.shift();

  draw();
}

function draw() {
  ctx.clearRect(0, 0, 800, 500);
  particles.forEach(({ color, x, y, width, height }) => {
    ctx.fillStyle = color;
    ctx.fillRect(x, y, width, height);
  });
}
<button>Add</button>
<canvas width="800" height="500"></canvas>


Your one-liner is too unreadable for my taste.  Furthermore, neither version actually works.

The fundamental obstacle to elegance is that the problem requires you to look ahead one element to interpret how to handle the current element.

def random_document(document_layout, type_, **kwargs):
    def internal_comprehension(document):
        full_dict = {}
        for i in range(len(document)):
            if isinstance(document[i], list):
                # This item should have already been processed in a previous
                # recursive call to internal_comprehension()
                pass
            elif i == len(document) - 1 or not isinstance(document[i+1], list):
                # This item is an independent item
                full_dict.update({document[i]: random_item(type_, **kwargs)})
            else:
                # Next item is a list, so create a level of nesting
                full_dict.update({document[i]: internal_comprehension(document[i+1])})
        return full_dict
    return internal_comprehension(document_layout)

On the other hand, if you iterate through the document_layout backwards, then you don't have a look-ahead problem.  Here's how it could look like:

def random_document(document_layout, type_, **kwargs):
    dict = {}
    iter = reversed(document_layout)
    for k in iter:
        if isinstance(k, list):
            dict[iter.next()] = random_document(k, type_, **kwargs)
        else:
            dict[k] = random_item(type_, **kwargs)
    return dict


Instead of all the if-else statements, you could use a switch statement, like so:

switch (x) {
  case 15:
    int y = z/10000000000000;
    if (y==34||y==37)
    ...
    ...
    ...
    break;
  case 13:
...
...
...
  default:
    printf("INVALID\n");
}

Also to make your code look cleaner, eliminate any curly brackets around if  statements that execute only one statement, for example,

if (l%10==0)
{
        return true;
}

could be:

if (l%10==0) return true;

Additionally, instead of

if (y==51||y==52||y==53||y==54||y==55)

use

if (y>=51&&y<=55)


Merge arrays in objects in array based on property

A short review;

This code looks incredibly complicated for what you want to achieve, sometimes a few for loops beat the functional approach
array is a global variable (not var or set or const), that is a bad thing
If a function is not inline, I would encourage you to use the function keyword
I am not sure mergeLines is a great name, perhaps mergeIds ?

array = [{
    id: 1,
    items: [1, 2, 3]
  },
  {
    id: 2,
    items: [1, 2]
  },
  {
    id: 1,
    items: [4]
  },
  {
    id: 3,
    items: [1]
  },
];

function mergeIds(list){
  const out = [];
  for(entry of list){
    const existingEntry = out.find(o => o.id === entry.id);
    if(existingEntry){
      existingEntry.items = existingEntry.items.concat(entry.items);
    } else {
      out.push(entry);
    }
  }

  return out;
}

console.log(mergeIds(array));


sets perform containing checks (w in visited) \$O(1)\$ rather than \$O(n)\$ for lists.
collections.deque are better than lists for poping elements at the front (popleft).
you should put your example code under an if __name__ == '__main__' clause.
w as a variable name does not convey meaning, you should try to come up with something more explicit.

import collections

def breadth_first_search(graph, root):
    visited, queue = set(), collections.deque([root])
    while queue:
        vertex = queue.popleft()
        for neighbour in graph[vertex]:
            if neighbour not in visited:
                visited.add(neighbour)
                queue.append(neighbour)

if __name__ == '__main__':
    graph = {0: [1, 2], 1: [2], 2: []}
    breadth_first_search(graph, 0)

Given a growing number of comments indicating that the code does not return anything, I’d like to add that, yes, this code does not process nodes: it only traverse the graph and you're likely to want to add your own custom logic to process each node. As your mileage may vary (building a traversal list, finding the first node that satisfies a condition, etc.), there is not a "one code fits all" approach, but a useful first approximation would be to yield each node as they are traversed:

import collections

def breadth_first_search(graph, root):
    visited, queue = set(), collections.deque([root])
    while queue:
        vertex = queue.popleft()
        yield vertex
        visited.add(vertex)
        queue.extend(n for n in graph[vertex] if n not in visited)

if __name__ == '__main__':
    graph = {1: [2, 4, 5], 2: [3, 6, 7], 3: [], 4: [], 5: [], 6: [], 7: []}
    list(breadth_first_search(graph, 1))  # [1, 2, 4, 5, 3, 6, 7]

Note that this alternative iteration also takes care of the bug mentioned in this answer


Build script for an operating system written in C++

Instead of repeated statements like this:

echo "==============================================="

I suggest adding a helper function, for example:

print_hr() {  # hr - as in horizontal rule
    echo "==============================================="
}

The advantage of this is if you later decide to change the length of the = in the line, you can change it in one place.

Instead of entering into sub-directories with cd dirname and later stepping back with cd .., I recommend to use sub-shell environments with (...). For example, instead of this:

cd include
rm *.o
scons
# Move all Object Files into Build Directory
cp *.o ../build
cd ..

Do like this:

(
    cd include
    rm *.o
    scons
    # Move all Object Files into Build Directory
    cp *.o ../build
)

Notice that there is no more cd ...
Working directory changes in a (...) sub-shell environment are only in effect within.

This maybe a matter of taste, but I find that the many comment lines like this are just noise, and make the script hard to read, I suggest to remove them:

# ----------------------------------------------------------------------------------------------


Let's start with the BUG.

if (entity.Count() == 0 || entity == null)

If entity is null, then you'll get a NullReferenceException when Count is called, so there's currently no possible way the second half of this statement will ever be called. I think you meant to do this.

 if (entity == null || entity.Count == 0)

Which works, but isn't great. I would prefer "not Any" here. I find it's good practice to get into the habit of using Any. It's just more readable IMO.

if ( entity == null || !entity.Any() )

To clarify. Any() returns as soon it finds an element, whereas Count has to iterate over the entire Enumerable before it returns.

Note that this isn't true for List. Any() still returns early when called on a List, but so will Count because a list keeps track of how many items it has as they're added/removed. Enumerables do not already "know" how big they are. They must be iterated to get a count.

Now let's back up a bit and stop your Linq from scrolling off the screen.

var entity = repository.Table
                 .OrderBy(c => c.ID)
                 .Skip(pageNo * pageSize)
                 .Take(pageSize);

Maybe it's because I "grew up" with a language where everything is passed ByRef by default (.Net passes ByVal by default), but I don't like assigning values to arguments.

public virtual HttpResponseMessage Get(int pageNo, int pageSize)
{
    pageNo = pageNo > 0 ? pageNo - 1 : 0;
    pageSize = pageSize > 0 ? pageSize : 0;

I'd introduce another variable, but I'm having a hard time thinking of good names at the moment. I'd also consider extracting the logic into private methods to clarify the intent. It doesn't matter that you're unlikely to ever call them from anywhere else, some well named methods can really clarify what code is doing. You can always look inside them if you're interested in the implementation, but at this level, I don't care how we're calculating these numbers, I just care that we are.

public virtual HttpResponseMessage Get(int pageNo, int pageSize)
{
    pageNo = NormalizePageNo(pageNo);
    pageSize = NormalizePageSize(PageSize);

Here's another great opportunity to give logic a name.

int pageCount = total > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0;

Mmmm hmmm... Now what is that doing exactly?

  If the total number of records is greater than zero,
    Then return the percentage of total divided by page size, rounded up
    Else return Zero.

Again, these are implementation details. At the current level of abstraction, we just want to know

int pageCount = CalculatePageCount(total, pageSize);


Count solutions of a equation with a constraint

Repeating work

Suppose one test case were 9747 and another test case were 9748.  Right now, you do the full work for each test case, throwing away the work done for other test cases.  This causes your program to take a long time if there are many large test cases.

There is a way to compute all the answers for each of the 10000 test cases in one computation, so you can immediately find the answer to any test case instantly after that.

Sieve-like algorithm

This algorithm works similar to the Sieve of Eratosthenes.  It loops through each (x,y,z) combination and increments count[n] by one.  Once that is done, count[n] is the answer for any test case n.

#include <stdio.h>

#define MAX        10000
int counts[MAX+1];

int main(void)
{
    int x, y, z, n;

    // For each (x,y,z) combination, increment counts[n] by one, where
    // n = x*y + x*z + y*z, or in other words: n = x*y + z*(x+y)
    for (x = 0; x <= MAX; x++) {
        for (y = 0; y <= x; y++) {
            int sum = x+y;
            for (z = 0, n = x*y; z <= y && n <= MAX; z++, n += sum) {
                counts[n]++;
            }
        }
    }

    // Read test cases and print out answers.
    do {
        scanf("%d", &n);
        if (n == -1 || n > MAX)
            break;
        printf("%d\n", counts[n]);
    } while(1);

    return 0;
}

Timing comparison

The sieve program takes 0.04 seconds on my computer no matter how many test cases are thrown at it.  The original program took 0.03 seconds for the sample input shown (3 test cases), but it took 0.56 seconds to handle a test input of 20 large test cases (9900..9919).  So as you can see, the original program is \$O(n)\$ on the number of test inputs when it could be made to be \$O(1)\$ using the sieve method.


Custom ostream for a println-like function

I'll review more later but a basic comment first.

Rather than write just the println_buf class I would also write the println_stream class that internally has a println_buf.

class println_stream: std::ostream
{
    // Make this a private class.
    // You don't need to leak implementation details.
    // As far as anybody else is convered it is just std::streambuf
    class println_buf { /* STUFF */ };

    println_buf     buf;
    std::streambuf* oldBuf = nullptr;
    public:
        println_stream()
            // You can't pass the buf to the ostream constructor
            // here as it has not been constructed yet.
            // There are ways but lets keep it simple for now.
        {
            // I did not do the work with logfunc
            // Have not read that bit yet.
            // But you get the idea I hope.
            oldBuf = rdbuf(&buf);
        }
        ~println_stream()
        {
            // Can't remember if it is required.
            // But I would always set back the original buffer.
            rdbuf(oldBuf);
        }
};

int main()
{
   println_stream stream;
    stream << "Hello world\n";
}


I would suggest that rather than try parsing strings all through your code, try this.

The code below creates a couple of new things. a numeric coordinate structure, a scenario, which is a pair of coordinates, and a list of scenarios.

There are also a couple of functions to parse the text file and each chess location into coordinates. Further down the line, it makes thing easier when you come to checking the queen and king locations.

Module Module1
    Structure Coord
        Dim Rank As Integer
        Dim File As Integer
    End Structure

    Structure Scenario
        Dim King As Coord
        Dim Queen As Coord
    End Structure

    Dim Scenarios As New List(Of Scenario)
    Dim fileContents() As String
    <STAThread>
    Sub Main()
        Const PATH = "C:\Temp\kingqueen.txt"
        fileContents = System.IO.File.ReadAllLines(PATH)
        ParseTextFile()
        Dim result As String = ""
        For Each testScenario As Scenario In Scenarios
            result = result & TestLines(testScenario) & " "
        Next
        result.Trim()
        Console.WriteLine(result)
        Console.ReadLine()
    End Sub

    Private Function ParsePieceLocationAsCoord(chessCoord As String) As Coord
        Dim tempPoint As New Coord
        tempPoint.File = Asc(chessCoord(0)) - 96
        tempPoint.Rank = Val(chessCoord(1))
        Return tempPoint
    End Function

    Private Sub ParseTextFile()
        Scenarios.Clear()
        For Each line As String In fileContents
            Dim newScenario As Scenario
            newScenario.King = ParsePieceLocationAsCoord(line.Substring(0, 2))
            newScenario.Queen = ParsePieceLocationAsCoord(line.Substring(3, 2))
            Scenarios.Add(newScenario)
        Next
    End Sub

    Private Function TestLines(testScenario As Scenario) As String
        With testScenario
            If .King.Rank = .Queen.Rank Or .King.File = .Queen.File Then
                Return "Y"
            Else
                Return TestDiagonals(testScenario)
            End If
        End With
    End Function

    Private Function TestDiagonals(testScenario As Scenario) As String
        With testScenario
            If (.King.Rank + .King.File = .Queen.Rank + .Queen.File) Or (.King.Rank - .King.File = .Queen.Rank - .Queen.File) Then
                Return "Y"
            Else
                Return "N"
            End If
        End With
    End Function


Ternary tree preoder traversal (recursive implementation)

Class Definition

First of all, I would separate the class definition from the actual use case. The challenge wants you to walk nodes with integer data, but a next challenge may ask you to use a string instead. Don't let the use case stipulate the class definition. Let's make a generic class to make the tree reusable for more scenarios.

public class TernaryTree<T>
{
    public T Data { get; set; }
    public TernaryTree<T> Left { get; set; }
    public TernaryTree<T> Right { get; set; }
    public TernaryTree<T> Middle { get; set; }
}

DRY Code

You then present a method PreOrderTraversal which combines walking the tree with outputting data for this use case. It's a pitty the flow is not split from the use case. We would have to rewrite that flow for every single use case like this. Let's keep it DRY.

We want to have a non specific flow for traversing the tree pre-order, middle, left, then right.

public IEnumerable<TernaryTree<T>> WalkPreOrder()
{
    yield return this;
    foreach (var descendant in Middle?.WalkPreOrder())
    {
        yield return descendant;
    }
    foreach (var descendant in Left?.WalkPreOrder())
    {
        yield return descendant;
    }
    foreach (var descendant in Right?.WalkPreOrder())
    {
        yield return descendant;
    }
}

Use Case

And now we can reuse that method for our use case. This code should not be part of TernaryTree but rather of our unit test, or container class for the challenge:

 static void Print(TernaryTree<int> tree)
 {
     foreach (var node in tree.WalkPreOrder())
     {
         Console.WriteLine(node.Data);
     }
 }

Unit Tests

I noticed a comment in your code // manually verify the console output is 1 2 22 3 33 4 5. You can avoid manually checking the outcome by writing unit tests.

What's Next?

Since you can set any node to any of the child positions, you might introduce cycles. Suppose you set node.Left = node, this would be a cycle because of a self-to-child reference. As a challenge, you should try to figure out how to prevent cycles.

public TernaryTree Left   { get; set; }
public TernaryTree Right  { get; set; }
public TernaryTree Middle { get; set; }


The explanation for slowness is simple: you're doing a slow operation (reading a file) many many times (due to combinatorial explosion).

How many permutations of "hello" are there? For 5 items, there are 5!, or 120 permutations. However, two of the letters are indistinguishable, so it's actually \$\frac{5!}{2!}\$, or 60. Add the 12 permutations of "hell", 24 permutations of "helo", and 12 permutations of "hllo", and we have about a hundred.

Of those, I would expect only maybe a dozen to be valid English words.

Then, for each permutation, you are opening the file and reading every line to see if the candidate is a word. File IO involves the operating system and the disk — both very expensive.

Generating all permutations of something is costly. In contrast, checking whether two given words are permutations of each other is a simple matter of counting.

A smarter approach, therefore, would be to go through the dictionary once, and check whether each word meets the acceptance criteria.


A beginners implementation of Game of Life

First of all, please try to reformat the Python code according to Python's style guide (PEP 8).

When programming, it is important to give meaningful names to all variables (with exception to some loop indexes). What is a? Or taille1? My strong believe is, that even "research" kind of programming can benefit from this advice. Try using good Python IDE, eg, PyCharm, which will help to autocomplete names. Programs are read by humans.

It's better to convert user input to the proper type immediately, no need to do it each time in while loop. Similarly, it makes program more readable if input/output is separated from computations.

Also, I do not quite understand why do you want deep copy the matrix each time. Perhaps, more efficient strategy is to have two arrays and alternate them.

As for the computational part, I'd suggested the following simplification:

instead of computing the sum or surrounding cells several times, do it just once. You can add current cell multiplied by eg 10 so the sum will be a single parameter.

You can also have precomputed rules:

RULES = {
    1: 0,
    2: 0,
    3: 1,
    4: 0,
    ...
    10: 0,  # tens indicate current cell
    12: 1,  # continues to live
    13: 1,  #
    14: 0,  # dies due to overpopulation
    15: 0,
    ...
}

Then deciding cell's fate can be done very efficiently:

matrix[x, y] = RULES[weighted_sum]

Of course, this is quite small optimization, but it makes possible to implement any cellular automaton by just changing rules in one place.

Also, pay attention to border conditions. Padding of zeros on each side is needed for the algorithm to work correctly.

Offtopic note: The question made me nostalgic: I remember how still a schoolboy I've found a BASIC program for the Game of Life in Peter Atkins's book "The Second Law" (I read it in translation), and wondered how inefficient implementation it had. Border conditions were checked for each neighbor instead of padding zeros. I do not remember now how the sum was calculated, but this answer actually repeats my idea from that time - single array lookup (in Basic). In Python, of course, there are dicts for O(1) computation.


An interface ResetableCounter that supports the message void reset() in addition to those of Counter.

Your professor provides this statement to you as a hint. It is practically saying ResetableCounter should extends Counter interface.

make countVariable or count(as @200_success suggested) private. As no other outside class should have any permission to change the count.


Simplifying `if` statements in Tic Tac Toe function

There should only be eight ways to win; you have nine ReportWin()s.  This one got listed twice:

fieldA2.GetState == state && fieldB2.GetState == state && fieldC2.GetState == state

Considering that you've named your squares as independent variables, there's not much you can do to generalize CheckWin().  Start by turning the board into an  array or two-dimensional array, then read the advice in Tic-Tac-Toe design .  Personally, I like the suggestion to list all eight winning configurations, as it results in the least code.


Can someone have a look to my Chess Project?

The first thing I noticed are the escaping orgies. Both HTML and JavaScript allow you to use either ' or " to quote strings. Don't use the same for both and you can get rid of all those ugly backslashes.

You can also get rid of the (badly-named) bol variable. You already have a loop variable so you can use j % 2 == 0 or even simpler j & 1 to determine if the number is even or odd.


To your question ( confirmed by the comments ), you are not polluting the namespace because you are

Wrapping already inside $(document).ready(function() {
Using var for every variable.

Furthermore, from what I can see that is left over from rotator, it was probably a better approach than what you have now.

From a once over:

Spelling is important: infiniateLoop -> infiniteLoop
slideToggle(800, function() {}); can simply be written as slideToggle(800);
You could use a ternary for increasing currenItem : currentItem = currentItem == numberOfItems - 1 ? 0 : ++currentItem;
Please remove commented out code, also please re-indent after taking out rotator
It is considered good practice to have one big var at the start instead of multiple vars:

var $accordionList = $('.accordion').find('li'),
    numberOfItems = $accordionList.length,
    currentItem = 0;

    // Set first item to active
  $accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800);

Jshint could not find a single flaw


There are few redundancies, both time and memory wise.

You don't need to maintain an entire visited set. It is only necessary for a general graph. For the grid, the wave computed at the previous iteration serves equally good.
Upon completion of bfs_next, both wave and bfs_que contain the same set of points. You don't need to update wave in the loop. Do wave = set(bfs_que) once, after the loop terminates. Since set is a built-in primitive, this should run faster.
I am not sure that dequeue is a right tool. The for _ in range(size) loop effectively drains it every time, and there is no need to store the new wavefront in the same structure with the old one. Consider using two lists instead.

Also, for the clarity of the algorithm, I'd seriously consider reworking bfs_next into a generator, yielding the next wavefront.

All that said, I am not convinced that len(wave) > len(blocked) means escape. In fact, correct me if I am wrong, when 9 blockers cut off the corner

   |*
   | *
   |  *
   |  3*
   | 323*
   |32123*
   |210123*
   |32123  *
   | 323    *
   +----------

the length of the third wavefront is 10. However, there is no escape.


Calculating numbers in the Collatz sequence

Test it

You are asking which one is faster, but did you actually test it yourself?  I'm sure if you did you would find out.

Math.pow()

In your second solution, just using Math.pow() is slower than the entire first solution, probably by an order of magnitude.  I'm not sure why you think using a single if statement would be slower than calling an extremely complicated function (which probably contains lots of if statements).

Avoiding Math.pow

You can compute \$(-1)^n\$ by using the 1 bit, like this: -(2*(n & 1)-1).  So you can change your second solution to:

n = ( (7 * n + 2) + (2*(n & 1)-1) * (5 * n + 2) ) / 4;

This version would be very similar in runtime to the first solution.  I couldn't tell you which would be faster.  I'm also not sure if the division by 4 here will be optimized away.  You may want to convert that into a shift by 2 instead:

n = ( (7 * n + 2) + (2*(n & 1)-1) * (5 * n + 2) ) >> 2;


Is there any way to shorten up this Facebook API call?

I haven't worked with Facebook's API using queries like this, but I know SQL inside and out, and this screams INNER JOIN to me.

var joinedQuery = "SELECT Photo_Tag.pid,Photo_Tag.xcoord,Photo_Tag.ycoord,Photo.src_big FROM photo_tag AS Photo_Tag INNER JOIN photo AS Photo ON Photo_Tag.pid = Photo.pid WHERE Photo_Tag.subject = {{mystery.uid}} ORDER BY RAND() LIMIT 1;";

Also, the use of ORDER BY RAND() is going to be inherently slow (especially with a system as large as Facebooks), so might I recommend something more like this:

var joinedQuery = "SELECT Photo_Tag.pid,Photo_Tag.xcoord,Photo_Tag.ycoord,Photo.src_big FROM photo_tag AS Photo_Tag INNER JOIN photo AS Photo ON Photo_Tag.pid = Photo.pid INNER JOIN (SELECT (MAX(pid) * RAND()) AS pid FROM photo_tag WHERE Photo_Tag.subject = {{mystery.uid}}) AS MaxId ON Photo_Tag.pid = MaxId.pid WHERE Photo_Tag.subject =  {{mystery.uid}} ORDER BY Photo_Tag.pid ASC LIMIT 1";

Written to be more readable, that query is:

SELECT Photo_Tag.pid
    ,Photo_Tag.xcoord
    ,Photo_Tag.ycoord
    ,Photo.src_big
FROM photo_tag AS Photo_Tag
INNER JOIN photo AS Photo ON Photo_Tag.pid = Photo.pid
INNER JOIN (
    SELECT (MAX(pid) * RAND()) AS pid
    FROM photo_tag
    WHERE Photo_Tag.subject = {{mystery.uid}}
) AS MaxId ON Photo_Tag.pid = MaxId.pid
WHERE Photo_Tag.subject = {{mystery.uid}}
ORDER BY Photo_Tag.pid ASC
LIMIT 1;

Using ORDER BY RAND() requires querying every row to build a new "randomness" ID, creating and populating a temporary table with this newly randomized result set, and then querying from that table to bring back your row. For large datasets, this can be very slow.

By instead JOINing the table back onto itself with random pids generated, then ORDERing and LIMITing that dataset, it can result in a much faster query. This article explains in (enormous) detail what I mean, but also shows that a query such as the one above will be faster with a table holding as little as 100 rows, and will be no slower than the original query in any case.

Even if you don't get rid of ORDER BY RAND(), your reduction to a single query should speed up your call.


Synchronous loop with internal asynchronous calls

You can do this manually with a counter along these lines (kind of messy):

function getAddresses(members, callback) {
  var addressList = [];
  var count = 0;

  for (var i = 0; i < members.length; i++) {
    service.member.info({
      name: members[i],
      company: "Cerberus",
    }, function(body) {
      addressList[i] = body.address;
      count++;

      if (count === members.length) {
        callback(addressList);
      }
    });
  }
}

There are also libraries for this sort of thing, like async:

var async = require('async');

function getAddresses(members, callback) {
  async.map(members, function (member, callback) {
    service.member.info({
      name: member,
      company: "Cerberus",
    }, function (body) {
      callback(null, body.address);
    });
  }, callback);
}

But promises are really the best option if you’re able to use them consistently throughout your project, with a library like bluebird:

var bluebird = require('bluebird');

// This only works if the callback is really (err, body)
bluebird.promisifyAll(service.member);

function getAddresses(members) {
  return bluebird.map(members, function (member) {
    return service.member.infoAsync({
      name: member,
      company: "Cerberus",
    }).then(function (body) {
      return body.address;
    });
  })
}

They could take some learning, but they’re the future of asynchronicity in JavaScript or something, since right now you can do this (or you could, if service.member.info returned a promise) – note how close it is to your original loop:

var bluebird = require('bluebird');

var getAddresses = bluebird.coroutine(function* (members) {
  var addressList = [];

  for (var i = 0; i < members.length; i++) {
    var body = yield service.member.info({
      name: members[i],
      company: "Cerberus",
    });

    addressList.push(body.address);
  }

  return addressList;
});

// or, to run the loop in parallel:

var getAddresses = bluebird.coroutine(function* (members) {
  var operations = [];

  for (var i = 0; i < members.length; i++) {
    operations.push(
      service.member.info({
        name: members[i],
        company: "Cerberus",
      })
    );
  }

  return (yield operations).map(body => body.address);
});

and one day, that might be simplified to this, but not yet:

async function getAddresses(members) {
  var addressList = [];

  for (var i = 0; i < members.length; i++) {
    var body = await service.member.info({
      name: members[i],
      company: "Cerberus",
    });

    addressList.push(body.address);
  }

  return addressList;
}


Given any positive range, count the values that are complete squares

Your algorithm is inefficient:

Floating-point arithmetic is slower than integer arithmetic.
To find all the perfect squares in a range, you need only find the square root of the minimum (and round up) and the square root of the maximum (and round down).

You should be able to find the answer in constant time, with no looping.


Bash script to set up an ad hoc wireless network

Not answering your actual question, but offering a couple of code comments:

use cd -- "$(dirname -- "$0")"

if the script is in the PATH and someone just enters the script name, you will try to cd to the (probably non-existant) "script name" directory in the current dir.

use grep -q $DEVICE

that is a bit speedier since, if it finds a match, it exits immediately instead of having to read the entire input looking for all matches.


Merging two Excel sheets by matching on two columns

If no one offered a suggestion, I have found a way to handle this. This makes it blazing fast:

Sub Verify()
Dim c As Range, last3 As Long, last4 As Long, last5 As Long
Dim wt As Worksheet, ws As Worksheet, wc As Worksheet
Set wt = Sheets("Temp"): Set ws = Sheets("Source"): Set wc = Sheets("Combined")
Application.ScreenUpdating = False

last3 = wt.Cells(Rows.Count, 1).End(xlUp).Row
last4 = ws.Cells(Rows.Count, 1).End(xlUp).Row
last5 = wc.Cells(Rows.Count, 1).End(xlUp).Row

wc.Cells.ClearContents ' Clear Contents
wt.Range("G2").Resize(last3 - 1, 1).Formula = "=C2&D2"
ws.Range("G2").Resize(last4 - 1, 1).Formula = "=C2&D2"
ws.Range("H2").Resize(last4 - 1, 1).Formula = "=MATCH(G2,Temp!$G$2:$G$" & last3 & ",0)"

' Copy & Format Headers
wt.Range("A1:E1").Copy wc.Range("A1")

' Copy All Data from Temp
wt.Range("A2:E" & last3).Copy wc.Range("A2")

' Copy Selected Data from Source
    For Each c In ws.Range("H2:H" & last4)
        If IsError(c) Then
          last5 = wc.Cells(Rows.Count, 1).End(xlUp).Row
    wc.Range("A" & last5 + 1).Resize(1, 5).Value = ws.Range("A" & c.Row).Resize(1, 5).Value
    End If
    Next c
' Clean temp Columns
Application.DisplayAlerts = False: wt.Columns("G").Delete: ws.Columns("G:H").Delete
Application.DisplayAlerts = True: Application.ScreenUpdating = True
End Sub


Generic C++ exception catch handler macro

In the catch block, you can rethrow the exception. This can be done in a function:

int rc = 0;
try{
// statements that can throw
}catch(...){
    HandleException(rc, "Extra info to append to logged exception message");
}

void HandleException(int rc, std::string msg)
{
    try{
        throw;
    }catch(Poco::Exception &e){
        // ...
    }catch( const std::exception &e){
        // ...
    }
}


The code does not account for negative numbers, yet the number type (int) allows them. The program will print 1 for the input -15 10, although 5 is the correct answer.
The GCD is usually positive, but your program will print -10 on the input -10 10.
A function int gcd(int, int) will make it easier to test and re-use.
Since you provided a complete program you probably want to check whether the user actually inputs two numbers and not tree 0.1234 or something else that's not an int.

That being said, thank you for

not using namespace std;
properly indenting your code (you could add braces around the if, though)
using proper names where they were reasonable (n1 and n2 aren't long-lived enough)

I guess that you know that there are better algorithms, so for a simple algorithm like this there is not much to improve. You certainly have to consider negative numbers, though.

Also, some variables are available for the whole scope (n1 and n2), but only used for a short time. Try to limit the scope of a variable as much as possible, as it prevents errors like

for(i = 2; i <= n1 / 2; ++i) // should have been "smaller", whoops


Stack implementation in C++ using linked list

Bug

Your main issue is memory management.

You did not implement the "Rule of Three" (you can google it).

The problem is that if you do not define the copy constructor or the assignment operator the compiler will generate these methods for you automatically. Under most conditions these generated methods work correctly. BUT when your class contains an "Owned" pointer they do not work.

Note: An "Owned" pointer is a pointer you are responsible for deleting.

{
    stack<int>   x;
    x.push(12);

    stack<int>   y(x);  // Copy constructor used.
                        // The default implementation does a shallow copy
                        // of each member from x into y.
                        // This means that x and y point at the same list.

}
// Here your destructor has destroyed the same list twice.
// This is a bug.

To fix this you need to define the copy constructor and assignment operator. But there is a nice pattern that allows you to define the assignment operator in terms of the copy constructor. Look up the "Copy And Swap Idiom".

You need to add the following to your class:

class stack
{
    // Stuff
    public:
        stack(stack const& rhs)
            : head(copyList(rhs.head))
            , size(rhs.size)
            , max(rhs.size)
        {}
        stack& operator=(stack const& rhs)
        {
            stack tmp(rhs);            // make a copy using copy constructor.
            swap(tmp);                 // swap the tmp and this object
            return *this;
        }
        void swap(stack& other) noexcept
        {
            using std::swap;
            swap(head, other.head);
            swap(size, other.size);
            swap(max,  other.max);
        }

    private:
        node* copyList(node* l)
        {
            if (l == nullptr) {
                return null;
            }
            return new node{l->data, copyList(l->previous)};
        }
    // STUFF
};

Your pop() has a bug. You delete the NEW head item before returning but leak the original head item.

T pop() {
    if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");

    T item = head->data;
    head = head->previous;     // You just leaked the old head.
                               // You need to keep a pointer to the old head

    --size;

    delete head;               // So you can delete the old head here.
    return item;
}

Other Stuff

Design of pop()

You make your pop() method return the top value and remove it from the stack. This is fine if your T type is simple. But if T is a complex type there is no way to do this safely (and maintain "Strong Exception Guarantee"). So most implementations of stack split this into two separate functions. A top() that returns the top value and a pop() that simply removes the top value.

So I would rewrite this:

void pop() {
    if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");

    node* old = head;
    head = head->previous;

    --size;
    delete old;
}
T const& top() {
    if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");

    return head->data;
}

Return by reference

Your pop() and peek() return the result by value. This is OK for simple types of T (like integer). But if T is a complex object you are making a copy of this complex object. Instead you should return a reference to the object. If the user is doing somehting simple they can do the action without copying if they want to keep a copy they can make that decision and save the value in a local variable.

T peek()

// Change to:

T const& peek();   // Don't really need this if you have top()
                   // Or you could use peek instead of top()

But notice the const& as the return type. You are returning a reference to the object so no copy is made. If you need a local copy then you can save it like this:

int   val = x.top();
x.pop();


Compressor number or real
When you are write_counting, you are writing the ASCII number characters to the new file. However, when you go to decompress this file, how are you going to differentiate between the actual content in the file and the numbers that mark the occurrences of a character?
A possible solution for this might be to just write the number itself to the file (no ASCII). That way, when you encounter a number that is ASCII, you can be almost sure that the number is part of the content (that is, unless there was a letter that occurred so many times in a row that the counter rose into the '0'-'9' range).

Two ones or twelve?
This is kind of a continuation from the top one. Let's say your compressor went to go compress this file:

12

Now, I am ready to decompress it. Since your compressor writes a number to show occurrences of a character, the output would be this:

1121

How do I know if all of those numbers are part of the content?
The only fix I can think of, unfortunately, would be to follow the above tip and write 0x01 instead of an ASCII number.

Misc

while (EOF != (current_char = getchar())

You are missing a brace here.

if (printf("%ull", count) < 0)

When compiling your code, I get this on this line:

warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘uint64_t’ [-Wformat=]

This also showed a problem that two ls are written after the number that shows how many character occurrences there were.


Finding the index of the character whose removal will make a palindrome

Code Style

As @coderodde also remarked, you should import specific classes.  Wildcard imports are for throw-away code and early development; no later than when your code is approaching completeness, you should replace any then-remaining wildcard imports with specific imports.  There are tools that can help you with that.

Also, format your code consistently.  Your indentation and placement of spaces are irregular.  I find code much easier to read when there are spaces on each side of every binary operator, but if you prefer not to use such spaces then at least be consistent!

I/O

For what it's worth, unlike @coderodde, I have no problem with BufferedReader for your input.  For input whose form is so simple, Scanner does not provide much advantage.

Performance

This is the main area of concern, and indeed I do not find it surprising that your code ...

        for(int i=0;i<sb.length()&&flag==0;i++){
            StringBuffer s = new StringBuffer(sb);
            s.deleteCharAt(i);
            if(isPalindrom(s.toString())){
                System.out.println(i);
                break;
            }
        }

... does not perform well.  Regardless of the details of the palindrome-checking algorithm, it is performing far more work than it needs to do when used this way.  In particular, it is very wasteful to test every deletion candidate, and it is slightly wasteful to test separately whether the full string is already a palindrome.  For each string it tests, your code may perform work proportional to the square of the length of the string.

Instead of testing every possible deletion, simply scan each test string from both ends until you find a pair of corresponding characters that differ.  If the string can be made a palindrome by deleting a single character, then that character will be one of those two.  They are the only candidates you need to consider.  By limiting yourself to considering only those as deletion candidates, the maximum amount work performed by your code is only linear in the length of the string.  (Also, if every corresponding pair of characters matches, then the string is already a palindrome, so you don't need to perform a separate check for that.)


This code is pointless since it creates async state machine while the code you execute is actually synchronous code.
So eventually you get a performance penalty for the creation of a state machine but no reward of asynchronous execution.
Consider using async and await when you're dealing with IO operations. Usually, such methods already provide asynchronous API. You can spot this as such methods return Task or Task<T>


Here are my suggestions:

Nodes, Edges: most of the time the function's parameters don't start with big letter. nodes and edges are more preferable.

Also consider to restraint the possible range of these variables. uint or even smaller like ushort might be a better fit for your use case.

throw new Exception: It is good that you do preliminary checks. Usually the preferred Exception type is ArgumentException (1) to indicate that you have a problem with the calling parameters.

adjacencyMatrix: You don't need to zero all of the entries inside this matrix because by default their value will be zero. (int is a value type with a default value 0).

If you wish to clean the array, because you have received that for example via a parameter then you can use the built-in Array.Clear (1):
Array.Clear(adjacencyMatrix, 0, adjacencyMatrix.Length);

random.Next(0, i): Alternative: random.Next() % i

random.Next(1, 10): Alternative: new Random().Next() * (10 - 1) + 1 (1)

placedEdges++: instead of increasing it every time you could initialize it with the proper value: int placedEdges = Nodes -1;

fromVertex and targetVertex:

fromVertex + toVertex
OR sourceVertex and targetVertex would

give more convenient naming.


Showing jQuery UI tooltip on focus of text box

The demo is seen here

$('.tooltip').each(function () {

    //title can be fetched directly from the element. I know no bugs for to
    //require the use of `attr()`. This removes several function calls.

    //No need to get the element by id since the current elements you are iterating
    //over each are the same DOM elements you are trying to attach events to. The
    //`this` in here is where you attach events.

    //You are appending the content to the parent, landing the span next to input.
    //Instead of doing that, you can use `insertAfter()` which inserts the object in
    //context after  the specified element, which is the current object in the
    //`each()`. It also accepts a DOM element so no need to wrap it in jQuery.

    var t = $('<span />', {
        title: this.title
    }).insertAfter(this).tooltip({
        position: {
            of: '#' + this.id,
            my: "left+190 center",
            at: "left center",
            collision: "fit"
        }
    });

    this.title = '';

    //Now the only need to wrap the current object this is here, when we attach events.

    //Since the event methods are merely shorthands of `on(eventName,fn)`, we use
    //`on()` instead to lessen function calls. Also, it allows a map of events, which
    //results in calling `on()` only once.

    $(this).on({
        focusin: function () {
            t.tooltip('open');
        },
        focusout: function () {
            t.tooltip('close');
        }
    });
});