Finding neighbors and returning average value from neighbors

Just a few things I want to point out before tackling this:

Based on the comment, your first condition is flipped.  You're skipping valid entries instead of invalid entries.  It should be:

if (!salesRecord.IsValid)

Your last condition in the loop could just break at that point.  Since it is sorted, every valid item will be a match but you're only interested in the first.
You should consider making UnitPrice of type decimal.  You're dealing with currency here so you should not be using double.

Using a little bit of LINQ here could make this more readable IMHO.  It's easier to think of it as "looping through the list of candidate records" rather than "looping through all records and skipping some of them."

Personally, I would write the last set of conditions as I have shown using the conditional operator.  You may or may not like it this way or this structure so your choice with that part.

public class SalesRecord
{
    public DateTime Date { get; set; }
    public bool IsValid { get; set; }
    public int SalesType { get; set; }
    public decimal UnitPrice { get; set; }
}
public class SalesDataContainter
{
    private SortedList<DateTime, SalesRecord> salesData;
    private decimal GetInferredPrice(SalesRecord inferredSalesRecord)
    {
        Func<SalesRecord, bool> isValidRecord = record =>
            record.IsValid                                          //neigbor needs to be valid
            && record.SalesType == inferredSalesRecord.SalesType;   //has to have the same sales type
        var candidateRecords = salesData.Values
            .SkipWhile(record => !isValidRecord(record))
            .Where(isValidRecord);

        SalesRecord closestBefore = null;
        SalesRecord closestAfter = null;
        foreach (var salesRecord in candidateRecords)
        {
            //get the last found for before neighbor
            if (salesRecord.Date < inferredSalesRecord.Date)
            {
                closestBefore = salesRecord;
            }
            //get the first found for after neighbor
            else if (salesRecord.Date > inferredSalesRecord.Date)
            {
                closestAfter = salesRecord;
                break;
            }
        }

        // there's a neighbor before
        if (closestBefore != null)
        {
            return (closestAfter != null)
                // we have neighbors on both sides
              ? (closestBefore.UnitPrice + closestAfter.UnitPrice) / 2M
              : closestBefore.UnitPrice;
        }
        else
        {
            return (closestAfter != null)
                // there's only a neighbor after
              ? closestAfter.UnitPrice
              : 0M;
        }
    }
}

An alternative would be to let LINQ do all the work:

public decimal GetInferredPrice(SalesRecord inferredSalesRecord)
{
    Func<SalesRecord, bool> isValidRecord = record =>
        record.IsValid                                          //neigbor needs to be valid
        && record.SalesType == inferredSalesRecord.SalesType;   //has to have the same sales type

    return salesData.Values
        .SkipWhile(record => !isValidRecord(record))
        .Where(isValidRecord)
        .GroupBy(
            record => record.Date.CompareTo(inferredSalesRecord.Date),
            record => record.UnitPrice as decimal?,
            (key, g) => (key < 0) // assumes no records will have equal dates
                ? g.LastOrDefault()
                : g.FirstOrDefault()
        )
        .Average() ?? 0M;
}


A few suggestions:

Each cell in the Game of Life has exactly two states: dead or alive. Unless you plan to implement -1 as undead, I'd suggest you use booleans instead of integers to indicate the state.
The int i[] is a bit odd; i is normally used for indices, not for whole rows.
In countSurrounding you are using Exceptions to count the surrounding living cells. This is wasteful and unnecessary; we can determine the correct bounds ourself.

Given an index i in an array row, we can get the lower index min and the upper index max by

int minRow = i == 0 ? 0 : i - 1;
int maxRow = i == (row.length - 1) ? (row.length - 1) : i + 1;

The same thing for columns (j index in an array column):

int minCol = j == 0 ? 0 : j - 1;
int maxCol = j == (column.length - 1) ? (column.length - 1) : j + 1;

This itself assumes that i and j always are inside the bounds. We can then loop over the surrounding cells like

for (int row_idx = minRow; row_idx <= maxRow; row_idx++) {
   for (int idx = minCol; idx <= maxCol; idx++) {
     if (board[row_idx][idx] && !(row_idx == i && idx == j)) { // assumes board is implemented with booleans
        count++
     }
   }
}

While this is longer, this doesn't abuse exceptions for something totally non-exceptional.
The printBoard is fine, except for my first two criticisms. The if/else can be condensed to a ternary; I'd find this easier to read:

for (boolean row[] : board) {
   for (boolean cell : row) {
      System.out.print( cell ? "#" : "." );
   }
   System.out.println();
}

In main, you initialize nextBoard with the initial board, then copy it over into board. This is slightly useless. I'd propose to refactor your main into a method boolean[][] nextGeneration(boolean[][] board). Your main would then look like

int[][] initialBoard = ...;
public static void main(String[] args) {
   int[][] board = new int[nextBoard.length][nextBoard[0].length];
   // copy over the initial board
   for (int i = 0; i < initialBoard.length; i++) {
      for (int j = 0; j < initalBoard[i].length; j++) {
         board[i][j] = initialBoard[i][j];
      }
   }
   // loop over 25 generations
   printBoard(board);
   for (int gen = 0; gen < 25; gen++) {
      System.out.println("\nGeneration " + gen);
      board = nextGeneration(board);
      printBoard(board);
   }
}

Now something is becoming obvious: We have collected a few static methods that operate on our board array. This is a sign that we should create a seperate class:

Board
========
- board: boolean[][]
--------
- countSurrounding(i: int, j: int): int
+ toString(): String
+ nextGeneration(): Board

The class could be easily extended to have a static default board, or a constructor that creates a random board.
Each “Game of Life” can be described by a ruleset like 23/3. The digits before the slash determine when a living cell stays alive, the digits after the slash determine when a new cell is born. Generalizing nextGeneration to be able to play with all possible rules is a nice exercise.

private boolean nextCellState(int i, int j) {
   int count = countSurrounding(i, j);
   int rules[] = board[i][j] ? stayAlive : birthNew;
   for (int rule : rules) {
      if (rule == count) {
         return true;
      }
   }
   return false;
}

then

public Board nextGeneration() {
   boolean next[][] = new boolean[board.length][board[0].length];
   int rows = board.length;
   int cols = board.[0].length;
   for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
         next[i][j] = nextCellState(i, j);
      }
   }
   return new Board(next);
}


Is there a more performant way to get thread-safety for this data structure?

It all depends on how the list will be used. Just a few examples:

Reads are more common than writes - use separate read/write locks.
Average list is short - use copy-on-write array instead of linked list.
Average list is long - use more efficient search method.
Lots of threads access list - use mutex instead of spinlock to avoid wasted cycles.
Lots of elements is added/removed in bulk - use external lock.

Have you actually measured performance in real world scenarios and identified bottlenecks? It looks like most of it is prematurely optimized.

__attribute__((always_inline))

Is this really necessary? Does it bring any measurable performance gain?

while (__sync_lock_test_and_set(lock, 1))
    while (*lock)

I do not understand this second while loop. Why are you checking the value twice?

#define MY_LISTLOCK_LOCK MYSpinLock *MY_macro_lock = &(list->_lockLL); MYSpinLockLock(MY_macro_lock)
#define MY_LISTLOCK_UNLOCK MYSpinLockUnlock(MY_macro_lock)

Avoid macros which can be replaced with functions.

MYBool

Use bool from stdbool.h.


Matrix to calculate effects using delta method

Aren't you looking for a simple matrix multiplication? Try:

x <- as.matrix(dpcp[c("x1", "x2", "x3", "x4")])

Then

marg_effects <- x %*% t(m4)

or equivalently (maybe a little faster):

marg_effects <- tcrossprod(x, m4)


Some minor changes to improve readability:

It's generally considered better practice to use str.charAt(0) instead of str[0] (even though str[0] often outperforms .charAt()).
Simplify the while condition and have it only check if p > 0; the character checks can be done inside the loop. This also lets you eliminate the if (p > 0) check.
Add some comments.

You could also incorporate p-- into your while loop (so it would read while (p-- > 0) { but that wouldn't improve readability.

wrapType(str) {
        if (str.length > 16) {
            // if string is longer than 16 characters
            var p = 16;
            while (p > 0) {
                // loop through the string and check each char
                if ((str.charAt(p) === " " || str.charAt(p) === "-") {
                    // if a dash or space is found, wrap the string
                    var left = (str.charAt(p) === "-") ? str.substring(0, p + 1) : str.substring(0, p);
                    var right = str.substring(p + 1);
                    return left + "\n" + this.wrapType(right);    // return the wrapped string
                }
                p--;
            }
        }
        return str;    // return the original string
}

If you wanted to take it further, you could create a small function to do the character-checking called breakHere or something similar that would return true if it found a dash or space, and false otherwise.  Then for your if checks, instead of checking for both the dash and space, you could just do something like if (breakHere()) { ... } which would make for slightly longer code but might make it easier for someone new to follow what's going on.  You could even have that function return the value itself, so you could call newStr = breakHere(); and newStr would either be assigned the wrapped string (if a dash or space was found) or the original string (str).  That would allow you to combine your two separate return statements into one -- return newStr.


Correctness

Files over 10240 bytes will fail to download because the streams are closed after one iteration of the while loop(Edit: Was paste error by OP). As of java 7, it is highly preferable to use a try-with-resources block when working with AutoCloseable objects.

Implementation

Wrapping your FileOutputStream in a BufferedOutputStream would be preferable to manually flushing.

Performance

You may see some performance gain by running each file download on its own thread. You'd need to take your existing code and move much of it into a Runnable or Callable. Use an Executor to perform some or all of the downloads concurrently.

If you made these modifications, the code might look more like:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class FileDownloader {

    // or newFixedThreadPool() to control the number of threads.
    private final ExecutorService executor = Executors.newCachedThreadPool();

    public FileDownloader() {
        super();
    }

    public void downloadPdf(final URL targetUrl) throws IOException {
        final File destination = File.createTempFile("download-pdf-" + System.currentTimeMillis(), ".pdf");
        this.executor.submit(new DownloadCallable(targetUrl, destination));
    }

    private static final class DownloadCallable implements Callable<File> {

        private static final int BUFFER_SIZE = 1024 * 1024;

        private final URL targetUrl;
        private final File destination;

        public DownloadCallable(final URL targetUrl, final File destination) {
            this.targetUrl = targetUrl;
            Objects.requireNonNull(targetUrl);

            this.destination = destination;
            Objects.requireNonNull(destination);
        }

        @Override
        public File call() throws IOException {
            final URLConnection request = this.targetUrl.openConnection();
            try (final InputStream inputStream = request.getInputStream();
                    final FileOutputStream fileStream = new FileOutputStream(this.destination);
                    final BufferedOutputStream outputStream = new BufferedOutputStream(fileStream, BUFFER_SIZE);) {

                final byte[] data = new byte[10240];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, bytesRead);
                }
            }
            return this.destination;
        }
    }
}


Elegant approach to building unordered list from XML

The part that looks most problematic in your code is the if statement: the code in the if part and the else part is almost the same except that you prepend urlPrefix to the URL if it is relative. (Also you're only checking whether the node is the last if the URL is relative, which does not seem right). At the very least I'd factor this out into a helper method, which takes the absolute URL as a parameter to remove the code duplication.

However there's an even better way: .net already comes with the System.Uri class, which can take care of making the URL absolute for you.

private void LoadNavigation()
{
    Uri urlPrefix = new Uri("http://mysite.com");
    string xmlFilePath = ConfigurationManager.AppSettings["NavigationUrl"].ToString();
    XmlDocument doc = new XmlDocument();
    doc.Load(xmlFilePath);
    XmlNodeList navigationItems = doc.DocumentElement.FirstChild.ChildNodes;

    foreach (XmlNode item in navigationItems)
    {
        Url fullUrl = new Uri(urlPrefix, item.Attributes.GetNamedItem("url").Value);
        String title = item.Attributes.GetNamedItem("title").Value;
        navList.InnerHtml += "
 " + title + "";

        if (item.NextSibling == null)
        {
            navList.InnerHtml += "
"; //last item in list
        }
        else
        {
            navList.InnerHtml += "|
"; //not the last item in list
        }
    }
}


Handling of memorystream with streamwriter efficiency

It looks like you are wasting your efforts on premature optimization. Which also results in a quite ugly code.

I think you should separate your grid-filling logic from csv export. There should be no memory streams, steam writers, etc. in your first method. Also notice that you have code duplication in it, so you might want to extract label creation logic to separate method. Ideally you'd want to remove this logic all together and use WPF ListView (or ItemsControl) with data-binding instead.

As for your second method - you do not need any buffers. Just iterate through your data, create strings and write them directly to your FileStream. You might also want to encapsulate this logic in some separate class and perform it in the background thread so your UI does not freeze for large data.


Reading from and writing to a file without passing around filename

you could use a teereader:

inr, inw := io.Pipe()
f, _ := os.Create(name)
tr := io.TeeReader(inr, f)
return tr, inw

use this code in go routine and handle errors


isPalindrome is a very unfortunate name in this code:

Names starting with "is" are typically methods returning a simple boolean
... but in this code isPalindrome is a parameterless method returning a boolean array
... and at the same time there is also a boolean array called isPalindrome

It would be better to use different names for the method and the array,
and neither should start with the word "is".

In the isPalindrome method, you could shorten this:

        if (checkForPalindrome(i)) {
            isPalindrome[i] = true;
        }

to this:

        isPalindrome[i] = checkForPalindrome(i);

I'm a big fan of descriptive variable names,
but I think you went a bit overboard, for example here:

private static int getPalindromeCount(int startNo, int endNo) {
    int totalPalindromeFound = 0;
    for (int i = startNo; i <= endNo ; i++ ){
        if(isPalindrome[i]){
            totalPalindromeFound++;
        }
    }
    return totalPalindromeFound;
}

I would simplify some of the names there to:

private static int getPalindromeCount(int start, int end) {
    int palindromeCount = 0;
    for (int i = start; i <= end; i++) {
        if (isPalindrome[i]) {
            palindromeCount++;
        }
    }
    return palindromeCount;
}

The numbers 100001 and 100000 are magic.
It would be good to create a constant from 100000 with a descriptive name.

A small tip: it's a lot easier to parse simple input using a Scanner, with its nextInt and nextLine methods,
instead of a BufferedReader and Integer.parseInt.

Also, why build output in a StringBuilder if you will print its contents anyway inside the same method.
You could just print the results directly.


Reusing thread and UdpClient for sending and receiving on same port

I find a better naming convention for private fields on a class is _PascalCase or _camelCase. This makes it easy to see whether you are using a field or a local variable.
It is completely unnecessary to create a new Thread to call StartListening. The thread will terminate once udpClient.BeginReceive() has been called as this is async. You might as well call StartListening() directly in PrepareClient().
UdpClient is IDisposable and should therefor be disposed when not needed anymore. You do not clean up the existing UdpClient at all.

The answer to this question indicates that when you call Dispose or Close on a socket then the callback is invoked but will throw an ObjectDisposedException when calling EndReceive . Because you are storing the currentAsyncResult you can probably get around this by changing StartListening() to this:

private readonly object _clientLock = new object();

private void StartListening()
{
    lock (_clientLock)
    {
        if (udpClient != null)
        {
            currentAsyncResult = null;
            updClient.Dispose();
        }
        udpClient = new UdpClient();
        udpClient.ExclusiveAddressUse = false;
        udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpClient.Client.Bind(localEP);

        var s = new UdpState(localEP, udpClient);
        currentAsyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s);
    }
}

Plus you should lock the inner block of your receive callback. This should ensure that you don't kill the client in the middle of receiving.


malloc and realloc live in cstdlib. malloc.h is not a standard header, neither in C++ nor in C, and should not be relied on in any case.
Also, you're missing #include <utility> for std::move.
Legacy C functionality, as everything else from the standard library, lives in the std namespace, if you include the corresponding <cheader> files. While you can also include the C standard headers via <header.h>, this is highly discouraged. With the first option, names may also exist in the global namespace, but this is not guaranteed and should not be relied on.
Your malloc and realloc functions need not be inline. In fact, inline does nothing here; remove it.
You don't need to check for null pointers when freeing memory. Passing a null pointer to free is always well defined and does nothing.
You don't need to move out all the data members from other in your move constructor. All of those members are trivial to copy, and have no special move behavior.
The move assignment operator invokes undefined behavior. You cannot just call the destructor of an object and then write to its members. Calling the destructor completely ends the lifetime of the object; afterwards, there's nothing there to write to. Furthermore, this is a kind of anti-pattern; in almost all cases, the move assignment operator should be implemented via the copy-and-swap idiom.
push_back is broken. You call change_capacity with the result of std::min(m_capacity * 2, 1), which is either 0 or 1, in any case. Most likely, you'd want to use std::max instead.
if (m_size + 1 > m_capacity) looks strange to my eyes. I would just write if (m_size >= m_capacity).
pop_back should definitely return a value. It's not very useful otherwise.
Since you're going for what seems to be a std-like container interface, you should add a little more functionality. For one, you're missing some of the usual type definitions, such as iterator and const_iterator. Furthermore, some sort of emplace mechanism would be appropriate, as well as some way to clear the container and some functionality to shrink it, as well as some other things.
You should make sure that memory is properly initialized. As a user, I would expect that it's safe to access every element in bounds; however, you are not initializing memory at all, leaving that job to the user. I'd expect memory to be default- or zero-initialized; making use of std::calloc should do the trick (alternatively, you can also just std::memset the area).
I would make your malloc and realloc functions a little bit more useful. As of right now, the onus of checking whether allocation succeeded is put on the user of those functions, but in my opinion it would be much cleaner and safer to lift those functions to a "C++-safe" level, i.e. make them check the return value of the underlying allocation call directly and convert that into an exception directly.
std::is_pod is being deprecated, in accordance with the standard library moving away from the term POD as a whole. Also, the requirement that T must be a POD type is too strict; your vector will still work correctly if T is trivial.


I'd:

exclude unnecessary duplication (List.filter etc.)
drop separate match rule for the list of one element
rely on type inference
use more succinct form of pattern matching

Something like this:

let rec qsort = function
    | [] -> []
    | x::xs -> let lt, ge = List.partition ((>) x) xs
               qsort lt @ x :: qsort ge


Harvard CS50 Problem Set 1: greedy change-making algorithm

The first thing that sticks out to me is indentation.  But I'm going to recommend some other changes, so I'll address indentation last.

Let's give our variables some better, more descriptive names, and let's declare our constants as constants.  And since we're taking in a floating point number for input from the user, we need to compare that with other floating point numbers.  Or we need to use it as an integer.

int const kVALUE_QUARTER = 25;
int const kVALUE_DIME = 10;
int const kVALUE_NICKEL = 5;
int const kVALUE_PENNY = 1;

float userInput = -1.0;
int balance = 0;
int coinCount = 0;

do {
    printf("please give balance owing: ");
    userInput = GetFloat();
} while (userInput < 0);

balance = (int)(userInput * 100.0);

Now, we can eliminate all of our loops using the modulo operator (%) and integer division.

// number of quarters:
coinCount += balance / kVALUE_QUARTER;
balance %= kVALUE_QUARTER;

// number of dimes:
coinCount += balance / kVALUE_DIME;
balance %= kVALUE_DIME;

// number of nickels:
coinCount += balance / kVALUE_NICKEL;
balance %= kVALUE_NICKEL;

// number of pennies:
coinCount += balance / kVALUE_PENNY;
balance %= kVALUE_PENNY;

Now let's put it all together and take a look at our indentation:

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <math.h>

int main(void) {
    int const kVALUE_QUARTER = 25;
    int const kVALUE_DIME = 10;
    int const kVALUE_NICKEL = 5;
    int const kVALUE_PENNY = 1;

    float userInput = -1.0;
    int balance = 0;
    int coinCount = 0;

    do {
        printf("please give balance owing: ");
        userInput = GetFloat();
    } while (userInput < 0);

    balance = (int)(userInput * 100.0);

    // number of quarters:
    coinCount += balance / kVALUE_QUARTER;
    balance %= kVALUE_QUARTER;

    // number of dimes:
    coinCount += balance / kVALUE_DIME;
    balance %= kVALUE_DIME;

    // number of nickels:
    coinCount += balance / kVALUE_NICKEL;
    balance %= kVALUE_NICKEL;

    // number of pennies:
    coinCount += balance / kVALUE_PENNY;
    balance %= kVALUE_PENNY;

    printf("the number of coins needed is: %i\n", count);
    printf("balance after coins paid: %i\n", balance);
}


When a request arrives, one thread downloads it and the remaining operations are dependent on download so it needs to wait for download to finish. But there can be many request coming and download tasks must run at the same time but each process operation need to wait for its own download task.

That does sound like you want it in the same thread, like a "standard" webserver actually. A request is routed to a thread which handles that request from start to finish. No waiting or synchronizing involved. These threads can also easily be pooled.

    int i = 0;
    while (i < 3) {

I find it curios that you've chosen a while over for here.

        try {
            Thread.sleep(6000); // mock for real operation
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

AS a note, you most likely want to exit here. The InterruptedException is being thrown when the Thead has been asked to stop doing whatever it does, so you don't want to ignore it most of the time.

    t.start();
    receiver.requestBomb();

Mind you that the Thread might not have started at this point. start does start the thread, obviously, but whether it has already executed something when your logic reaches the next instruction is undefined. Whether receiver.setRequestListener(...) has been called when you call threadBomb is undefined, might not have been.

Your code looks and reads fine, actually. It's well written, however, it is unnecessarily complicated, or at least I'm failing to see why you need to do it this way.
What would make sense is to have a single thread pool for processing, which is being fed by a single queue. A little pseudo-code for that:
Queue processingQueue = new BlockingQueue();

class RequestReceiver {
    public void onRequestReceived(Reqquest request) {
        processingQueue.add(request);
    }
}

class ProcessingThread {
    public void run() {
        while (aliveCondition) {
            Request request = processingQueue.poll();
            download(request);
            process(request);
        }
    }
}

This scheme is in, some form or another (rather another), also used by servers and webservers to process requests. You spin up multiple ProcessingThreads and have them wait for something to do, and after being done, they go back into the idle state.
If you now require different threads for download and processing, you're just adding a another queue, like this:
Queue downloadingQueue = new BlockingQueue();
Queue processingQueue = new BlockingQueue();

class RequestReceiver {
    public void onRequestReceived(Reqquest request) {
        downloadingQueue.add(request);
    }
}

class DownloadingThread {
    public void run() {
        while (aliveCondition) {
            Request request = downlaodingQueue.poll();
            download(request);
            processingQueue.add(request);
        }
    }
}

class ProcessingThread {
    public void run() {
        while (aliveCondition) {
            Request request = processingQueue.poll();
            process(request);
        }
    }
}

    t.start();
    receiver.requestBomb();

Mind you that the Thread might not have started at this point. start does start the thread, obviously, but whether it has already executed something is undefined. The


OOP design for multiple user authentication

First of all, I am not at all sure it is good idea to learn OOP by re-implementing security-sensitive feature for a web-framework, which already has support for such things. Please, at least consider using Flask-Security, Flask-Login, Flask-Principal unless you plan a total rewrite of all those. Also, I see plain text passwords in use - most of the time a security risk.

That said, I can find the following problems:

Persistence service is too intrusive and its logic is not clear.
For example, you are creating a user just to login: Why do you want to
persist anything someone tries to enter as a login attempt? Consider
using some ORM, where you can control object's persistence, or come
up with something better than object dealing with its persistence.

Those aspects better be invisible in the model. In Python, it's probably best to use a DTO (data-transfer object, received from the login form, usually a dict) until identity is verified.
I do not really understand why you are using threads. In the Flask environment one can use a session as an abstraction, so dealing at thread level is strange and can make your code too dependent on a specific implementation, preventing porting it to multiprocessing, async/greenlets and the like.

There are some naming problems (what is ph_no?).

In my opinion the best place for OOP in user authentication is (in addition to User class) a possibility to define different authentication strategies (and inject dependencies like Utils.encrypt that way). Then, if a more complex system is in question - role-based authorization, etc, etc. The code you presented above is not geared towards those goals. Instead, it deals with low-level concerns which are already solved in the framework.


My toy example I build from your snippets:

import numpy as np

def throw_a_coin(N):
    return np.random.choice(['H','T'], size=N)

def make_throws(number_of_samples, sample_size):
    sample_probs = np.zeros(number_of_samples)
    for i in range(number_of_samples):
        num_heads = sum(throw_a_coin(sample_size) == "H")
        sample_probs[i] = float(num_heads) / sample_size
    return sample_probs

sample_sizes = [np.random.randint(1, 1e3) for idx in range(500)]

mean_of_sample_means = np.zeros(len(sample_sizes))
std_dev_of_sample_means = np.zeros(len(sample_sizes))

for i in range(len(sample_sizes)):
    prob = make_throws(200, sample_sizes[i])
    mean_of_sample_means[i] = np.mean(prob)
    std_dev_of_sample_means[i] = np.std(prob)

cProfile (ordered by cumtime) reveals the problem (runs in 82.359 seconds):

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 133/1    0.003    0.000   82.359   82.359 {built-in method builtins.exec}
     1    0.002    0.002   82.359   82.359 fast_flip.py:1(<module>)
   500    0.940    0.002   82.200    0.164 fast_flip.py:8(make_throws)
100000   79.111    0.001   79.111    0.001 {built-in method builtins.sum}
100000    0.058    0.000    2.148    0.000 fast_flip.py:4(throw_a_coin)
100000    1.455    0.000    2.090    0.000 {method 'choice' of 'mtrand.RandomState' objects}
100000    0.207    0.000    0.635    0.000 fromnumeric.py:2456(prod)
100000    0.026    0.000    0.429    0.000 _methods.py:34(_prod)
101500    0.409    0.000    0.409    0.000 {method 'reduce' of 'numpy.ufunc' objects}
     6    0.000    0.000    0.176    0.029 __init__.py:1(<module>)

There is a steep gap after buildins.sum, i.e. you spend most time there. We can use np.sum instead (pushing it down to 3.457 seconds):

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 133/1    0.003    0.000    3.457    3.457 {built-in method builtins.exec}
     1    0.002    0.002    3.457    3.457 fast_flip.py:1(<module>)
   500    0.905    0.002    3.307    0.007 fast_flip.py:8(make_throws)
100000    0.046    0.000    1.869    0.000 fast_flip.py:4(throw_a_coin)
100000    1.287    0.000    1.823    0.000 {method 'choice' of 'mtrand.RandomState' objects}
201500    0.702    0.000    0.702    0.000 {method 'reduce' of 'numpy.ufunc' objects}
100000    0.172    0.000    0.536    0.000 fromnumeric.py:2456(prod)
100000    0.136    0.000    0.532    0.000 fromnumeric.py:1778(sum)
100000    0.023    0.000    0.378    0.000 _methods.py:31(_sum)
100000    0.021    0.000    0.364    0.000 _methods.py:34(_prod)
     6    0.000    0.000    0.178    0.030 __init__.py:1(<module>)

further we can replace the strings "H" and "T" with a Boolean and stay in numpy for longer (down to 1.633 seconds):

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 133/1    0.003    0.000    1.633    1.633 {built-in method builtins.exec}
     1    0.001    0.001    1.633    1.633 fast_flip.py:1(<module>)
   500    0.101    0.000    1.485    0.003 fast_flip.py:11(make_throws)
100000    0.169    0.000    0.893    0.000 fast_flip.py:4(throw_a_coin)
100000    0.724    0.000    0.724    0.000 {method 'uniform' of 'mtrand.RandomState' objects}
100000    0.122    0.000    0.491    0.000 fromnumeric.py:1778(sum)
100000    0.024    0.000    0.354    0.000 _methods.py:31(_sum)
101500    0.334    0.000    0.334    0.000 {method 'reduce' of 'numpy.ufunc' objects}
     6    0.000    0.000    0.178    0.030 __init__.py:1(<module>)

next we can get rid of throw_a_coin and instead sample a numer_of_samples x sample_size array of uniformly distributed random numbers and threshold them. This also allows us to vectorize the for loop and stay in numpy even longer (0.786 seconds):

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 133/1    0.003    0.000    0.786    0.786 {built-in method builtins.exec}
     1    0.003    0.003    0.786    0.786 fast_flip.py:1(<module>)
   500    0.053    0.000    0.634    0.001 fast_flip.py:4(make_throws)
   500    0.526    0.001    0.526    0.001 {method 'uniform' of 'mtrand.RandomState' objects}
     6    0.000    0.000    0.179    0.030 __init__.py:1(<module>)

Here is the code:

import numpy as np

def make_throws(number_of_samples, sample_size):
    # True == Heads
    throws = np.random.uniform(size=(number_of_samples, sample_size)) > 0.5
    sample_probs = np.sum(throws, axis=1) / sample_size
    return sample_probs

sample_sizes = [np.random.randint(1, 1e3) for idx in range(500)]

mean_of_sample_means = np.zeros(len(sample_sizes))
std_dev_of_sample_means = np.zeros(len(sample_sizes))

for i in range(len(sample_sizes)):
    prob = make_throws(200, sample_sizes[i])
    mean_of_sample_means[i] = np.mean(prob)
    std_dev_of_sample_means[i] = np.std(prob)

At this point we could start to tackle the for loop, but it would start to get very micro optimized. One might consider aggregating the results in prob and then using np.mean(prob, axis=1) and np.std(prob, axis=1) outside the loop, but that only nets like 20ms so it's more of a personal preference thing.


Float to Byte Array Serialization Over Network

Endianness matters only if your application (or another one you can communicate with) may run on environments with different CPU architectures. If you write, let's say, a Windows application it will currently run only on little-endian CPUs. Moreover you're designing your own communication protocol then endianness is simply part of your specification. If someone else will write, let's say, a compatible application running on PowerPC (!!!) then she will simply adhere to your protocol...

Also note that floating point were sometimes an exception and they did follow different rules than integers. It's pretty uncommon nowadays and, anyway, it's not something you should care about (see previous paragraph).

My suggestion is then to don't care about endianness and save that few CPU cycles you may need to perform any (unneeded) conversion.

Last point more on-topic with Code Review: you should consider to drop that custom implementation that mimic C union, there already is a fast implementation that performs same task: BitConverter.GetBytes(value) (and its counterpart BitConverter.ToSingle(array, 0)).

Doing this way you may also read a bigger buffer (second parameter of ToSingle() is an offset in array) and this will greatly improve performance (over a byte by byte read or multiple array accesses, each one with its bounds checking).

EDIT: note that if performance in this case are a real (measured) issue and you can have an unsafe assembly then you may pick their implementation dropping arguments checking (in release builds):

unsafe static byte[] GetBytes(float value) {
    var bytes = new byte[4];
    fixed (byte* b = bytes)
        *((int*)b) = *(int*)&value;

    return bytes;
}

If access is synchronized then you may even reuse same buffer:

unsafe static void GetBytes(float value, byte[] bytes) {
    Debug.Assert(bytes != null);
    Debug.Assert(bytes.Length == sizeof(float));

    fixed (byte* b = bytes)
    fixed (float* v = &value)
        *((int*)b) = *(int*)v;
}

Note that if you don't really have any performance problem then I'd keep code easier and verifiable and I'd go with BitConverter. ToSingle() implementation is straightforward.

EDIT: a small performance test (just roughly indicative because it's not your true scenario) averaging 100 executions, repeating each trial Int32.MaxValue times to have a significant execution time, keep this in mind when you compare this values (because you see a big difference only because of this):

BitConverter.ToSingle(): 19 milliseconds
Conversion using union style struct: 16 milliseconds
Conversion using unsafe pointer conversion: 7 milliseconds

Code for unsafe conversion is:

static unsafe float ToSingle(byte[] data, int startIndex) {
    fixed (byte* ptr = &data[startIndex]) {
        return *((float*)(int*)ptr);
    }
}

Vice-versa (same test conditions):

BitConverter.GetBytes(): 28 milliseconds
Conversion using union style struct: 15 milliseconds
Conversion using unsafe pointer conversion: 9 milliseconds


Validating the model outside of the controller in ASP.NET:
Model validation with Data Annotations, the MVC framework will usually automated to handle the performance of actual validation and results to the end-user.
To validate the model outside of controller,we can create a sample of console application into the same application or in other application also.
Here,We are using class named User model:

using System.ComponentModel.DataAnnotations;
namespace ValidateExample
{
    public class User
    {
        [Required]
        [StringLength(20)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(25, MinimumLength = 3)]
        public string LastName { get; set; }

        [Required]
        [EmailAddress]
        public string EmailAddress { get; set; }
    }
}

I have created, within the same Solution, a Console App project.Here's our Console App:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using ValidateExample.Models;

namespace ValidateExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting validation:");

            User user = new User();
            user.FirstName = null;
            user.LastName = "aaa";
            user.Emailaddress = "eg@exam@example";

            var context = new ValidationContext(user, null, null);
            var results = new List<ValidationResult>();

            var isValid = Validator.TryValidateObject(user, context, results, true);

            if (!isValid)
            {
                Console.WriteLine("User is not valid! Errors are:");
                foreach (var validationResult in results)
                {
                    Console.WriteLine(validationResult.ErrorMessage);
                }
            }
            Console.WriteLine("Validation Complete...");
            Console.ReadKey();
        }
    }
}

We simply created a model named User and made some data-annotations in it.Then,In console class We putted some invalid values to test the application.
Here,We called the Validator.TryValidateObject() this function which validate the model according to the data-annotations.
Run the apllication :
The Console Output :-

Starting validation:
User is not valid! Errors are:
The FirstName field is required.    //(as We assigned null to FirstName field)
The EmailAddress field is not a valid email address.


Building a set of all subsets recursively in C++

The recursion - even simulated via std::stack - is indeed unnecessary. Each subset has a corresponding number in \$[0, 2^n)\$ with bits indicating presence of an element in the subset, and each number in \$[0, 2^n)\$ corresponds to a subset. Consider a pseudocode

Set power_set(Set& the_set)
{
    Set result;
    Integral n = the_set.size()
    for (i = 0; i < (1 << n); i++) {
        result.insert(make_subset(the_set, i);
    }
    return result;
}

Set make_subset(Set& the_set, Integral indicator)
{
    Set result;
    Integral n = the_set.size();
    for (i = 0; i < (1 << n); i <<= 1) {
        if (indicator & i) {
            result.insert(the_set[i]);
        }
    }
    return result;
}


What about this:

function isDate18orMoreYearsOld(day, month, year) {
    return new Date(year+18, month-1, day) <= new Date();
}

The month - 1 is required because JS months start at 0.


Invoke is a blocking call that returns only after that call has competed.

That means your loop is also including the time it takes to marshal over to the GUI thread and complete.  You probably don't want that.

I would use BeginInvoke instead, which does not wait for the method to complete on the GUI thread.

This is also the difference between SynchronizationContext methods Post and Send.

I would also prevent await from potentially capturing the current SynchronizationContext using ConfigureAwait(false).

To protect against exceptions if the control is disposed of (happens on form close and for other reasons) I'd add an IsDisposed check.

Finally I would allow this Task to be cancelled as a matter of best practices using a CancellationToken.

private async Task SnoozeAsync(int seconds, CancellationToken token)
{
    for (var i = 0; i < seconds; i++)
    {
        if (token.IsCancellationRequested)
            break;
        BeginInvoke((MethodInvoker)(() =>
        {
            if (!statusLabel.IsDisposed)
                statusLabel.Text = $"Waiting {seconds - i} seconds...";
        }));
        await Task.Delay(1000, token).ConfigureAwait(false);
    }
}


Better approach on handling unexpected string upon converting it to the enum value

All enumerations have a default valueOf(String) method that throw an IllegalArgumentException so your first idea is coherent.

I would say that it depends (..). It depends of your use cases:

If he conversion would be called form an unsafe (user/api) input, then there are chances that you receive an unexpected symbol. And using Optional will force the developer to handle that case more explicitely.
If the convesrion is made from a safe input (code/config), then you can live with the exception.

In the book Effective Java  from Joshua Bloch (Addison-Wesley Professional, 978-0134685991) there is a full chapter on that subject (in the 2nd edition):

  Enum types have an automatically generated valueOf(String) method that
  translates a constant’s name into the constant itself.

  [..]

  The following code
  (with the type name changed appropriately) will do the trick for any enum, so long
  as each constant has a unique string representation:

// Implementing a fromString method on an enum type
private static final Map<String, Operation> stringToEnum
        = new HashMap<String, Operation>();
static { // Initialize map from constant name to enum constant
    for (Operation op : values())
        stringToEnum.put(op.toString(), op);
    }

// Returns Operation for string, or null if string is invalid
public static Operation fromString(String symbol) {
    return stringToEnum.get(symbol);
}

That chapter (and the whole book) is worth the read: CHAPTER 6 ENUMS AND ANNOTATIONS


Making a decorator with arguments in a flat manner

I've found a couple bugs - lack of exception support and it doesn't work with generators. Well, it does in a way, but not the way someone would expect it to.

To fix aforementioned issues, decorator have been changed into this (nevermind Python 2.7 compatibility modifications):

def temp_loglevel(level):
    """
    Decorator to set temporary loglevel for the scope of this function
    (then revert it back on wrapper exit)

    Arguments:
        level: new logging level to set
    """
    logger = logging.getLogger()
    p_closure = dict(func=None)

    def wrapper(*args, **kwargs):
        old_level = logger.level
        logger.setLevel(level)
        try:
            rv = p_closure['func'](*args, **kwargs)
            if isinstance(rv, types.GeneratorType):
                def wrapper_gen():
                    # wrapper's finally block overrides initial setLevel after
                    # returning a generator object
                    logger.setLevel(level)
                    try:
                        for x in rv:
                            yield x
                    finally:
                        logger.setLevel(old_level)

                return wrapper_gen()
            else:
                return rv
        finally:
            logger.setLevel(old_level)

    def wrapper_maker(decorable):
        p_closure['func'] = decorable
        logger.warn(
            "temp_loglevel used, don't forget to "
            "remove it when debugging is done"
        )

        return functools.wraps(decorable)(wrapper)

    return wrapper_maker

P.S. After thinking about how ugly would a flat version of wrapper_gen be, I've made a mental note to myself: "flat is better than nested", but if you absolutely need to make something nested, do it FFS!


My code changes a single RGB value by a set amount, then does the same changes over the other channels

Some style advice and much simpler/shorter/faster solutions.
Style
Your comments break the structure, making the code harder to read. As PEP 8 says:

Block comments [...] are indented to the same level as that code. Each line of a block comment starts with a # and a single space

So
while count <9:
#Creat Pic at the start of each loop
    pic = Image.open(file)
#Convert the image to RGB, so we dont have to deal with the alpha channel
    pic = pic.convert('RGB')

becomes
while count <9:
    # Create pic at the start of each loop
    pic = Image.open(file)
    # Convert the image to RGB, so we dont have to deal with the alpha channel
    pic = pic.convert('RGB')

and I might remove the first comment, as it, unlike the second comment, doesn't contain any insight that's not easily seen in the code anyway.
NumPy
Taking tsh's solution further, to NumPy:
from PIL import Image
import numpy as np

file = "Final/charlie.png"

im = Image.open(file).convert('RGB')
images = []
for channel in range(3):
    for factor in 0.1, 0.5, 0.9:
        data = np.copy(im)
        ch = data[:, :, channel]
        np.multiply(ch, factor, ch, casting='unsafe')
        images.append(Image.fromarray(data))

Image.convert with matrix
Or using convert's matrix parameter:
from PIL import Image

file = "Final/charlie.png"

im = Image.open(file)
images = []
for channel in range(3):
    for factor in 0.1, 0.5, 0.9:
        matrix = [1, 0, 0, 0,
                  0, 1, 0, 0,
                  0, 0, 1, 0]
        matrix[channel * 5] = factor
        images.append(im.convert('RGB', matrix))

Speeds
Using some 575 x 575 sample image, I got roughly these times per new image:

Yours: 2.9 seconds
tsh's: 0.8 seconds
My NumPy one: 0.003 seconds
My convert one: 0.005 seconds


You're doing a lot with .Selection. By default, that is going to be slow. Doing things behind the scenes is always faster. Either way, working with selection isn't the best way to go. Either pass the document to the sub or prompt the user. Is the selection a document, text, body, header, title, section? Be explicit.

The way you use .Find makes me thing you're referring to a range, which can be any of those things. Let's take a look at the basic skeleton of your sub -

    With Selection
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find
    .Find.Execute
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find
    .Find.Execute
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find
    .Find.Execute
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find
    .Find.Execute
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find
    .Find.Execute
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find
    .Find.Execute
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    .Find
    .Find.Execute
End With

Yikes. You're doing the same thing 7 times. At worst that should be refactored. Something like this -

Private Sub AlterRange(ByVal target As Range, ByVal findString As String, ByVal replaceString As String)
    With target
        .Find.ClearFormatting
        .Find.Replacement.ClearFormatting
        .Find
            .Text findString
            .Replacement replaceString
        .Find.Execute Replace:=wdReplaceAll
    End With
End Sub

Now something like this would work

Dim target As Range
Set target = Selection
Dim findStrings(1 To 7) As String
findStrings(1) = "^p^p"
findStrings(2) = "^p"
findStrings(3) = "wvw"
findStrings(4) = "$GPGGA" & "(*)" & "$GPRMC"
'...
Dim replacestrings(1 To 7) As String
replacestrings(1) = "wvw"
replacestrings(2) = ","
'...

Dim i As Long
For i = 1 To 7
    AlterRange target, findStrings(i), replacestrings(i)
Next

All of this is untested, but you get the idea.

What you could do to speed it up is to create a variant (or whatever) to store the entire selection in and then do your finding and replacing in the variant, then place the variant back out to the sheet overwriting the selection.

I don't know how all this would interact with your formatting, but it doesn't seem like you're keeping any formatting so it shouldn't be a problem.


Your examples are pretty useful (especially 'Aardvark'), and should be included in the documentation of the function, ideally as a doctest.  However, the problem is still underspecified: what should happen when a streak of three identical characters is encountered?  Should removeDoubles('eeek') return 'eek' (which is how I would interpret "doubles"), or 'ek' (which is what your code actually does)?

As per PEP 8, the official Python style guide, function names should be lower_case_with_underscores unless you have a good reason to deviate.  Therefore, I recommend renaming the function to remove_doubles.

Obviously, initializing output to ' ' and then dropping it with output[1:] is cumbersome and inefficient.

Fundamentally, this operation is a fancy string substitution.  Typically, such substitutions are best done using regular expressions.  In particular, you need the backreferences feature:

  Backreferences in a pattern allow you to specify that the contents of an earlier capturing group must also be found at the current location in the string. For example, \1 will succeed if the exact contents of group 1 can be found at the current position, and fails otherwise. Remember that Python’s string literals also use a backslash followed by numbers to allow including arbitrary characters in a string, so be sure to use a raw string when incorporating backreferences in a RE.

  For example, the following RE detects doubled words in a string.

>>>
>>> p = re.compile(r'(\b\w+)\s+\1')
>>> p.search('Paris in the the spring').group()
'the the'

For my interpretation of "doubles":

import re

def remove_doubles(string):
    """
    For each consecutive pair of the same character (case-insensitive),
    drop the second character.

    >>> remove_doubles('Aardvark')
    'Ardvark'
    >>> remove_doubles('bookkeeper')
    'bokeper'
    >>> remove_doubles('eELGRASS')
    'eLGRAS'
    >>> remove_doubles('eeek')
    'eek'
    """
    return re.sub(r'(.)\1', r'\1', string, flags=re.I)

To preserve your implementation's behaviour:

import re

def deduplicate_consecutive_chars(string):
    """
    For each consecutive streak of the same character (case-insensitive),
    drop all but the first character.

    >>> deduplicate_consecutive_chars('Aardvark')
    'Ardvark'
    >>> deduplicate_consecutive_chars('bookkeeper')
    'bokeper'
    >>> deduplicate_consecutive_chars('eELGRASS')
    'eLGRAS'
    >>> deduplicate_consecutive_chars('eeek')
    'ek'
    """
    return re.sub(r'(.)\1+', r'\1', string, flags=re.I)


you should move the states list outside of view, i.e. to model class.

class User < ActiveRecord::Base
  STATES = ['AL', 'AK', 'ID']
end

then in view:

<%= f.label(:state, "State:*") %>

<%= f.select(:state, User::STATES) %>

This will allow you to reuse states collection anywhere across the application and add easily validate if user hasn't modified the form manually.

Keeping states in User model is not necessary the best option but it's outside of this question scope


Okay, so let's forget about syracuses2 because using ifs is indeed slower and let's stop depending on Unix which makes things less portable and slightly more difficult to compile.

let time f x =
    let t = Sys.time() in
    let fx = f x in
    Printf.printf "Execution time: %fs\n" (Sys.time() -. t);
    fx

let syracuse x =
    let rec aux x t =
        match x with
            | 1 -> t
            | x ->
                if x mod 2 = 0 then
                    aux (x / 2) (t + 1)
                else
                    aux (3 * x + 1) (t+1) in
     aux x 0

let rec iterate_over n f l =
     if n = 0 then l else iterate_over (n-1) f ((f n)::l)

let syracuses n = iterate_over n syracuse [] ;;

time syracuses 100000 ;;

This takes 0.4s on my machine and 0.03s when compiled (ocamlopt syracuse.ml && ./a.out).

Keep in mind that integer arithmetic is about twice as slow as in C because integers in OCaml are tagged. Nothing we can do about this.

syracuse looks fine by itself but iterate_over is highly inefficient because you're computing the same values over and over again. Once you know that a given integer n ends up with a 1, you can remember this. This is called memoization:

open Printf

let time f x =
    let t = Sys.time() in
    let fx = f x in
    Printf.printf "Execution time: %fs\n" (Sys.time() -. t);
    fx

let syracuse n =
    let rec aux x t cache =
        if x < n && Array.get cache x <> 0 then
            Array.get cache x
        else
            match x with
                | 1 -> t
                | x ->
                    if x mod 2 = 0 then
                        aux (x / 2) (t + 1) cache
                    else
                        aux (3 * x + 1) (t + 1) cache in
    let cache = Array.init n (fun x -> 0) in
    for i = 1 to n-1 do
        Array.set cache i (aux i 0 cache)
    done ;;

time syracuse 100000 ;;

This takes 0.035s on my machine and 0.003s when compiled: a 10x speedup! This is a space-time tradeoff. Another optimization allows you get a k-speedup with a 2^k precomputation, but it might not play well with the cache.

Now, to get maximum performance, you probably want to get down to C, given the relative slowness of integer arithmetic in OCaml.


Updating number of article views - potential concurrent access issue?

The performance with simple queries such as yours will depend more on what is going on in the database than what is going on in your code.

Here are a few things to consider if you are maintaining the DB yourself, or to bring up with the DBA if you are not:

If the id field is an integer, and ideally a  surrogate key (e.g. generated by an identity function instead of being a natural key using date/time, articlename, etc.), that will perform significantly better. Integers can be easily and swiftly ordered and generate relatively small indexes that can be searched quickly. A surrogate key improves performance for many reasons, one of which improved index performance by pushing data INSERTs to the leading edge of the index.
If the article table has a clustered index on the id field, that's even better for your performance as it will reduce the cost of both the SELECT and the UPDATE in most cases. The clustered attribute means that the data is already ordered by your ID column, significantly improving search performance.
If you don't have a lot of competing queries that try to lock bigger sets of data than a row at a time, that will also be good for the performance of these queries. You want to avoid contention for locking the same data as much as possible. For example, you don't want a big 100,000-row update that runs every 15 minutes competing with your single-row update.

Which brings me to the one thing I would change about your query: locking. Unless you really need per-transaction integrity when serving articles to the readers (and in most cases, for a publishing system, you probably don't) you can hint to the database that you'd like a more permissive transaction isolation level. In layman's terms, you can volunteer to let the other guy win if you both need a lock.

So if you are doing a SELECT at the same time an UPDATE is occurring to the same article, you can allow a READ UNCOMMITTED transaction isolation level on your query to avoid taking unnecessary locks. The syntax for doing this varies from one DBMS to another, but usually it's some variation on the theme of SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED. Some (MS SQL, for example) also have a shortened syntax such as WITH (NOLOCK).

Finally, a couple of caveats to this advice since you didn't specify your DB system. Some DB systems don't fit this mold. For example, Oracle implements non-blocking SELECTs without requiring dirty reads, so there's no equivalent to NOLOCK there because it's a built-in assumption. MySQL, on the other hand, has InnoDB and MyISAM tables, and on the latter type you are not going to be able to use READ UNCOMMITTED due to the underlying architecture of the table. However, even though you will be taking a table lock the architecture is designed to efficiently allow many concurrent reads by sharing the lock to multiple readers.

To sum up, your queries look fine but explore whether a NOLOCK-type option is available.


From my point of view, I cannot see any further improvement in terms of efficiency when you have a massive list of fields like that.

However, you might be interested in change the logic slightly.

For example, you might want the user to select the topic that he is interested in (using a dropdown list):

Offices
News
...
Events

And once he had selected the topic, and typed the keyword (s) in the input field, you can perform the search against an array which contains the fundamental fields such as heading, bodyText and against a custom list of fields just for that particular topic, such as the News:

string[] aliasNewsList = new string[]{"newsDate", "newsLocation", "newsSummary", "newsCategory"};


Clone Vector in rust except at one index

In my opinion none of your solution is idiomatic and all use an useless comparaison.

Using for loop:

Doesn't pre-allocate the vector
Use a comparaison that could be avoid

Using functional style:

Use a comparaison that could be avoid

Using mem replace:

Use a comparaison that could be avoid
Is unnecessary complex to just copy a vector

Also, you should avoid take a &Vec<T> as parameter, it's much better to take a &[T]. See: Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

I would use one of the following version:

#[derive(Clone)]
struct Pokemon {
}

fn a(pokemons: &[Pokemon], i: usize, pokemon: Pokemon) -> Vec<Pokemon> {
    let mut digimons = Vec::with_capacity(pokemons.len());

    digimons.extend_from_slice(&pokemons[0..i]);
    digimons.push(pokemon);
    digimons.extend_from_slice(&pokemons[i + 1..]);

    digimons
}

fn b(pokemons: &[Pokemon], i: usize, pokemon: Pokemon) -> Vec<Pokemon> {
    let mut digimons = pokemons.to_vec();
    digimons[i] = pokemon;

    digimons
}

fn c(pokemons: &[Pokemon], i: usize, pokemon: Pokemon) -> Vec<Pokemon> {
    pokemons[0..i]
        .iter()
        .cloned()
        .chain(std::iter::once(pokemon))
        .chain(pokemons[i + 1..].iter().cloned())
        .collect()
}

I don't really know witch version is better, a() and c() should be the same but sometime chain() is not optimized away. And b() is probably the most straightforward solution. I think I would choice a() in a production code.

However, looking at the assembly, we can see that a() and c() doesn't produce the same, and that b() is the simplest.


Bash function to dynamically move N directories above the current directory

If you're writing this as a shell function, then you don't need to eval.

The indentation could be done more idiomatically.  By using elif, you can eliminate one level of indentation and make the code structure clearer.

up() {
    if [ -z "$1" ]; then
        cd ..
    elif [ "$1" -eq "$1" ]; then
        if [ "$1" -lt 0 ]; then
            echo "First argument is not a positive integer"
        else
            for i in `seq 1 $1`; do
                cd ..
            done
            pwd
        fi
    else
        echo "First argument is not an integer"
    fi
}

Your question is very similar to this one.  The main problem, as you have already noted in your own comment, is that by doing multiple cd .. in sequence instead of one cd ../../.., you would be inserting many hops into the directory history.  Then, cd - or referencing $OLDPWD wouldn't work as expected.


There are a few points that can be critizised.

The method signature suggests that the architecture of the system isn't well-designed. Traversal of a Tree should likely be encapsulated in an Iterator class. In that case, the stack would be a private field of the iterator, and the actual code would use a foreach loop.

for (TreeNode node : tree)
  System.out.print(node.t + ":");

(preorder iteration is a good default)
Even if we let the design of your classes as they are, your implementation could be improved.

Single-letter variable names should be avoided. True, there are only two variables in your method, but using node and stack would be so much less cryptic.

The stack does not have to be concurrent, because it is not shared accross multiple threads. The vanilla java.util.Stack should work just fine. If you care about concurrency, you should rather worry about the tree nodes. What happens when a node was stored on the stack, but removed from the tree before the right child can be consumed by your code? Make sure the nodes aren't mutated until you visited them.

The body of your loop does not have a single comment although the stack manipulation may not be totally obvious to everybody (incl. you).

If you are optimizing for readability and not for space, I'd strongly suggest a recursive solution. This also makes writing correct code much easier:

static void preorder(TreeNode node) {
  if (node == null) return;

  System.out.println(node.t + ":");

  preorder(node.left);
  preorder(node.right);
}

(Not that your code was incorrect, this is just much easier to verify).

Next, I would like to reorder the parts of your loop to make it more obvious what is happening:

while (true)
{
    // check if we have to pop a value of the stack
    while (node == null) {
      if (stack.empty()) return;
      node = stack.pop().right;
    }

    System.out.print(node.t + ":");

    stack.push(node);  // store the node to continue the right path later
    node = node.left;
}

Note: If we use the java.util.Stack, then peek() could throw an EmptyStackException. We should rather use the empty() method which returns a boolean.

I think it would be more elegant to put the right childs on the stack, not the nodes which we already visited. We should also test whether these are null before adding them to the stack. This would keep the stack smaller:

while (true)
{
    // check if we have to pop a value of the stack WITHOUT LOOPING:
    // It is guaranteed that there never is a null node on the stack.
    if (node == null) {
      if (stack.empty()) return;
      node = stack.pop();
    }

    System.out.print(node.t + ":");

    // store the right node to continue there later
    if (node.right != null) stack.push(node.right);

    node = node.left;
}

I am not too comfortable with a while (true) loop, but the alternatives would mean slight code duplication (e.g. in your original code, you have two t!=null tests.)

Finally, you likely want to print a newline after this iteration. (In that case, the return should be a break).


$.fn.do() method: Execute other code within a jQuery chain

I guess this plugin could be useful, however I think you can drop the async part since it's not any harder to call queue directly.

Also, I am not a huge fan of error swallowing or ignoring invalid calls since it makes the code harder to debug. If there's a call to do without providing a callback, you should let the developer be notified.

I also like to allow defining the this value for the callback function so that you do not need to use $.proxy for that purpose.

Finally I allowed to return a value from the callback to change the target object for the rest of the chain. However I am not so sure about this feature since it could harm code comprehension but I am leaving it there as an idea.

Basically it would be as simple as:

!function($) {
    $.fn.do = function (callback, thisArg) {
        if (typeof callback !== 'function') {
            throw new TypeError("the 'callback' argument must be of type 'function'");
        }

        return callback.call(thisArg || this, this) || this;
    };
}(jQuery);

Note: I've defined the plugin within an IIFE so that it still works if $.noConflict() was used.


A One-Pass Hash Table Solution to twoSum

Don't leave white space at the end of lines.
Use enumerate.
When comparing with None use is and is not.
It'd be cleaner to just use in rather than get.
If you want to use nums_d.get then you should use it outside the if so you don't have to use it a second time when you enter the if.
This however makes the code messy for not much of a benefit IMO.
Unless the site forces you to return lists returning a tuple would be more Pythonic.
Your comments aren't helpful, if anything they make the code harder to read for me.
The variable name nums is easier to read then nums_d, the _d is useless.
When returning it would be better to either:

Raise an exception, as the lookup failed.
Return a tuple where both values are None. This is so you can tuple unpack without errors.

Getting the code:

def test_peil(nums: List[int], target: int) -> Tuple[int, ...]:
    lookup = {}
    for i, v in enumerate(nums):
        if target - v in lookup:
            return i, lookup[target - v]
        lookup[v] = i
    raise ValueError('Two sums target not in list.')

You can further improve performance by including Alain T.'s change for small numbers.

def test_peil_alain(nums: List[int], target: int) -> Tuple[int, ...]:
    if len(nums) <= 100:
        for i, n in enumerate(nums):
            if target - n in nums:
                return i, nums.index(target - n)
    else:
        lookup = {}
        for i, v in enumerate(nums):
            if target - v in lookup:
                return i, lookup[target - v]
            lookup[v] = i
    raise ValueError('Two sums target not in list.')

And has a performance improvement: (the graph is volatile due to only using one input sample)


Script to move images into year and month folder

I see this invocation of stat is MacOS specific.

Here's how I would shrink your code

find . -type f -iname '*.jpg' -size +500k -exec sh -c '
    for file in "$@"; do
        folder="/path/to/backup/folder/$(stat -f '%Sm' -t '%Y/%m' "$file")"
        mkdir -p "$folder"
        echo mv "$file" "$folder"
    done
' sh {} +

mkdir -p will create all missing folders, and it will also suppress errors if the directory already exists.

find's -exec cmd {} + feeds several filenames to the given command.

And this looks odd sh -c 'stuff' sh file ... -- the 2nd sh will be assigned to $0 inside the -c script, and the given files will be $1, $2, etc.


Submit form data to MYSQL table with PHP execute

You could possibly move the database include before the server checks and sets the $_POST variable, as it would not be needed if the database is unable to connect.

I notice there is no sanitization of the email variable. This may be helpful.


SQL uses three valued logic.

When one of the operands is null the expression evaluates to UNKNOWN not false. Your current code does not take account of this and can be altered as below to do so.

PRINT CASE
        WHEN @aTotalExVat = @sTotalExVat THEN 'true'
        WHEN @aTotalExVat <> @sTotalExVat THEN 'false'
        ELSE 'unknown'
      END

If you wanted to treat NULL = NULL as true and NULL = any not null value as false you could use

DECLARE @Message VARCHAR(5) = CASE WHEN EXISTS(SELECT @aTotalExVat
                                               INTERSECT
                                               SELECT @sTotalExVat)
                                   THEN 'true'
                                   ELSE 'false'
                               END;

PRINT '==Full Ex Vat==';
PRINT @Message;

On SQL Server 2012 there are a couple of new functions that shorten the above somewhat

DECLARE @Message VARCHAR(5) = IIF(EXISTS(SELECT @aTotalExVat
                                         INTERSECT
                                         SELECT @sTotalExVat),
                                  'true',
                                  'false');

PRINT CONCAT('==Full Ex Vat==', CHAR(13), ( CHAR(10) ), @Message);


Soup of the day: best served during election season

Since your list SITES_INFO_HELPER remains constant throughout the entire program, that list should be a tuple instead

Tuples are faster than lists and are write-protected, which doesn't make a difference to you because you are writing to them.

Read more about when you should use a tuple and when you should use a list here.

Good job using ArgumentParser in your code; that is often something that you don't see used in python code and is actually an extremely useful tool.

You could make your code more object oriented by turning the information inside SITES_INFO_HELPER into instances of a class, probably called Site.

It doesn't have to be anything too complicated; it's just supposed to be a way to store some values:

class Site:
    def __init__(self, name, initials, format=STANDARD_URL_FORMAT):
        self.name = name
        self.initials = initials
        self.format = format

Note: I set the format property to be STANDARD_URL_FORMAT by default because most stack exchange sites follow this format.

Then, when storing the sites, you'd store them like this:

SITES_INFO_HELPER = ( Site("codereview", "cr"), Site("stackoverflow", "so", COM_URL_FORMAT) ...)

I'm not entirely sure, but storing site information like this may rid of the need of build_sites_info.

I think you made a good choice using urllib and BeautifulSoup together to read the election webpage. And, from what I know about BeautifulSoup, what you are doing looks just fine.

Also, looking over the election page layout, how you are scanning the webpage seems to be the only/best way.


My Assumptions about your requirements

Here are a few points, assuming that you want performance and maintainability.

Assumption: Since you did not put the generation of the sequence and the sum of the evens in separate methods, I assume that a separate generation of the sequence is explicitly not a requirement and therefore it's okay if all functionality goes into one single method.

Runtime Comparison of solutions

Runtime comparison on my machine:

Your solution: ~950000ns
My simple solution (no loop unrolling, same structure as your code, except for the points mentioned below): ~3300ns
Best solution known to me: ~1700ns

Key points to improve performance of your code

without trading in maintainability.

The ArrayList is slowing the code down somewhat. As long as the code is interpreted, it is quite slow because interpreted method calls are slow. Once it is JIT-compiled the method calls no longer matter. Still, using ArrayList is unnecessary, as we will see below.
Your usage of Long for result involves unnecessary boxing / unboxing in the line result += .... Use long instead, result doesn't need to be Long. This speeds up your program by 1%.
You're concatenating Strings while time is still running. That tampers your  time calculation. Call System.nanoTime() right after the algorithm, not later.
Also, you might want to perform the runs to your algorithm multiple times in order to rule out effects of things like the OS scheduler or the code not being JIT-compiled when you measure performance.

Details about the even check

Given the requirements, you could check the numbers to sum up right away. Why do you check the numbers later?

I believe you fell into a premature optimization pit without considering the odds of your trade. You've traded the cheap operation "n is even", which is if ((n & 1) == 0), for a very expensive one - calling virtual method add() and calling virtual method get() inside the loops.

Your observation about every third number in the Fibonacci sequence being even is correct, the conclusion for the performance optimization is wrong.

!Spoiler Alert!

Fibonacci solutions below.

The typical Fibonacci loop

The typical Fibonacci loop looks like this:

long prevprev, prev = 1, current = 1;
while (current <= MAX_NUM) {
    prevprev = prev;
    prev = current;
    current = prev + prevprev;
}

Because we shall start with 1, 2 instead of 1, 1, which produces the same sequence except that it's missing the first member, we would use current = 2 instead.

So here's how to calculate the result:

long result = 0;
long prevprev, prev = 1, current = 2;

while (current <= MAX_NUM) {
    if ((current & 1) == 0) // if (isEven(current))
       result += current;
    prevprev = prev;
    prev = current;
    current = prev + prevprev;
}

loop unrolling to skip 2/3rd of the checks.

You can still use your smartness about the even/odd/odd pattern of the Fibonacci sequence.

There is a way in which you can ensure that you only sum up the evens without using a condition. We can use loop unrolling for that. Please note that as such, loop unrolling in Java is absolutely pointless. It only helps in this case because it enables us to get rid of 2 even checks for every 3 Fibonacci numbers.
The result is not maintainable, and because of the JIT compiler being smarter than all humans except its creators and those that studied it extremely well (I haven't), we usually would never even think of loop unrolling in Java.

Here's a code fragment which demonstrates the unrolled loop:

public static long sumOfEvenFibonacciNumbersUntilMaxNum() {
    long result = 0;

    long prevprev, prev = 1, current = 2;

    // Use the fact that every third is even: 1, 1, 2, 3, 5, 8.
    // We start with 2, so the first one in three is even.
    // Sum overflow over MAX_NUM inside the loop irrelevant:
    // The values of current which are too big are not used for result.
    while (current <= MAX_NUM) {
        result += current;// even
        prevprev = prev;
        prev = current;
        current = prev + prevprev;
        prevprev = prev;
        prev = current;
        current = prev + prevprev;
        prevprev = prev;
        prev = current;
        current = prev + prevprev;
    }
    return result;
}

This trades 6 additional assignments and 3 additional additions in the last loop for avoiding n checks of (current & 1) == 0 and reduces the number of current <= MAX_NUM checks by 3.

If you think that this unrolled loop looks like it can be optimized further, you're right, we can actually optimize the loop logic, see next step.

Further algorithmic analysis

The Fibonacci calculation is a window of three numbers over the Fibonacci sequence with the current number F(n) and two precursors F(n-1) and F(n-2) for remembering the intermediate results in order to perform the production of F(n) := F(n-1) + F(n-2).

You noticed correctly, that every third member of the Fibonacci sequence is even.

This happens to be the same size as the window that we need to move in order to perform the calculation.
We can utilize this.
As always, good naming helps.
Therefore, let's change the names of the variables as well.

public static long sumOfEvenFibonacciNumbersUntilMaxNum() {
    long sumOfEvens = 0;
    long odd1, odd2 = 1, even = 2;

    while (even <= MAX_NUM) {
        sumOfEvens += even;
        odd1 = even + odd2;
        odd2 = odd1 + even;
        even = odd2 + odd1;
    }
    return sumOfEvens;
}

Given the self-explanatory variable names and the comment, I claim this still is perfectly well maintainable code. The only drawback is that it cannot generate the Fibonacci sequence separately. Hence my initial assumption about the requirements.

P.S.:
Of course we'd make MAX_NUM a parameter, I just didn't discuss this because I think it's completely irrelevant for the problem and obvious to the typical audience of this class of problem.

Comparison of the add solution with the multiply solution.

There also exists a solution which uses the fact that you can generate the sequence of evens without the intermediate odds.

Let's compare them.

// Add alternative
public static long sumOfEvenFibonacciNumbersUntilMaxNum() {
    long sumOfEvens = 0;
    long odd1, odd2 = 1, even = 2;

    while (even <= MAX_NUM) {
        sumOfEvens += even;
        odd1 = even + odd2;
        odd2 = odd1 + even;
        even = odd2 + odd1;
    }
    return sumOfEvens;
}

// Multiply alternative
public static long sumOfEvenFibonacciNumbersUntilMaxNum() {
    long sumOfEvens = 0;
    long prevPrevEven, prevEven = 0, even = 2;

    while (even <= MAX_NUM) {
        sumOfEvens += even;
        prevPrevEven = prevEven;
        prevEven = even;
        // << 2 instead of * 4 matters here to reuse value 2 in the byte code.
        even = (prevEven << 2) + prevPrevEven;
    }
    return sumOfEvens;
}

Now we really have to go down to machine code in order to understand what's going on. This of course has limited value in Java, as there are too many unknowns like if it is JIT compiled, how the JIT works, and how fast the CPU is.

The byte code of the multiply solution is 3 instructions shorter, which happen to be in the loop. If the byte code is interpreted only, the multiply solution wins.

If the code is compiled, we need to think of what machine instructions are going on inside the loop.

Add loop:

; R0: result = 0
; R1: odd1
; R2: odd2 = 1
; R3: even = 2
; R4: MAX_VALUE
.label
    cmp R3, R4
    bgt .done
    add R0 <- R0 + R3
    ; begin difference
    add R1 <- R3 + R2
    add R2 <- R1 + R3
    add R3 <- R2 + R1
    ; end difference
    bra .label
.done

Multiply loop:

; R0: result = 0
; R1: prevPrevEven
; R2: prevEven = 0
; R3: even = 2
; R4: MAX_VALUE
.label
    cmp R3, R4
    bgt .done
    add R0 <- R0 + R3
    ; begin difference
    mov R1 <- R2
    mov R2 <- R3
    lsl R3 <- R3 << 2
    add R3 <- R3 + R1
    ; end difference
    bra .label
.done

Whether the multiply solution is faster or the add solution is faster depends on how this pseudo assembly translates into the real machine code.
The key questions are:

Is add Rn <- Rx + Ry available? If not, i.e. only add Rn <- Rn + Rx is available, each add Rn <- Rx + Ry with n != x and n != y requires an additional mov instruction.
Is lsl Rn <- Rn << 2 available? If not, we need one more register. And if so, are enough registers available?

On CPUs like ARM, on which add Rn <- Rx + Ry is available, the Add solution is fastest.
On CPUs like 80x86 or 680x0 / CPU32, on which add can only modify an existing register but not store the result in a new register, additional move instructions would be inserted for each add instruction which does not use a source register also as destination register. So the Multiply solution is faster on 80x86 and 680x0 / CPU32.

EDIT Note: The original answer contained statements about method calls being expensive, which is wrong, and a description of loop unrolling which was partially wrong and thus misleading. The credit for fixing these bugs in the answer goes to jrolfl, who pointed this out and patiently discussed this with me in chat. Thank you!


Rule of Zero

You should follow the rule of zero where class that deal with memory ownership should deal exclusively with memory ownership. Your class allocate raw memory but do not free it when being destroyed. It will leak memory. Also issue with copying your queue. You should use std::unique_ptr instead of raw new.

Reuse memory when queue is empty

Why do you need to free the underlying memory when the queue is empty? Can't you just set head to the beginning and reuse the memory? This will save you from having to allocate new memory.

Use STD algorithm

Use std::copy_n instead of for loop in doubleSize() to make your code more readable.


Finding sum of divisors of numbers between the range (1 to 1e16)

What's going on with the indentation?

  long long

No. We're not in the 1970s. Use <cstdint>. Here you probably want std::uint_fast64_t.

IMO n should be const and the copy (x) should be the variable which is modified in the loop.

    for(long long i=2;i*i<=n;i++)

The first step to optimising prime divisor searches is to use a wheel. If you special-case i=2 then you can search for(i=3;i*i<=x;i+=2), which is already a speedup by about a factor of 2.

On some architectures, multiplication is expensive and it's faster to maintain a variable ii or iSquared which is updated using the identity \$(i+a)^2 - i^2 = 2ai + a^2\$: e.g. (untested, may be buggy): for(i=3,ii=9;ii<=x;ii+=(i+1)<<2,i+=2)

          long long current_sum=1,current_term=1;
           while(n%i==0)
           {
              n/=i;
              current_term*=i;
              current_sum+=current_term;
            }

This can be simplified:

           std::uint_fast64_t current_sum=1;
           while(x%i==0)
           {
              x/=i;
              current_sum=current_sum*i+1;
           }

The first big step to improving the algorithm would be to exploit the fact that up to 500 test cases are passed at a time. If you read them all and find the largest, you can do a variant of Eratosthenes' sieve once to set up an array which allows you to factor all numbers up to that largest one very fast.

If that's not enough, it's probably necessary to switch factorisation approach, starting with Pollard's rho algorithm.


Create all combinations of length N from a given alphabet

Nitpicks

You're using the "wrong" bracing style :). The vast majority of Java code-conventions enforces "egyptian" bracing style with the opening brace on the same line.
The method name create_combinations is in "snake_case". The vast majority [...] "camelCase" variable naming. The method should be named createCombinations.

Approach

While you're using a pretty performant approach with StringBuffer, this can be improved a bit when working on a raw char[]. The vast majority of the costs here comes from creating the new Strings. That is something you won't be able to eliminate.

Furthermore you seem to have missed the "crucial point" of the challenge. What you're doing from a mathematical (or theoretical cs) point of view is counting. Your strings are fixed-width numbers.

Consider the following call:

createCombinations({'0', '1'}, 4);

the results are the following:

0000
0001
0010
0011
0100
0101
0110
0111
[...]
1111

You should see that this matches the binary numbers 0 to 15.

Now let's see what we can do with this information:

Know how many results there will be. (namely \$a^c\$ with \$a\$ being the size of the alphabet and \$c\$ the length of the word)
Count through the results.

This makes clear what our method signature will look like:

private String[] createCombinations(char[] orderedAlphabet, int wordLength) {

If you want to add some raw performance it would be a consideration to return a char[][] instead.

Enough talk about concepts: Here's how it looks:

public String[] createCombinations(char[] orderedAlphabet, int wordLength) {
    long resultCount = Math.pow(orderedAlphabet.length, wordLength);
    String[] result = new String[resultCount];
    char[] workingWord = new char[];
    for (int i = 0; i < workingWord.length; i++) {
        workingWord[i] = orderedAlphabet[0];
    }
    // initialization complete, algorithm starts:
    for (int i = 0; i < result.length; i++) {
        result[i] = new String(workingWord);
        int leastSignificantDigit = i % orderedAlphabet.length;
        workingWord[workingWord.length - 1] = orderedAlphabet[leastSignificantDig];
        // TODO propagate changes up the workingWord if the lsd is 0.
        // [...]
    }
    return result;
}

Propagating the changes up the working word is left as a challenge for you.

Interestingly the observation about the "crucial point" of the challenge will allow you to formulate  the challenge as a Stream. Do note that the stream will not have the state of a workingWord to ease computation (because streams must not have side-effects), which imposes a performance hit. Either way it's basically only a bit of hard thinking on how numbers work to get from IntStream.range(0, resultCount) to a Stream<String> containing all your results.


Palindrome numbers - Project Euler Problem 4

First of all, you are only interested in the biggest number, so why do you start from the bottom??
Correcting that allows you to dispense with an explicit lower boundary, a dynamic boundary can be computed depending on current-best result.
Why don't you read the upper boundary from the command-line?
Proper indentation is a very valuable help in quickly and accurately reading source-code, as well as ferreting out errors.
In your case, the one level of indentation missing through much of your code might be an artifact of sloppy posting here. Whether or not it is, don't do that.
You are depending on implicit definition of palindrome. Don't do that, reverse their positions.
An int only has a guaranteed range of -32767 to 32767. Use a long (or unsigned long), that has the proper range without depending on implementation-dependent behaviour.
Why do you use an array and all that paraphernalia to check for being a palindrome, simply reversing is easy:

unsigned long reverse(unsigned long in) {
    unsigned long r = 0;
    for(; in; in /= 10)
        r = r * 10 + in % 10;
    return r;
}

Final program (on coliru):

#include <stdio.h>
#include <stdlib.h>

static int is_palindrome(const unsigned long in) {
    unsigned long r = 0;
    for(unsigned long x = in; x; x /= 10)
        r = r * 10 + x % 10;
    return r == in;
}

int main(int argc, char* argv[]) {
    unsigned long max = argc > 1 ? strtoul(argv[1], 0, 10) : 0;
    if(!max || max > 9999)
        max = 999;
    unsigned long _a = 0, _b = 0, _m = 0; // best yet
    for(unsigned long a = max, a_min = 1; a >= a_min; --a)
        for(unsigned long b = max, b_min = _m / a + 1; b >= b_min; --b)
            if(is_palindrome(a*b)) {
                _a = a, _b = b, _m = a*b, a_min = _m / max + 1;
                break;
            }
    printf("Biggest palindrome-number which is product of two natural numbers"
        " no bigger than %lu: %lu = %lu * %lu\n", max, _m, _a, _b);
    return 0;
}


Simple password dictionary attack script

Performance

For each cipher, you re-read and re-encrypt the dictionary again and again. If some of your ciphers have the same length, then this is wasteful. At the minimum, you should load the dictionary only once. If you have a lot of passwords, then you could pre-encrypt all words in the dictionary for each unique factor. That should speed things up.

Coding style

You could simplify this if condition:

if (($factor == 56) ||
      ($factor == 64) ||
      ($factor == 96) ||
      ($factor == 128))
{ ... }

by using a helper function, perhaps something like this:

sub one_of {
    my $value = shift;
    for (@_) { return 1 if $_ eq $value; }
}
# ...
if (&one_of($factor, 56, 64, 96, 128)) { ... }

This can be slightly simpler:

my @ciphers = <$input>;
# remove end of line characters
chomp(@ciphers);

like this:

chomp(my @ciphers = <$input>);

And then close($input) right after. It's good to close an input file immediately after you're done reading from it.

You could simplify $factor = $factor * 4; as $factor *= 4;

I think all your comments are pointless. You can remove them and let the code speak for itself.

If the meaning of a variable is not clear enough without a comment, then try to rename it to be self-explanatory. Note that the variable will be self-explanatory every time you use it, whereas a comment only explains it in once place.

Likewise, you can extract non-trivial logic to a function with a name that explains what it does. For example:

sub get_factor {
    my $cipher = shift;
    my $factor = length($cipher);
    if ($factor == 40) {
        return 1;
    } elsif (&one_of($factor, 56, 64, 96, 128)) {
        return $factor * 4;
    }
}

foreach my $cipher(@ciphers) {
    # ...
    my $factor = &get_factor($cipher) || next;
    # ...
}


Need an algorithm to optimize grouping python dictionaries in hierarchical form

Try doing a recursive sequence that iterates through each group, by passing a group index to each call, and find and build the tree as it receives inputs:

def generate_hierarchical_hash(entries, groups):
  """Returns hierarchical hash of entries, grouped at each level by the groups"""
  hierarchy = {}
  for to_insert in entries:
    insert_into_hierarchy(to_insert, hierarchy, groups, 0)
  return hierarchy

def insert_into_hierarchy(to_insert, hierarchy, groupings, current_grouping_level):
  if current_grouping_level == len(groupings):
    # if at final level, do not do anything - protection case
    pass
  else:
    grouping_at_level = groupings[current_grouping_level]
    grouping_key = to_insert[grouping_at_level]
    is_final_group = current_grouping_level == len(groupings) - 1
    if is_final_group:
      # if at last grouping, nodes will contain lists, so create or retrieve list
      # and append value to it
      if grouping_key in hierarchy:
        list_for_group = hierarchy[grouping_key]
      else:
        # create new list and insert it into hierarchy
        list_for_group = list()
        hierarchy[grouping_key] = list_for_group

      # insert to insert into end of list
      list_for_group.append(to_insert)
    else:
      # otherwise, find or create hash for this grouping,
      if grouping_key in hierarchy:
        hierarchy_for_group = hierarchy[grouping_key]
      else:
        # create hash and insert into parent hash
        hierarchy_for_group = {}
        hierarchy[grouping_key] = hierarchy_for_group
      # recursive call, go down a level and group
      insert_into_hierarchy(to_insert, hierarchy_for_group, groupings, current_grouping_level + 1)

This could be called like:

input =[{'dept':1, 'age':10, 'name':'Sam'},
        {'dept':1, 'age':12, 'name':'John'},
        {'dept':2,'age':20, 'name':'Mary'},
        {'dept':2,'age':11, 'name':'Mark'},
        {'dept':2,'age':11, 'name':'Tom'}]

groups = ['dept', 'age', 'name']

hierarchical_hash = generate_hierarchical_hash(input, groups)


The problem is that this._slideIn refers to a function, not a method invocation.  In your third code sample, changing your last line to

var self = this;
setTimeout(function() { self._slideIn(componentId) }, 20);

should be sufficient.  You have to capture this in the closure that you pass to setTimeout(), because when the code runs later, this will refer to something else in that execution context.


All seems good.

As you mentioned it is sensitive to trailing slash being missing. I would just force that issue and always append one between the prefix and the path. An extra slash will not hurt but a missing one will.

Apart from not using C in the first place :-) all my other issues are simple stylistic ones that only 30% of people would agree (I always divide stylistic camps as 30% Side A, 30% side ~A, 40% don't care).

A tiny bit more white space to make it easier to read. But let me just say your code is not bad in that regards (just slightly less than I would use).

I don't want to recommend any particular style. But I can show you how I would have written it:

// Keep you includes sorted in alphabetical order
// Here it is not such a big deal but with big projects the list can get big
// and alphabetical order helps you find things in large lists.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define APP_PREFIX_ENV_VAR "APP_PREFIX"

const char * app_path_prefix()
{
    char * env_prefix = getenv(APP_PREFIX_ENV_VAR);
    return (env_prefix == NULL)
               ? ""
               : env_prefix;
}

char * app_path(char * in_path)
{
    /*
     * Some people really hate this.
     *
     * Others like myself really like lining up the '=' sign
     * Just do it locally with a set of calculations. I find it easier to see
     * both the lhs and the rhs of expression quickly.
     */
    char const* prefix     = app_path_prefix();
    size_t      prefix_len = strlen(prefix);
    size_t      out_size   = prefix_len + strlen(in_path) + 1;

    /*
     * Dynamically allocated. Released to outside world it is the
     * responsibility of the caller to free this memory
     */
    char *      out        = malloc(out_size);

    strlcpy(out, prefix, prefix_len + 1);
    strlcat(out, in_path, out_size);
    return out;
}

int main(int argc, char ** argv)
{
    /* test */
    char * path = app_path(argv[1]);
    printf("result: '%s'\n", path);
    free(path);

    return EXIT_SUCCESS;
}


Prompt user for some numbers, then print the max and min

It's a shame python doesn't have a do..while loop, which would have been a better fit for the occasion.

You do plenty of branching. For every valid input, you check if the extreme values so far are still None. If you think about it, this will only be the case the first time a valid value is entered. It's not very plausible to keep on performing that check and it needlessly bloats the code.

To find maximum and minimum efficiently, use max() and min() and initialise your variables with appropriate values, that make the initial case blend in with the rest of the operation. +/-Infinity are good candidates for such values. Everything is bigger than -infinity, which makes it ideal as a starting value for the largest number. Here's what your code would look like with those changes applied:

largest = -float('inf')
smallest = float('inf')

while True :
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try :
        num = int(num)
    except :
        print "Invalid input"
        continue

    largest = max(num, largest)
    smallest = min(num, smallest)

print "Maximum is", largest
print "Minimum is", smallest


Python Inheritance and Class (Hackerank problem)

Read PEP8 the Python style guide

Functions and variables should be lower_snake_case
Naming

Single letter variable names are a bad habit. Code should be self explanatory and function names like m() don't tell what they are supposed to do
Instead of the printPerson() function, override the magic function __str__

Doing this you can do print(student) to print the class
You should make the avg function a part of the Student class
Your grade function can be simplified

 scoreList = [
   {'O': '90-100'},
   {'E': '80-89'},
   {'A': '70-79'},
   {'P': '55-69'},
   {'D': '40-54'},
   {'T': '0-39'},
]

When you swap the key and values around, and loop over them in order

self.score_dictionary = {
    90 : 'O',
    80 : 'E',
    70 : 'A',
    55 : 'P',
    40 : 'D',
    0  : 'T'
}

It becomes clear that if the average is higher than the value that should be the grade to give, else go to the next value

This will happen automatically with Python3.7+, or else you can make use of an OrderedDict

from collections import OrderedDict
self.score_dictionary = OrderedDict([
    (90, 'O'),
    (80, 'E'),
    (70, 'A'),
    (55, 'P'),
    (40, 'D'),
    (0, 'T')
])

Thnx @Graipher, for correcting my mistake regarding the OrderedDict

Another way (which might be clearer) is to loop over the dictionary keys in sorted order
You can unpack multiple arguments in one go

line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]

Could be

f, l, i = input().split()

It is Python idion to use _ for variables you don't use

Code

class Person:
    def __init__(self, first_name, last_name, id):
        self.first_name = first_name
        self.last_name = last_name
        self.id = id

    def __str__(self):
        return f"Name: {self.last_name}, {self.first_name}\nID: {self.id}"

class Student(Person):
    def __init__(self,  first_name, last_name, id, scores):
        super().__init__(first_name, last_name, id)
        self.scores = scores
        self.avg = sum(self.scores) / len(scores)
        self.score_dictionary = {
            90 : 'O',
            80 : 'E',
            70 : 'A',
            55 : 'P',
            40 : 'D',
            0  : 'T'
        }

    def grade(self):
        for score in sorted(self.score_dictionary.keys(), reverse=True):
            if self.avg >= score:
                return self.score_dictionary[score]

if __name__ == '__main__':
    f, l, i = input().split()
    _ = input()
    scores = list(map(int, input().split()))
    student = Student(f, l, i, scores)
    print(student)
    print(f"Grade: {student.grade()}")


Use an enumerator?

And use it like this:

if($this->isInRole(Roles::MANAGER)


Reading and writing of pixels of BufferedImages

The problem comes from iteratively accessing your image object in your current manner.  Take a look below.  This is substantially faster.

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

public class FastRGB {

private final int width;
private final int height;
private final boolean hasAlphaChannel;
private int pixelLength;
private final byte[] pixels;

public FastRGB(BufferedImage image) {
    pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    width = image.getWidth();
    height = image.getHeight();
    hasAlphaChannel = image.getAlphaRaster() != null;
    pixelLength = 3;
    if (hasAlphaChannel) {
        pixelLength = 4;
    }
}

public int getRGB(int x, int y) {
    int pos = (y * pixelLength * width) + (x * pixelLength);
    int argb = -16777216;
    if (hasAlphaChannel) {
        argb = (((int) pixels[pos++] & 0xff) << 24);
    }
    argb += ((int) pixels[pos++] & 0xff);
    argb += (((int) pixels[pos++] & 0xff) << 8);
    argb += (((int) pixels[pos++] & 0xff) << 16);
    return argb;
}
}