Web service - getting data from SQL and adding to Object

This code here is not good

using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
        result.CommandType = reader.GetString(0);
        result.Command = reader.GetString(1);
        result.SendDateTime = reader.GetDateTime(2);
        reader.Close();
}

you don't surround your while statement,  so it will only result in your commandtype being set.

You need to use Braces!

using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        result.CommandType = reader.GetString(0);
        result.Command = reader.GetString(1);
        result.SendDateTime = reader.GetDateTime(2);
    }
    reader.Close();
}

I assume that the reader.Close(); is supposed to be outside the while statement.  the other thing here is that if your reader returns more than 1 record your result will only hold the last record that is read.

You should do something with that ugly call to your connection string as well, instead of this:

    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestProjectConnectionString"].ConnectionString))
    {
         ...

Do something pretty like this:

var connectionString = ConfigurationsManager.ConnectionStrings["TestProjectConnectionString"].ConnectionString;

using (SqlConnection connection = new SqlConnection(connectionString)
{
     ....

This way when you want to change from the Test connection string to the Production String, you only have to change it here and not every place it is mentioned in the code.  it is easier to maintain this way.

I did some research and I you should also use a using statement for you sqlcommand as well (do we need using for the SqlCommand or is it enough just for the SqlConnection and SqlDataReader).

so this:

    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestProjectConnectionString"].ConnectionString))
    {
        string query = "exec usp_dequeueTestProject";
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
             result.CommandType = reader.GetString(0);
             result.Command = reader.GetString(1);
             result.SendDateTime = reader.GetDateTime(2);
             reader.Close();
        }
        connection.Close();
    }

Will become this (with all the changes so far):

    using (SqlConnection connection = new SqlConnection(connectionString)
    {
        string query = "exec usp_dequeueTestProject";
        connection.Open();

        using (SqlCommand command = new SqlCommand(query, connection))
        {
            using (SqlDataReader reader = command.ExecuteReader())
            {
                 while (reader.Read())
                 {
                      result.CommandType = reader.GetString(0);
                      result.Command = reader.GetString(1);
                      result.SendDateTime = reader.GetDateTime(2);
                 }
                 reader.Close();
            }
        }
        connection.Close();
    }

I moved the connection.open before it is called for the command,  it makes more sense there, at least to me. everything inside the using connection statement should need the connection so Open it first.  That variable for the query string should be created with the other variable, outside the using statement.

Don't clutter your using statements, it will make things difficult when you go to change something and could cause issues later on with the scope.


Is this a safe way to parse out HTML tag attributes?

Whitespace around = is allowed, your regex won't handle that.
Characters in HTML can be encoded, some characters (like &) have to be encoded. For example name="AT&amp;T" should return that the value of name is AT&T.


Stored procedure to implement a search filter

A user could cause a dos attack by passing in complex like filters, you might want to sanitize the @name parameter. https://www.owasp.org/index.php/Testing_for_SQL_Wildcard_Attacks_(OWASP-DS-001)


Beginner solution to basic quiz exercise, a la Gophercises

Two things I noticed:

    file, err := os.Open(path)
    correct, lines := 0, 0

    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

Handle errors immediately, don't do other things first:

file, err := os.Open(path)
if err != nil {
    log.Fatal(err)
}
defer file.Close()

correct, lines := 0, 0

Don't leave an opportunity to add more code later before the error handling by separating os.Open from if err != nil. Sooner or later you'll use file where it may be nil.
Creating a new scanner for each answer is slightly wasteful. Since you asked about potential tests, you can clearly test one or two question/answer cycles. To do that, you'll want to pass two io.Readers to quizLoop instead of a filename

func quizLoop(questions io.Reader, answers io.Reader, verbose bool)

You can pass the file and os.Stdin from main, and in tests you can pass bytes.Buffers, for instance, to supply test data.

I don't see an opportunity to leverage Go routines here. This program is inherently sequential. I'm sure you'll get an excercise for that later.


Short square matrix class in C++ using an array

(1) The exception is a good way of handling such errors, but it may be a good idea to provide a non-throwing, less safe accessors. For example, std::vector::at() will throw an std::out_of_range if requested index is not valid, but std::vector::operator[] will silently accept all values. That's because, if individual elements are accessed very frequently (some complicated math algorithm), all those ifs may impact the performance. So, as it goes for the exceptions, two suggestions:

throw std::out_of_range instead of plain std::exception to indicate what kind of error just happened,
do not throw in every accessor (you only have one, which leads to point 4, see below).

(2) Yes, they do. But, the basic question is: do you really need to be able to specify size of a matrix at runtime? Perhaps it would be better to use compile-time constant size:

template <size_t Size>
class Matrix
{
private:
  int elements[Size*Size];
  //...
};

Then, you would use it this way:

Matrix<4> mat4;

In this version, no destructor would be necessary and no memory allocation required. Because of that, this version also can be faster.

(3) "Idiomatic C++ style" has become a very fragile term recently (IMHO). But, you could probably provide support for accessing elements of your matrix using operator[] (see point 4).

(4) It would be nice if users of your Matrix could write simply:

Matrix<4> mat; // Or: Matrix mat {4}, in dynamically-allocated version
mat[3][3] = 1; // set elements in row 3, column 3 (note, that indices are from 0 to 3)

Or, equivalently, in simpler version:

mat[15] = 1;

(*) Simple version only requires the presence of operator[]:

template <size_t Size>
class Matrix
{
    int& operator[](size_t index)
    {
        return elements[index];
    }

    const int& operator[](size_t index) const
    {
        return elements[index];
    }
};

Note, that two version are provided, so you can do this:

Matrix<4> mat;
mat[5] = 1;

but not this:

const Matrix<4> constMat;
constMat[2] = 3; // compilation error: cannot assign to const reference

(**) The more elegant, but also more difficult version (nested [][] syntax), requires, that operator[] of the matrix must return an object (or an array) that also supports [] notation.

The easier way to achieve this would be to to change the T* elements to T** elements (or, in templated version, elements[Size*Size] to elements[Size][Size]). Note, that in this case you do not need the convert() function, since you can use the indices explicitly.

You could also declare simple Vector struct (I will limit myself here to templated version):

template <size_t Size>
struct Vector
{
private:
  int elements[Size];

public:
  int& operator[](size_t index)
  {
    return elements[index];
  }

  const int& operator[](size_t index) const
  {
    return elements[index];
  }
};

And then implement your Matrix using Vector:

template <size_t Size>
class Matrix
{
private:
  Vector<Size> columns[Size];

public:
  Vector<Size>& operator[](size_t index)
  {
    return columns[index];
  }

  const Vector<Size>& operator[](size_t index) const
  {
    return columns[index];
  }
};

(1.1) Now, after we covered the topic of operator[], we can return to the exceptions once more. To aid those unsafe operator[]s, we can add more safe, explicit at() function:

template <size_t Size>
class Matrix
{
private:
  Vector<Size> columns[Size];

public:
  Vector<Size>& at(size_t index)
  {
    if (index >= Size) throw std::out_of_range("Invalid index!");
    return columns[index];
  }

  const Vector<Size>& at(size_t index) const
  {
    if (index >= Size) throw std::out_of_range("Invalid index!");
    return columns[index];
  }
};


CtCi 2.6: Implement a function to check if a linked list is a palindrome

Don't use using namespace std;. See any other C++ question for the reasons.

The declaration createSampleList(string str) means that when you pass a string to that function, the whole string will be copied. That's unnecessary. Declaring the function as createSampleList(const string &str) is much more efficient.

The variable name tempStack can be improved. The word temp should not appear here at all, since it doesn't explain anything about the code.

I was first confused on why you called tempStack.pop() two times in a row. But then I saw that it was top and pop. There's nothing you can do against that, since the C++ API just doesn't provide the method that combines these two. Maybe you could move the tempStack.pop() below the if sentence.

The char reverseVal line is not indented properly. Let your IDE fix the indentation.

After each if, there should be a space. Only for function calls the space should be omitted.

A general rule is that you should not use global variables. The global variable in this case is head. It is better to pass such variables as parameters. This corresponds to natural language speaking, where you would ask Is the word asdfdsa a palindrome? instead of Is the word written at the wall over there a palindrome?. This makes your code much more flexible.

The rest of the code looks great for learning algorithms. If you want to use that code in practice, it should be much shorter. Something like this:

#include <cassert>
#include <string>

bool is_palindrome(const std::string &str)
{
    std::string rev(str.rbegin(), str.rend());
    return str == rev;
}

int main()
{
    assert(is_palindrome(""));
    assert(is_palindrome("a"));
    assert(is_palindrome("aa"));
    assert(!is_palindrome("ab"));
    assert(!is_palindrome("aaabcaaa"));
}


Getting the smallest snippet from content containing all keywords

First, going over your code

import itertools, re

re is not used

contentWords = content.split()

I would be more explicit on the split, calling split(' ') so your intentions are crystal clear

index = contentWords.index(term)

Each call to this is an O(n) operation on the list, m times where m is the number of times the element occurs, x times where x is the number of keywords. So in big O (and worst case) we have O(nmx). We can be smarter about this, and do it in O(n) and in one iteration. We will use extra memory to store the keywords in a dict

So replacing this:

termPosition = {}
for term in keywords:
    index = 0
    positions = []
    while index is not None:
        try:
            index = contentWords.index(term)
            positions.append(index)
            contentWords[index] = None
        except:
            index = None
    termPosition[term] = positions

With:

# Create an empty list for each keyword
# We could achieve the same result with a defaultdict
termPosition = {keyword: [] for keyword in keywords}
# enumerate gives us the indexes of the word
for index, word in enumerate(contentWords):
    # if the word is a keyword, record the index
    if word in termPosition:
        termPosition[word].append(index)

for term in termPosition.keys():
    if len(termPosition.get(term)) == 1:
        singlePositions.append(termPosition.get(term)[0])
    else:
        multiplePositions.append(termPosition.get(term))

You don't need to work out the values from the keys. Also .append(x[0]) for a list of size one is the same as extending by that list. (You can concat lists with either += or .extend)

for positions in termPosition.values():
    if len(positions) == 1:
        singlePositions += positions
    else:
        multiplePositions.append(positions)  # Keeping it as a list of lists

    contentWords = content.split(' ')

No longer needed since we don't modify contentWords

for element in itertools.product(*multiplePositions):
    tempList = list(element) + singlePositions
    minPos = min(tempList)
    maxPos = max(tempList) + 1
    if len(' '.join(contentWords[minPos:maxPos])) < len(snippet):
        snippet = ' '.join(contentWords[minPos:maxPos])

This is going to be the main slowdown of your code as product means factorial growth. I can't think of something that does this better right now, but I'll come back if I do find one. The issue at hand is that it isn't the shortest range of indexes which contain all the keywords, it is the shortest snippet. The words might vary in length, giving each index a weight. In addition, spaces mean it isn't the smallest sum of weights, it is the min sum of weights plus number of additions used.
You could create a list of the length of each word in contentWords, and find the min sum(contentWordsLens[minPos:maxPos] + (maxPos - minPos)). The should be more performant as you are adding numbers instead of strings
As for the code, there are a couple of tricks to squeeze down the time

# The min and max from singlePositions never change
# We convert the single value to a tuple to avoid doing repeatedly in the loop

minSinglePositions = tuple(min(singlePositions))
maxSinglePositions = tuple(max(singlePositions))
minSnippetLen = len(snippet)
for element in itertools.product(*multiplePositions):
    minPos = min(element + minSinglePositions)
    maxPos = max(element + maxSinglePositions) + 1
    candidate = ' '.join(contentWords[minPos:maxPos])
    if len(candidate) < minSnippetLen:
        snippet = candidate
        minSnippetLen = len(snippet)

The main improvements come from moving any work that is constant to outside the loop. We also avoid repeating work like working out the length of the snippet. For this kind of tricking about, profiling should be done to test the function.

A final note, there are two parts to the function, getting the indexes, and checking which combination is the shortest. As such, we can move them to two functions.

A cleaner version of the submitted code:

import itertools

def get_positions(content, keywords):
    termPosition = {keyword: [] for keyword in keywords}
    # enumerate gives us the indexes of the word
    for index, word in enumerate(content):
        # if the word is a keyword, record the index
        if word in termPosition:
            termPosition[word].append(index)

    singlePositions = []
    multiplePositions = []
    # Note, if any of the positions are of len 0, the keyword isn't in the snippet
    # This should be raised. As it is currently, it returns the input snippet
    for positions in termPosition.values():
        if len(positions) == 1:
            singlePositions += positions
        else:
            multiplePositions.append(positions)  # Keeping it as a list of lists

    return singlePositions, multiplePositions

def get_shortest_snippet(content, contentWords, singlePositions, multiplePositions):
    # The min and max from singlePositions never change
    # We convert the single value to a tuple to avoid doing repeatedly in the loop
    if singlePositions:
        minSinglePositions = tuple(min(singlePositions))
        maxSinglePositions = tuple(max(singlePositions))
    else:
        minSinglePositions = tuple()
        maxSinglePositions = tuple()

    snippet = content
    minSnippetLen = len(snippet)

    for element in itertools.product(*multiplePositions):
        minPos = min(element + minSinglePositions)
        maxPos = max(element + maxSinglePositions) + 1

        candidate = ' '.join(contentWords[minPos:maxPos])
        if len(candidate) < minSnippetLen:
            snippet = candidate
            minSnippetLen = len(snippet)

    return snippet

def solve(content, keywords):
    # Input
    content = content.strip()
    contentWords = content.split(' ')

    singlePositions, multiplePositions = get_positions(contentWords, keywords)
    shortestSnippet = get_shortest_snippet(content, contentWords, singlePositions, multiplePositions)
    return shortestSnippet


First, you could wrap the PrintWriter pw into a try-with-resources statement.

Without knowing the library, it is unclear how the loop for (i = 0;; i++) can be left (only with an exception). Does some method throw a JauntException ?
If so, where? JauntException also seems to be a quite general exception. Maybe a more specific one can be used. Also if the API provides such methods, it might be a good idea to test if more results are available (like hasNext() in Iterator) (instead of relying on exceptions for control flow).


Apply capitalization of one string to another

We can do this in single traversal rather then two

for (int i = 0; i < min(apple.length(),orange.length()); i++) {
    if (Character.isUpperCase(apple.toCharArray()[i]) &&
        Character.isLowercase(oranger.toCharArray()[i])){
           orange[i] = Character.toUppercase(oranger.toCharArray()[i]);
    }elseif(Character.isLowerCase(apple.toCharArray()[i]) &&
            Character.isUppercase(oranger.toCharArray()[i])){
           orange[i] = Character.toLowercase(oranger.toCharArray()[i]);
    }
}


fixed size memory allocator interface without fragmentation on freeing the memory

Thoughts as I read through your post:

  On returning the memory there is no risk of memory fragmentation

I'm not sure what you mean.  Do you mean that all the memory will be free i.e. not leaked?  I don't see anything related to memory fragmentation.

char arr[4];

I don't know your use case, but 4 bytes is very small for a modern computer.  You could easily spend 100 times longer dereferencing a pointer than reading 4 bytes.  Are you sure a linked list is the right choice here?

struct mem_struct *head=NULL;

If someone else makes a global variable named head in another .c file, then you will get a linker error because of duplicate symbols.  If you have to use a global variable, you should name it something distinctive like

struct mem_struct *global_mem_struct_head=NULL;

But a better idea is not to use a global variable at all, and pass a mem_struct* argument to each function.

//max no. of fixed size memory blocks initialized at once in a pool
#define total 10

How about this:

static const int max_init_memory_blocks = 10;

Now you effectively get the comment every time you use the variable, you get type checking, and even though this is a global, it's invisible outside of this translation unit/this file.

That said, you've done a good job adding comments throughout your code.

int mem_pool_init()

This function does initialization a fixed number of times.  Can you use a for loop?

calloc

If calloc succeeds and then fails, you'll leak the first allocations.

void* mem_grant

Why does this return void*?!  How is the user supposed to know they can only use the first few bytes?!

   while(total_pool_size < siz)   //insufficient memory in pool
       if(mem_pool_init())
          return NULL;

Isn't this an infinite loop?

I'm going to stop here.  I think you would find a lot of these mistakes with some very simple test cases.  Then you can post an improved version.


Just a few generic notes, I'm not familiar with Google App Engine:

HashMap<...> reference types could be Map<...>:

public Map<String, List<ListDisplay>> getData() {

See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces
I'd rename this variable to result to express its purpose:

List<ListDisplay> data = new ArrayList<ListDisplay>();

remove is unnecesary here, put will override it:

data.remove(d.getConstituency());
data.put(d.getConstituency(), hashlist);

Consider replacing the following with a Multimap:

// if null add
if (data.get(d.getConstituency()) == null) {
    List<ListDisplay> internal = new ArrayList<>();
    internal.add(d);
    data.put(d.getConstituency(), internal);
}
// else modify
else {
    List<ListDisplay> hashlist = data.get(d.getConstituency());
    hashlist.add(d);
    data.remove(d.getConstituency());
    data.put(d.getConstituency(), hashlist);
}

The following uses Google Guava's Multimap and much simpler:

final ArrayListMultimap<String, ListDisplay> data = ArrayListMultimap.create();

for (ListDisplay d : list) {
    data.put(d.getConstituency(), d);
}

If you really need Map return type you can convert it  back to Map with data.asMap() which returns a Map<String, Collection<ListDisplay>> but you cast it down safely to Map<String, List<ListDisplay>>. (ArrayListMultimap javadoc supports this as well as these Stack Overflow posts.)
Variable names in Java usually camelCase.

String PARTY_ID = (String) entity.getProperty("partyId");

Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs and editors could show blocks.

    } // end loop entity2

“// …” comments at end of code block after } - good or bad?


When you tackle a programming challenge like this, it's a good idea to test out your program to see if it's fast enough, before you submit it. The problem description usually tells you how big the worst case is going to be, so it's a good idea to make a test case that's as big as the worst case, and then try out your program on it.

In this case, the problem description says,

  Each of the remaining \$P\$ lines contains the year of election of a Pope, in chronological order. We know that \$P≤100000\$ and also that the last year \$L\$ in the file is such that \$L≤1000000\$, and that \$Y ≤L\$.

So there could be as many as 100,000 popes! Let's make some sample data using this program:

Y = 100                         # Years in range of interest.
P = 100000                      # Number of popes
L = 1000000                     # Maximum year.
print(Y)
print(P)
for i in range(P):
    print(i * L // P)

Let's try it:

$ python make-popes-data.py > popes.txt
$ /usr/bin/time python cr150204.py < popes.txt
10 0 90
        0.71 real         0.65 user         0.05 sys

That doesn't seem so bad — 0.71 seconds. But remember that the problem statement says that \$Y\$ might be large — perhaps as large as \$L\$. So let's increase \$Y\$ to 1,000 and try again:

$ /usr/bin/time python cr150204.py < popes.txt
100 0 990
        4.25 real         4.19 user         0.05 sys

That would already fail the 3 second time limit at UVa Online Judge. But what if \$Y\$ was even larger? Let's increase \$Y\$ to 10,000 and try again:

$ /usr/bin/time python cr150204.py < popes.txt
1000 0 9990
       45.04 real        44.70 user         0.17 sys

45 seconds! So it should be clear now what the problem is. The code in the post has two nested loops. The outer loop is over all the popes:

for i in range (N_P):

and the inner loop is over the popes that are elected less than \$Y\$ years after pope number \$i\$:

while(popes[j] <= popes[i] + Y):

So if \$Y\$ is big, then the inner loop might have to loop over a large fraction of the popes — and to do so for every pope in the outer loop. This is quadratic runtime behaviour.

You need to change the program so that it doesn't have this behaviour. But how can you do that? For this problem, the thing to do is to think about how you would solve the problem by hand. You might start with the first pope and count the popes that are elected in the next \$Y\$ years. But at that point you wouldn't throw away all your work and start again with the second pope — instead you would ... well, I don't want to spoil it for you!


Haskell searching through a large textfile efficiently

I think you've missed the forest for the trees. While the origin of your list might be IO, there's no need to carry values around inside the IO monad just because that's where you found them.

Write your functions as though the external world doesn't exist. E.g.—

-- Was `good`
pigExists :: String -> Set String -> Bool
pigExists word set = Set.member (toPigLatin word) set

Write your actions to set up the values you need to use your IO-ignorant functions. E.g.—

main :: IO ()
main = do
    allWords <- words <$> readFile "wherever" -- equivalent to `allWords <- wordList`
    let pigHits = map (\word -> pigExists word (Set.fromList allWords)) allWords
    print $ length $ filter id pigHits -- Or some other IO action that does what you need

When in doubt, parameterize. You tripped yourself up by defining wordSet directly on wordList instead of just accepting any [String] value you're passed.


Reordering items which must have alphabetically ordered keys

public static List<Item> MoveIndex(this List<Item> myItems, int from, int to)

Code to the interface, not the implementation: you might be able to rewrite this as

    public static IList<Item> MoveIndex(this IList<Item> myItems, int from, int to)

and if not you can almost certainly rewrite it as

    public static TList MoveIndex<TList>(this TList myItems, int from, int to)
        where TList : IList<Item>

        for (int i = 0; i < myItems.Count; i++)
        {
            myItems[i].Key = i.ToString("D2");
        }

For a start, this looks too tightly bound to me. From the description given I would expect MoveIndex to work with the existing keys, whatever they are.

But given the strong assumptions made here, I wonder whether there's a better solution based on eliminating the List<Item> entirely. Can you maintain an IList<string> which contains the labels and then generate the items lazily with IEnumerable<string>.Select(Func<string, int, Item>)?


You can modify the input until there's nothing left of it.  In this example, I've used a regex with .replace() to shorten the FQDN.

If you don't like regex, you could instead split the domain name on ., then in the loop use dom.join(".") to compose the object key, followed by dom.shift() to shorten the array.  With the array technique, the loop conditional is dom.length (instead of just dom).

function getDomainHits(arr){
    let total={};
    arr.forEach( row => {
        let [hits, dom] = row.split(",");
        hits=parseInt(hits);
        while ( hits && dom ) {
            total[dom] = (total[dom] || 0) + hits;
            dom = dom.replace( /^[^.]*\.?/, '' )
        }
    });
    return total;
}


Bugs

You are losing precision by calling sc.nextFloat() instead of sc.nextDouble().

If the equation has complex roots, Math.sqrt(discriminant) will crash.

Style

You are using too many variables to easily keep track of them mentally.  Also, it's better to avoid a giant block of declarations like your

double numOne, numTwo, numThree, negativeB,
        discriminant, divisor, sqRtDisc, dividendPlus,
        dividendMinus;

We know that we need to store at least a, b, and c, so let's start there.  Why not use the conventional terminology instead of numOne, numTwo, numThree?

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the value for A: ");
    double a = sc.nextDouble();

    System.out.println("Enter the value for B: ");
    double b = sc.nextDouble();

    System.out.println("Enter the value for C: ");
    double c = sc.nextDouble();

from there, the next important calculation is the discriminant, and optionally, its square root and the divisor.

    double discriminant = (b * b) - 4 * a * c;
    double divisor = 2 * a;

From there, you could go straight to formatting.  I suggest System.out.printf() for readability.

    if (discriminant < 0) {         // Complex roots
        System.out.printf("x = %d + %d i\n",
                          -b / divisor, Math.sqrt(-discriminant) / divisor));
        System.out.printf("x = %d - %d i\n",
                          -b / divisor, Math.sqrt(-discriminant) / divisor));
    } else {
        System.out.println("x = " + (-b + Math.sqrt(discriminant)) / divisor);
        System.out.println("x = " + (-b - Math.sqrt(discriminant)) / divisor);
    }
}


Python - Hexadecimal to Decimal conversions

First -- document your code!  I read through your d_func function and here's my attempt at writing a docstring for what it does, with Python-2-compatible type hints.  Hopefully I got it right.  :)

def d_func(digit, mode):
    # type: (Union[str, int], int) -> Union[int, str, None]
    """Mode 1: give the int value of the hex digit.
    Other modes: give the hex digit of the given value.
    Returns None if you give it a bad value, I guess?
    """
    if mode == 1:
        for x in range(len(d_dict.keys())):
            if digit == list(d_dict.keys())[x]:
                return x
    else:
        for y in range(len(d_dict.values())):
            if digit == list(d_dict.values())[y]:
                return list(d_dict.keys())[y]
    return None  # stumblebum

Right off the bat: this should not be one function.  (The fact that it can return either an int or a str depending on its input type is a good clue!)  You should have one function that converts value to digit and another that converts digit to value; there's no value at all to having one function that does completely different things depending on a flag you pass it.

Second: yes, this can be a lot simpler.  I think you could implement d_func as follows:

d_dict = {"0" : 0, "1" : 1, "2" : 2, "3" : 3, "4" : 4, "5" : 5, "6" : 6, "7" : 7, "8" : 8, "9" : 9, "A" : 10, "B" : 11, "C" : 12, "D" : 13, "E" : 14, "F": 15}
d_dict_reverse = {v: d for d, v in d_dict.iteritems()}  # this is just building a new dictionary with the keys and values swapped

def d_func(digit, mode):
    # type: (Union[str, int], int) -> Union[int, str]
    if mode == 1:
        return d_dict[digit]
    else:
        return d_dict_reverse[digit]

At that point, it doesn't need to be a function at all, because you're just doing a simple dictionary lookup.  Give your dictionaries reasonable names that say what they do:

digit_to_value = {
    "0" : 0, "1" : 1, "2" : 2, "3" : 3, "4" : 4, "5" : 5, "6" : 6, "7" : 7,
    "8" : 8, "9" : 9, "A" : 10, "B" : 11, "C" : 12, "D" : 13, "E" : 14, "F": 15
}
value_to_digit = {v: d for d, v in digit_to_value.iteritems()}

and then instead of:

d_num = d_num + 16 ** p * d_func(h_num[digit - 1], 1)

do:

d_num = d_num + 16 ** p * digit_to_value[h_num[digit - 1]]

and instead of:

    for f in f_list[::-1]:
        h_num += d_func(f, 2)

do:

    for f in f_list[::-1]:
        h_num += value_to_digit[f]

With this approach, not only do you not have to write a function, but unlike your function the dictionary will automatically raise a KeyError if you provide the wrong kind of input, e.g. if you do value_to_digit[100] or digit_to_value[1].  Raising an error ASAP when you mess up (aka "fail fast") is good, because it makes it easier to figure out exactly where your bug is.  :)


Decorate instance method with (arbitrary) meta data in python

From your three approaches, I think MacroWithoutSuperclass is probably the cleanest. I wanted to just comment a bit, but it turned out I had too much to say... Thus, here a few remarks followed by a maybe more intuitive solution as an inspiration (it's probably not perfect).

None of your methods supports arbitrary meta data, in case that is a requirement, but only name. In the following I assume that you in fact want to add arbitrary data.

You are assigning meta-data by name, so that e.g. macro.name is accessible. Is that a requirement? Or would macro.meta['name'] be enough? Below I will present both options, but it is not really clear from you question, only implicitly from your code.

All of your three methods seem in general very complicated.
For example

if self._func is None:
    assert len(args) == 1 and len(kwargs) == 0
    self._func = args[0]
    return self
else:
    return self._func(*args, **kwargs)

is quite complicated and should have some more explanations.

The inheritance

class MacroWithIfInCall(MethodDecoratorWithIfInCall):
    def __init__(self, name):
        super(MacroWithIfInCall, self).__init__()
        self.name = name

is not needed (the same applies to MacroWithExplicitDecorate), instead you can assign the name in MethodDecoratorWithIfInCall's init function – exactly as you did in the MacroWithoutSuperclass. Which is basically why I think a combination of the MacroWithIfInCall (the __call__ function) and the MacroWithoutSuperclass would be the best solution using your approach.

I don't understand why you need wildcard parameters (# wildcard parameters to satisfy PyCharm) for one class, but not for the others, you shouldn't need them in either case.

Anyways, I think you can fare much better with an even simpler decorator, as I will explain below.

I will try to go along your list and provide some comments to answer your requirements.

  it is 'easy' to retrieve all such methods for a given class instance

This is sufficiently easy using inspect.getmembers:

import inspect

types = (MacroWithIfInCall, MacroWithExplicitDecorate, MacroWithoutSuperclass)
macros = inspect.getmembers(Shell, lambda m: isinstance(m, types))

Note however, that macros is now a list containing tuples of the form (name, function). Dependending on your use case you might have to use any of the following lines:

names = [macro[0] for macro in macros]  # Get only the names
funcs = [macro[1] for macro in macros]  # Get only the functions
names, funcs = zip(*macros)  # Get names and functions in separate lists

  methods can still be called 'in a normal way', e.g. obj.method()

This is fine, and will be the case for the classic decorator which follows this form:

import functools

def decorator(func):

    @functools.wraps(func)  # Handles the docs and names properly
    def wrapper(*args, **kwargs):
        # Do something before the call

        result = func(*args, **kwargs)

        # Do something after the call

        return result

    return wrapper

In fact, for your problem slightly less complex, as you don't need to perform any tasks on execution but only when declaring the function, so in fact you can return the original function:

def meta(func):
    func.meta = 'meta data here'  # Assign constant metadata
    return func

  meta-data is accessible from the decorated method, e.g. obj.method.data

As mentioned above, I am not sure whether you mean that all meta data is contained in data or that data is just one part, and name, age, abc would be others.

To have this, you could now just assign these values by extending the decorator meta(func) I presented above. Remember that in Python, functions are just objects (search for "User-defined functions"):

  Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes.

This means, that instead of having your complex wrapper classes storing the meta data and the function you can just store the meta data at the function itself.

So the decorator meta needs to have a way to specify the meta data. The common way is building another function around it, which eventually returns the decorator.

def meta(**meta_data):
    """Attaches meta information to a method."""

    def _attach_meta(func):
        func.meta = meta_data
        return func

    return _attach_meta

To support the dot-notation (and not the meta-dictionary) the line func.meta = meta_data could to be changed to

for k, v in meta_data.items():
    setattr(func, k, v)
func.has_meta = True  # flag to use for inspect.getmembers' predicate

I would use the dictionary version unless you have a very strict set of meta attributes, as then accessing data using function.meta.get(KEY, DEFAULT_VALUE) becomes fairly useful.

  IDEs (PyCharm in particular) do not produce any warnings or errors (and, if possible, IDE support, e.g. auto-completion, should be able to handle the annotation)

I can't say anything about this, but I think it should work as you expect... I use YCM and am too lazy to install PyCharm now.

  Additionally, I would like the code to be readable/intuitive (not necessarily the super classes, though)

This should be sufficiently satisfied with the presented solution, although it is also lacking some (in-code) documentation.

  generally robust and 'bug-free'.

There can always be name clashes etc., and my solution does not have the strong typing your solution has. But for bug-free-ness, it is possible to add some tests, making it less buggy.

  I accept the limitation that my decorators need to be the most 'outer' decorator for the automatic collection to take place.

This should still be the case, I fear. But I haven't tried to solve this.

Full working example

import inspect

def meta(**meta_data):
    """Attaches meta information to a method."""

    def _attach_meta(func):
        func.meta = meta_data
        return func

    return _attach_meta

def has_meta(func):
    """Predicate to check for meta data."""
    return hasattr(func, 'meta')

class SomeAnnotated:
    @meta(a=1, b=2)
    def __call__(self):
        """The call method."""
        return 'Hello'

    @meta(x=3, y=4)
    def annotated(self, abc):
        """The annotated method."""
        return abc

    def not_annotated(self):
        """The not annotated method."""
        return 'Not annotated'

print('Meta information is available for:')
for name, func in inspect.getmembers(SomeAnnotated, has_meta):
    print(f'{func.__qualname__}: {func.meta} -- {func.__doc__}')

Expected output:

Meta information is available for:
SomeAnnotated.__call__: {'a': 1, 'b': 2} -- The call method.
SomeAnnotated.annotated: {'x': 3, 'y': 4} -- The annotated method.

Edit: As per comment here is a solution more closely related to your idea around a non-data descriptor (i.e. using __get__):

import inspect
import functools

class MetaAnnotated(functools.partial):
    pass

class MetaAnnotator:
    def __init__(self, func, **meta_data):
        self.func = func
        self.meta = meta_data

    def __get__(self, obj, type=None):
        annotated_func = functools.wraps(self.func)(MetaAnnotated(self.func, obj))
        annotated_func.meta = self.meta
        return annotated_func

def meta(**meta_data):
    """Attaches meta information to a method."""

    def _attach_meta(func):
        return MetaAnnotator(func, **meta_data)

    return _attach_meta

def has_meta(func):
    """Predicate to check for meta data."""
    return isinstance(func, MetaAnnotated)

The above solution uses functools for two purposes: first, to retain the documentation etc (wraps). Second, and more importantly, to create a partial function which is called with our instance as self. In a step-by-step solution we would do this as follows (each block represents a change to understand the code, not a sequence of commands):

# annotated_func behaves the same as func, but will
# always use "obj" as its first argument.
annotated_func = functools.partial(func, obj)

# We can inherit from functools.partial to have a tagging class:
class MetaAnnotated(functools.partial): pass
annotated_func = MetaAnnotated(func, obj)

# Keep the doc string from func:
class MetaAnnotated(functools.partial): pass
annotated_func = functools.wraps(func)(MetaAnnotated(func, obj))

This way, no __call__ is needed, neither is a staticmethod: as soon as the function we decorated using MetaAnnotated is searched for on the original object, the properly wrapped function is returned (instead of the MetaAnnotator!).

This behaves almost the same as the solution without typing, but it does not have the func.__qualname__ needed in my test prints, so we need to change this. I also added a "proof" that it's properly callable:

print('Meta information is available for:')
for name, func in inspect.getmembers(SomeAnnotated, has_meta):
    print(f'{name}: {func.meta} -- {func.__doc__}')

instance = SomeAnnotated()
print(instance())
print(instance.annotated(123))

I think this is a nice synthesis between your original ideas about using the descriptors and my ideas of having a very plain and straight forward decorator. All the "magic" happens in one place (the MetaAnnotator), the MetaAnnotated class transparently tags functions, and there is a very neat API: a user just needs to call @meta and can forget about everything else.


Improve performance while Traversing List

You can actually change the performance to O(n) by changing one line of code here (and adding a couple of imports):

import java.util.Set;
import java.util.HashSet;

...

private Set<String> listTempName = new HashSet<>();

Although this works, we can simplify the code a little bit. Effectively, you want to see if the list of elements in the given List are unique. There's a really easy way to do this: add them all to a Set. If the size of the set and the size of the list are equal, then there are no duplicates. If the sizes are different, then there must be 1 or more duplicate elements. With this, we can simplify your code to:

public boolean isPreviousNameExist()
{
    for(String name : listNames) {
        listTempName.add(name);
    }
    return listNames.size() != listTempName.size();
}

A slight improvement based on comment by @bowmore:

public boolean isPreviousNameExist()
{
    for(String name : listNames) {
        if(!listTempName.add(name)) {
            return true;
        }
     }
     return false;
}


Any way to optimize this already fast Python solution to Project Euler 31 (coin sums)?

It will be faster if you pre-generate the ways_to_make array:

def count_coins(sum, coins):
    ways_to_make = [0 for _ in range(sum + 1)]
    ways_to_make[0] = 1
    for coin in coins:
        for t in range(sum + 1):
            if t >= coin:
                ways_to_make[t] += ways_to_make[t - coin]

    return ways_to_make[sum]

This doesn't waste memory because you would allocate those elements anyway, and it's a lot faster to create a larger list once than extending it in every loop iteration. Not to mention that this gets rid of an if statement.

I also changed the for o in range(len(coins)) loop to the more intuitive for coin in coins. In my measurements this gave an extra speed boost too.

Finally, I took the liberty to rename your function parameters to more meaningful names.


Overall, you've got decent structure there. However, there are a few things I can see from my limited experience.

You defined an associative array $data at the beginning. From experience, it usually works best to define it fully up front instead of in bits and pieces. This is not required in PHP like it is in Java, but it usually works better because it keeps your code looking clean and organized. It's hard to know what exactly is in your array if you add to it in multiple places.

From what I can see, you don't have any specific delimiters or checks to see if the inputs exist, this should be the first thing you do. If something is null, there should be red flags going up.

That being said, inside the try statement you insert into the database twice. Both times you pass $data to the insertGetId() magic method. While you do want to pass an associative array, you must make sure that all required fields are in that array. Effectively, you're duplicating your data with just an extra column.

Reading your $data array, you have a column named 'till_account_id'. If I understand the project correctly, this field should be unique as no one person should share an account. There may be cosigners, but it isn't technically their account. That being said, I think the 'till_account_id' should be your primary key, which means your insert should look like this:

DB::table('till_transaction')->insertGetId($data,'till_account_id');

Be very careful when you return data. You return several variables defined inside of an if statement. If the update fails, it will return null which means !empty($update) will fail because you're trying to read a null object. The same goes for further down, when you return, all the values that were defined inside the if statement wouldn't exist, thus returning null.

Good job catching the exception and then rethrowing it to the caller. Most people would catch it and forget to handle it. That being said, though, depending on how specific of an app you're developing, it might be beneficial to make a custom exception class and do something like this:

catch (Exception $e) {
    //respond here as needed
    throw new CustomException('some message describing error',0,$e);
}

This would do whatever you need to do, then rethrow the exception in a more manageable fashion. You would have a message specific to what you need to explain - details are very important in debugging, you would have the error code, and you would have the previous exception passed to the new exception for the trace.


Calculate total width of a range of numbers

Note that your algorithm is not correct:

For example input n=9, add=2 it properly returns 27 (9*1 + 9*2), but for n=10 it should be 31 (+ 2 for representing "10" and +2 as defined by add) but your algorithm returns 32.

The error increases drastically as n grows. For example n=10000, add=2 it returns 1098374! Even if all the 10000 numbers would be 5 characters long, it would be a really high estimation of 10000*5 + 10000*2 = 70000 (instead of a million).

All the following implementations along with the benchmarking code can be found on the Go Playground. The code posted there is not an executable but a test file. Save it in a file like XX_test.go, and run go test -bench . to run the benchmarks.

The algorithm

Let's examine the algoritm. Since the extra space add has to be added for each number, it always means n * add to the number of total digits. We can incorporate this at the end, so we don't have to think about it. So let's reduce the problem and algorithm putting add aside for now.

Example

Let's take the input number n=23456. How can we calculate the total length of all numbers starting from 1 up to 23456?

The numbers whose length is 5 digits is 13456 + 1, their length: 13456*5 + 5
Numbers with 4 digits and their length: 9000*4
Numbers with 3 digits and their length: 900*3
Numbers with 2 digits and their length: 90*2
Numbers with 1 digit and their length: 9*1

Formalize

Let's formalize the algorithm:

Subtract 1 from the first digit and add +1 to the result, and multiply the result with the digits count of this number.
Add the total number of digits of all the numbers having less digits.
Add extra digits specified by the add parameter.

Implementation

Things to note:

To determine which power of 10 preceeds the input n, we may use a loop always multiplying the previous number by 10. These multiplications (the powers of 10) are constants, we don't need to do this in the function, we can precalculate them and store them in a slice beforehand. Note that for practical reasons, I will store the power of 10's -1. See below the implementation for details.

var pows = []int{0, 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999}

If we have a sorted slice of the power of 10's, we can use binary search to find the power of 10 for our input number. However as this slice is small (~10 elements), it is faster to just loop over it in a sequencial way.

The total number of digits of all numbers having the same width (same amount of digits) are also constant values. We will precalculate these and store them so we don't have to repeat this constant calculation. For the first 8 digits:

var sums = []int{0, 9, 189, 2889, 38889, 488889, 5888889, 68888889, 788888889}

To find the power of 10, it's a simple loop, something like this:

for i := 1; ; i++ {
    if n <= pows[i] {
        // Found it, n is lower than pow(10, i) and greater than pow(10, i-1)
    }
}

The code

Once we have the power of 10 (its index is i), the formalized algorithm:

Subtract 1 from the first digit:
n - (pows[i-1]+1)
Add +1:
n - (pows[i-1]+1) + 1 = n - pows[i-1]  (this is why we stored powers of 10 -1)
Multiply with the digits count:
(n-pows[i-1])*i
Add the total number of digits of all the numbers having less digits:
(n-pows[i-1])*i + sums[i-1]
Add extra digits specified by the add parameter:
(n-pows[i-1])*i + sums[i-1] + n*add

And that's all! It's extremely short and compact! It contains 2 multiplications, no divisions, and maybe like 10 additions and subtractions!

The complete code:

var sums = []int{0, 9, 189, 2889, 38889, 488889, 5888889, 68888889, 788888889}
var pows = []int{0, 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999}

// n must be in the range of 1..999999999
func GetBufLen(n, add int) int {
    for i := 1; ; i++ {
        if n <= pows[i] {
            return (n-pows[i-1])*i + sums[i-1] + n*add
        }
    }
}

Further optimization for small numbers

If the GetBufLen() is called frequently with small numbers, it is profitable to put some additional code which "hardcodes" simplified handling of these cases. Here it is:

// n must be in the range of 1..999999999
func GetBufLenOpt(n, add int) int {
    if n < 10 {
        return n + n*add
    }
    if n < 100 {
        return n*2 - 9 + n*add
    }

    for i := 3; ; i++ {
        if n <= pows[i] {
            return (n-pows[i-1])*i + sums[i-1] + n*add
        }
    }
}

Benchmarking, speed analysis

Let's compare the speed of this algorithm with yours. We'll write a short benchmarking code, one for each of the functions (all look like this, except they call the appropriate function):

func BenchmarkLen(b *testing.B) {
    for i := 0; i < b.N; i++ {
        for j := 1; j < testUpTo; j++ {
            GetBufLen(j, 2)
        }
    }
}

Benchmark results

testUpTo = 1000: ~21% faster

BenchmarkLen      200000              7750 ns/op
BenchmarkLenOpt   200000              6365 ns/op
BenchmarkLen2     200000              8120 ns/op

testUpTo = 100000: ~26% faster

BenchmarkLen        2000           1025102 ns/op
BenchmarkLenOpt     2000            974097 ns/op
BenchmarkLen2       1000           1328132 ns/op

testUpTo = 1000000: ~28% faster

BenchmarkLen         100          11591159 ns/op
BenchmarkLenOpt      100          11691169 ns/op
BenchmarkLen2        100          16331633 ns/op


I'm not into C++, but here's a suggestion for what it is worth.  Create a class that encapsulates the array, let's call it Array. Define an operator[] method that gives you the value of the element of the array at (x,y);  the function returns 0.0 if the coordinates are invalid.  Another method, n_points, returns the number of valid points around (x,y) - ie. 4, 6 or 9. Then you can compute the average using the following function, ignoring where the point (x,y) is located in the array:

float average(const Array &array, int x, int y)
{
    return
        (array[x-1,y-1] + array[x,y-1] + array[x+1,y-1] +
         array[x-1,y]   + array[x,y]   + array[x+1,y] +
         array[x-1,y+1] + array[x,y+1] + array[x+1,y+1])
        / array.n_points(x,y);
}

That won't be more efficient (the reverse probably), but it would be more readable.


Select multiple minimum items in an Array

You can achieve what you want, just with one for loop:

int minIndex = 0;
List<Integer> list = new ArrayList<>();

for (int i = 0; i < array.length ; i++) {
    if (array[i] == array[minIndex]) {
        list.add(i);
    } else if (array[minIndex] > array[i]) {
        list.clear();
        list.add(i);

        minIndex = i;
    }
}

return list;

Changes and recommendations:

I think that you must change the name of the method variable to 'array', since there is a Java collection class named ArrayList and it could confuse some readers of your code
You should also change the method name, since from its name it is not clear that it returns a list of min indexes. Maybe getMinIndexes could be used
Regarding the old code, I think that you should use less temporal variables, in your case len variable, doesn't give any more semantic to the code, so it could be removed. When you works with arrays consider the usage of for loops.

Update

As additional recommendations I would add:

I think that 'find' could be used as prefix instead of 'get', since you are actually searching for those indexes, you don't getting them from some POJO
I also think that it is better if you are using curly brackets even in a single line block statements
Also there is no need of transforming the list into array and then into string in the debug log. Lists has nice implementation of toString function that would print the elements the same way as Arrays.toString


Finding common strings among 2 arrays of strings of length 1, sorted alphabetically in O(n) time complexity

Java is not my strong-point, but there are a few things that stand out.

Spacing is non-standard.
There are unnecessary parentheses, e.g. in

(i<a.length)&&(j<b.length)

and

if(!(a[i].equals(prev)))

Optional braces should always be included, e.g. in

if(!(a[i].equals(prev)))
    result++;

Statements should always be on separate lines, e.g. don't do

i++; j++;

There is a more elegant solution using a HashSet<String>, which I believe has the same time complexity.

public int commonTwo(String[] a, String[] b) {
    Set<String> common = new HashSet<>(Arrays.asList(a));
    common.retainAll(new HashSet<>(Arrays.asList(b)));
    return common.size();
}


Sort all even numbers in ascending order and then sort all odd numbers in Descending order Java

You already dug into the standard library a bit (which is good) and discovered the beautiful sort method. Using this method is a perfect start.

What you overlooked is, that there is an overloaded second version of sort which accepts a comparator, so that you can perform all kinds of custom sorting with a single call.

Thus, instead of splitting the list in even and odd parts, sorting them separately, reversing one part, gluing it all back together, you could simply have created a comparator which encapsulates the logic, passed this into the sort method, and be done.

(BTW: even if you take your approach, reversing a list should be done with Collections.reverse())

So: create a comparator, do it all in a single sort call, and I look forward to see your revamped solution here in a day or so. And while you are at it: "GFG" is not an acceptable class name: what does that class do? Give it a name worth remembering!


Getting a Future from a Vector and a function

I think the best is to simply use then() and collect():

use futures::{Future, StreamExt};

pub async fn traverse<I, T, F, Fut, O>(xs: I, f: F) -> Vec<O>
where
    I: IntoIterator<Item = T>,
    F: Fn(T) -> Fut,
    Fut: Future<Output = O>,
{
    futures::stream::iter(xs).then(f).collect().await
}

Note:

futures generic should be name Fut
function generic should be name F
I rename R as O but I don't know if it's better but it's my way.
Doesn't need FutureExt


Performing a regex search and saving results to CSV

10 Tips, Problems, etc.

Don't begin comments with # ###
Put the code that you had outside of functions in a main() function. This makes it so that if the module is imported, this code won't be run inadvertently. You can use this standard framework:

def main():
    # put code here that you want to run when file is executed

if __name__ == "__main__":
    main()

Spell words in your comments correctly, and wrap them to a new line if they are getting too long. (After a few years of coding I have found that the vast majority of comments needn't be longer than one line.)
Use with open("file.txt", 'r') as f: whenever working with files
Always end your file with a new line
When comparing to None use is and not instead of == and !=
Actually catch the three return values of the regex_search method explicitly with a well-named variable
No capital letters in variable names according to pep-8 guidelines
I find it much easier to use print than write when writing to a file inside of a with open() statement:

print(some_text, file=some_file, flush=True)

Use string.format() instead of the deprecated old string formatting tools (%s...)

# coding: utf-8

import re
import csv

def regex_search(pattern, file_name):
    remove_arr = []
    res = []
    remain_sms = []
    for sms in file_name:
        j = re.match(pattern, sms)
        if j is not None:
            res.append(j.groupdict())
            remove_arr.append(sms)
        else:
            remain_sms.append(sms)
    return res, remove_arr, remain_sms

def write_to_csv(result, csv_name):
    keys = result[0][0].keys()
    with open(csv_name, 'wb') as output_file:
        dict_writer = csv.DictWriter(output_file, keys, dialect='excel')
        dict_writer.writeheader()
        dict_writer.writerows(result[0])

def main():
    # Run this part only once in the starting. From here

    # change the directory to working folder and give the right filename (hdfcbk),
    # if unsure what to do go to your folder and right click and copy the file here,
    # it will look like /home/XYZ/.../Your_folder_name/hdfcbk
    with open('hdfcbk', 'r') as smsFile:
        data = smsFile.read()
    data = data.split('\n')
    main_data = data
    regl = []

    pat1 = 'INR (?P<Amount>(.*)) deposited to A\/c No (?P<AccountNo>(.*)) towards (?P<Towards>(.*)) Val (?P<Date>(.*)). Clr Bal is INR (?P<Balance>(.*)) subject to clearing.'

    # TODO - Use much more descriptive names...no idea what's going on here without searching for a while
    a, b, c = regex_search(pat1, main_data)

    # Updating main_data to remaining messages
    main_data = c

    # Writing remaining sms to a file, you don't need to change the file name as it will be updated
    # everything as you run the script. Just look at the remaining sms and make new regex.
    with open('remaining_sms.txt', 'w') as fp:
        fp.write('\n'.join('{}'.format(x) for x in main_data))

    # Update the csv file
    write_to_csv([a, b, c], 'hdfc_test_3.csv')

    # Keeping all the regexes in one list, update the index number in [i, pat1]
    regl.append([1, pat1])

    # Writing the regex index to csv, run this part in the end, or if you're unsure that you will
    # make the mistake run this part and keep changing the output file name.
    with open("output.csv", "wb") as f:
        writer = csv.writer(f)
        writer.writerows(regl)

if __name__ == "__main__":
    main()


Modifying database using POSTed variables in PHP

If I were you, I'd create a function that looked like this:

function getArrayValues( array $array, array $keys)
{
    $result = array();
    foreach($keys as $key)
    {
        if (!isset($array[$key]))
        {
            throw new RuntimeException($key.' is not set');
        }
        $result[$key] = $array[$key];
    }
    return $result;
}

This function will return an array, containing just those keys you were actually looking for. Then, in your try-catch block, I'd write this:

$values = getArrayValues($_POST, array('var1','var2','var3'));
$stmt = $db->prepare('your query here');
$stmt->execute($values);

And that's it.
Now I do have some worries/thoughts/suggestions about your code, but I'll add them in a future edit.

Edit:
You're throwing exceptions when an array-key does not exist. In this particular case, that might be desirable. You can't insert a row in your db, lest all data is at hand. I get that. But how often might you end up writing either:

try
{
    $var = demandArrayValue($someArray, 'isNotSet');
}
catch(Exception $e)
{
    $var = 'default value';
}

Or, to avoid having to write the try-catch too many times:

$var = isset($someArray['notSet'] ? $someArray['notSet'] : 'default value';

You could write 2 distinct functions: one throwing exceptions, one that doesn't, but that's just silly. getting array-keys shouldn't throw an exception. your code should be able to handle a missing parameter.
What's more, you place the demandArrayValue in the same try-catch block as all of your DB operations. If you're using PDO, and you've set the PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, then you're actually handling 2 distinct exceptions in the same catch block:

catch(Exception $e)
{//you have to catch Exception, since that's what demandArrayValue throws
    if ($e instanceof PDOException)
    {
        $db->rollBack();
        echo $e->getMessage();//handle DB exception
    }
    else
    {
        echo $e->getMessage();//handle other Exception
    }
}

Now, that's not nice. Besides, like I said before: dealing with the request parameters is something that is, actually, quite a complex task, but most, if not all frameworks, implement a (series of) request objects. You can write your own, too.
Once you've done that, you can actually use the getKey or get or getAll methods you might implement:

class PostRequest
{
    private $raw = null;
    private $data = null;
    public function __construct(array $data = null)
    {
        $data = $data ?: $_POST;
        $this->raw = $data;
        $this->setData();
    }
    public function get($name, $default = null)
    {
        if (isset($this->data[$name]))
        {
            return $this->data[$name];
        }
        return $default;
    }
    private function setData()
    {
        $this->data = array();
        foreach ($this->raw as $k => $v)
        {//validate, sanitize, decode... do whatever
            $this->data[$k] = trim($v);
        }
        return $this;
    }
}

You could expand on this basic template, with custom email validation, or number formatting and what have you, but you could just  as well implement some form of constant-system, to set the get method's behaviour:

const POST_EXCEPTION = 1;
const POST_DEFAULT = 0;
private $exceptionMode = false;

public function setExceptionMode($exceptionMode = self::POST_DEFAULT)
{
    $this->exceptionMode = !!$exceptionMode;
    return $this;
}
public function get($name, $default = null)
{
    if (!isset($this->data[$name]))
    {
        if ($this->exceptionMode === true)
        {
            throw new Exception($name. ' key is not set');
        }
        return $default;
    }
    return $this->data[$name];
}

This get method does everything yours does, and more... but please, do look into the linked answer, and look into how other frameworks deal with the request. It's all been done before, and you're free to copy with pride


Insert JSON data into rendered template after AJAX call

If you're using a jQuery collection more than once, make sure to set a variable, this means you don't have to do unnecessary DOM lookups:

 var $table = $('#table-body');

You can probably improve your append code to make it more legible. Personally I prefer utilising the jQuery methods where possible, such as .text().

 data = JSON.parse(data);
 $table.empty(); // empty is more explicit
 // iterate over the data
 data.forEach(function (buses) {
   // create a new table row and append it
   var $row = $('<tr>')
     .appendTo($table);
   // iterate over the buses
   buses.forEach(function (bus) {
     // create the cell, set the text,
     // and append it to the row
     $('<td>')
       .text(bus)
       .appendTo($row);
   });

 });

Since you're just doing a simple get, you can use jQuery shorthand $.get function:

$.get('/data/json', { bus_id : {{ bus_id }} })
  .success(function (data) {
    // do render
  });


Keep the scope of variables to a minimum

Since C99 we are allowed to mix declaration and code. At the moment, you have i, j, rest and so on in scope, even if day is out of the specification. That can lead to hard to find errors, for example if we accidentally use i++ where i isn't used.

Late declaration makes it easier to copy our code into other blocks also, but more on that later. So instead, let's push the declaration as late as possible and limit the scope:

#include<stdio.h>

int main(){
    int day;
    scanf("%d",&day);

    //Check for exceptions
    if(day<=1){
        printf("You cannot generate christmas tree");
        return 0;
    }
    else if(day>20){
        printf("Tree is no more");
        return 0;
    }

    // printf("Heres Your Christmas Tree:\n\n");

    // For first part
    int leaves=1;
    int branches=day+1;
    int max_leaves = 1+(branches-1)*2; // Arithmetic Progression
    for(int i=1;i<=branches;i++){
        for(int j=i;j<=max_leaves/2;j++){
            printf(" ");
        }
        for(int j=1;j<=leaves;j++){
            printf("*");
        }
        printf("\n");
        leaves=leaves+2;
    }

    // For remaining parts
    branches=branches-2;
    for(int rest=1;rest<=day-2;rest++){
        leaves=3;
        for(int i=2;i<=branches+1;i++){
            for(int j=i;j<=max_leaves/2;j++){
                printf(" ");
            }
            for(int j=1;j<=leaves;j++){
                printf("*");
            }
            printf("\n");
            leaves=leaves+2;
        }
        branches--;
    }

    // For stand
    for(int i=1;i<=2;i++){
        for(int j=1;j<=max_leaves/2;j++){
            printf(" ");
        }
        printf("*\n");
    }

    return 0;
}

Use whitespace to scan code quickly

Now that we've introduced late declarations, let us add some whitespace between operators. Gone are the days where bytes in source code where expensive. Unless you intend write-only code, make code easy to read. Debugging is much nicer in well-written and spaced code:

#include <stdio.h>

int main() {
    int day;
    scanf("%d", &day);

    // Check for exceptions
    if (day <= 1) {
        printf("You cannot generate christmas tree");
        return 0;
    } else if (day > 20) {
        printf("Tree is no more");
        return 0;
    }

    // printf("Heres Your Christmas Tree:\n\n");

    // For first part
    int leaves = 1;
    int branches = day + 1;
    int max_leaves = 1 + (branches - 1) * 2; // Arithmetic Progression
    for (int i = 1; i <= branches; i++) {
        for (int j = i; j <= max_leaves / 2; j++) {
            printf(" ");
        }
        for (int j = 1; j <= leaves; j++) {
            printf("*");
        }
        printf("\n");
        leaves = leaves + 2;
    }

    // For remaining parts
    branches = branches - 2;
    for (int rest = 1; rest <= day - 2; rest++) {
        leaves = 3;
        for (int i = 2; i <= branches + 1; i++) {
            for (int j = i; j <= max_leaves / 2; j++) {
                printf(" ");
            }
            for (int j = 1; j <= leaves; j++) {
                printf("*");
            }
            printf("\n");
            leaves = leaves + 2;
        }
        branches--;
    }

    // For stand
    for (int i = 1; i <= 2; i++) {
        for (int j = 1; j <= max_leaves / 2; j++) {
            printf(" ");
        }
        printf("*\n");
    }

    return 0;
}

By the way, your text editor should provide some automatic format feature. I formatted the code with clang-format -style="{BasedoNStyle: llvm, IndentWidth: 4}", since that's very similar to your variant.

Don't repeat yourself

Now that we have easy to read code, we can see that there are repeating patterns, namely

for(int k = init; k <= stop; k++) {
    printf("some string");
}

We have at least five occurrences. So let's write a small function:

void repeat_string(int times, const char* str) {
    for(int i = 0; i < times; ++i) {
        printf("%s",str);
    }
}

Let's replace all occurrences of your loop with the function:

#include <stdio.h>

void repeat_string(int times, const char* str) {
    for(int i = 0; i < times; ++i) {
        printf("%s",str);
    }
}

int main() {
    int day;
    scanf("%d", &day);

    // Check for exceptions
    if (day <= 1) {
        printf("You cannot generate christmas tree");
        return 0;
    } else if (day > 20) {
        printf("Tree is no more");
        return 0;
    }

    // printf("Heres Your Christmas Tree:\n\n");

    // For first part
    int leaves = 1;
    int branches = day + 1;
    int max_leaves = 1 + (branches - 1) * 2; // Arithmetic Progression

    for (int i = 1; i <= branches; i++) {
        repeat_string(max_leaves / 2 - i, " ");
        repeat_string(leaves, "*");
        printf("\n");
        leaves = leaves + 2;
    }

    // For remaining parts
    branches = branches - 2;
    for (int rest = 1; rest <= day - 2; rest++) {
        leaves = 3;
        for (int i = 2; i <= branches + 1; i++) {
            repeat_string(max_leaves / 2 - i, " ");
            repeat_string(leaves, "*");
            printf("\n");
            leaves = leaves + 2;
        }
        branches--;
    }

    // For stand
    for (int i = 1; i <= 2; i++) {
        repeat_string(max_leaves / 2; " ");
        printf("*\n");
    }

    return 0;
}

Again, it's easier too read. Also, any optimization we find for repeat_string will now help at all five call sites. Great.

Exercises:

Write repeat_character(int n, char c), which prints a single character c a total of n times.
If we look closely, we can see that the branches look very similar:

for (int i = 1; i <= branches; i++) {           // <---
    repeat_string(max_leaves / 2 - i, " ");     // <---
    repeat_string(leaves, "*");                 // <---
    printf("\n");                               // <---
    leaves = leaves + 2;                        // <---
}

// For remaining parts
branches = branches - 2;
for (int rest = 1; rest <= day - 2; rest++) {
    leaves = 3;
    for (int i = 2; i <= branches + 1; i++) {   // <---
        repeat_string(max_leaves / 2 - i, " "); // <---
        repeat_string(leaves, "*");             // <---
        printf("\n");                           // <---
        leaves = leaves + 2;                    // <---
    }
    branches--;
}

Write a function that draws a single part, e.g. a trapezoid or pyramid width a given width, height, and so on.

Mark read-only values and locations with const

We denoted the str as const char* in order to make sure that we don't accidentally change string's contents. In the same spirit, we can add const to max_leaves:

…
const int max_leaves = 1 + (branches - 1) * 2; // Arithmetic Progression
…

Now typos like max_leaves /= 2 will get cought by the compiler.

Use 0…(n-1) as range, not 1…n

Your ranges use start = 1; i <= end; start++. Since we often work with arrays in C++ and arrays start with 0, it's more common to work with start = 0; start < end; start++. Keep that in mind for future code.

Other remarks

You mix leaves, branches and max_leaves, but their exact meanings are lost for the unprepared reader. Some additional comments can be helpful.

Other than that, the missing whitespace and therefore code structuring was my biggest criticism, but that's a minor point that can get fixed quickly.

Here's the complete code:

#include <stdio.h>

void repeat_string(int times, const char *str) {
    for (int i = 0; i < times; i++) {
        printf("%s", str);
    }
}

void repeat_character(int times, char c) {
    // Exercise 1
}

void draw_part(int height, int start_width, int max_width) {
    // Exercise 2
}

int main() {
    int day;
    scanf("%d", &day);

    // Check for exceptions
    if (day <= 1) {
        printf("You cannot generate christmas tree");
        return 0;
    } else if (day > 20) {
        printf("Tree is no more");
        return 0;
    }

    // printf("Heres Your Christmas Tree:\n\n");

    // For first part
    int branches = day + 1;
    const int max_leaves = 1 + (branches - 1) * 2; // Arithmetic Progression

    // For first part
    draw_part(branches, 1, max_leaves);

    // For remaining parts
    branches -= 2;
    for (int rest = 0; rest < day - 2; rest++) {
        draw_part(branches, 3, max_width);
        branches--;
    }

    // For stand
    for (int i = 0; i < 2; i++) {
        repeat_string(max_leaves / 2; " ");
        printf("*\n");
    }

    return 0;
}


Decide if 4 lengths form a square, rectangle or neither

Why do we need a set to find a square?
Why is a square not a subset of rectangle?
You can do the any check in the gon[0] == gon[2].
Why no filter on length of gon? Pentagons aren't squares...
gon is a poor name... do you mean polygon?
I agree with holroy, -5 makes sense, but 0 does not.

So I would do:

for shape in tgons:
    if shape[0] == shape[2] > 0 and shape[1] == shape[3] > 0 and len(shape) == 4:
        if shape[0] == shape[1]:
            squares += 1
        else:
            rects += 1
    else:
        neithers += 1

This can also be changed to allow all 2D rects/squares. (not lines.)

if shape[0] == shape[2] != 0 and shape[1] == shape[3] != 0 and len(shape) == 4:

Also follow PEP8 a bit more, as then you'll have easier to read code.
You mostly need more spaces:

Before and after infix operators.
After but not before commas.


Dispose() of types that implement IDisposable with using blocks:

using (var conn = new OleDbConnection(connectionString))
{
    conn.Open();
    using (var cmd = new OleDbCommand(query, conn))
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
            yield return formator(reader);
    }
}


You could start by adding the necessary imports as well:

import numpy as np
from matplotlib import pyplot as plt

Since you already said how you can improve performance here (it's not
going to be easier to read, at least not to people who don't "live"
matrixes), I'm going to sketch the idea, although at least one step
isn't clear to me as well.  Which is to say, I find the function plus
for-loop way more readable than the following.

Now, instead of computing the response one by one, just vectorise each
step in rec_lin.  With the following rewrite, which is a tiny bit more
structured:

def rec_lin_neuron(x_inter, max_fire, gain_sign, x_max=1.0):
    def rec_lin(x):
        factor = max_fire/(x_max-x_inter)
        fire = np.maximum(np.dot(gain_sign, x) * factor - x_inter * factor,
                          np.zeros(x.size))
        return np.minimum(fire, max_fire)
    return rec_lin

That would be:

diffs = np.subtract(np.repeat(1.0, n_neurons), x_cepts) # aka x_max-x_inter
factors = np.divide(max_firing_rates, diffs) # aka factor

Similarly for the rest of that function, with the exception of np.dot,
where it's not clear to me how you'd run that function element-wise
against the input array, maybe you already know the answer, otherwise
I'll try to update it later.

The maximum and minimum for the matrixes should be np.amax and
np.amin.


I find your code to be very good and readable :)

In the code you present here, I only see one mishaps :

raise 'Resource ID is required' unless id

is repeated multiple time and actually don't test for much.
I'd consider making a private method that check id and also check if id is not empty (or even if it isn't strip.empty? to consider only-spaces strings).

For the create method, can the option parameters really can be an empty hash ? If not I'd consider at least removing the default value for this.

I haven't read your whole repo, so I'm not sure but does the Tag class really need to include both Search and Ressource ?

Code like

@user_id = user_id ? user_id : 'self'

should be replaced with @user_id = user_id || 'self'

One important point : your code must be hard to unit test as it is coupled with HTTParty, you should consider using a Strategy pattern here.

Finally, I'd make some simple class that have only one or two fields (such as Tag, Location, User...) immutable by duping and freezing the parameter and freezing the whole object : (note that it won't work if you expect a boolean, a number, a Symbol or nil as dup raise an exception in such case :()

def initialize(user_id)
  @user_id = (user_id || 'self').dup
  @user_id.freeze
  freeze
end

I haven't done Ruby in some time so I'm a bit rusty but I hope my review helped you at least a bit :)


Calculate electric field of a charged annulus

I think the main time consuming factor here is calculating the dbquad, that said there are some smaller improvements you can make

split into functions

lookup of local variables in a function is faster than a global lookup, so putthing each part in a function can speed up this process already. If you do this, beware that your E_calc functions use global state (x0, y0 and z0), so they should be defined in the function scope, so they can use the local variables

numpy

You can use numpy a bit more to assemble the final answers

Instead of  keeping 2 arrays fields and errors, you can  keep this in 1 array, and index the errors and values.

def calc2():
    twopi = 2.*np.pi

    # annulus of uniform, unit charge density
    rmin, rmax   = 0.8, 1.2
    thmin, thmax = 0,   twopi

    x = np.arange(-2,    2.1, 0.1)
    z = np.arange(-1.55, 1.6, 0.1) # avoid z=0 plane for integration.
    X, Z = np.meshgrid(x, z)
    s = X.shape

    eps = 1E-4
    y0  = 0
    def Excalc(r, th):
        x, y, z = r*np.cos(th), r*np.sin(th), 0.0
        return (x0-x) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

    def Eycalc(r, th):
        x, y, z = r*np.cos(th), r*np.sin(th), 0.0
        return (y0-y) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

    def Ezcalc(r, th):
        x, y, z = r*np.cos(th), r*np.sin(th), 0.0
        return (z0-z) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5
    values = []
    for x0, z0 in zip(X.flatten(), Z.flatten()):
        # use of lambda in lieu of function calls https://stackoverflow.com/a/49441680/3904031
        Ex, Exerr  = dblquad(Excalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
        Ey, Eyerr  = dblquad(Eycalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
        Ez, Ezerr  = dblquad(Ezcalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
        values.append([Ex, Ey, Ez, Exerr, Eyerr, Ezerr])
#         errors.append([Exerr, Eyerr, Ezerr])
    values = np.array(values).T.reshape(6, *X.shape)

    e_vec = values[:3]
    e_mag = np.linalg.norm(e_vec, axis=0)

    e_vec_err = values[3:]
    e_mag_err = np.linalg.norm(e_vec_err, axis=0)

    return Evec, Emag, Evecerr, Emagerr

This resulted in a very slight reduction in time, so will not save you heaps

lru_cache

refactoring the calc methods to reuse the most of the result actually slowed things down, this is how I tackled that

from functools import partial, lru_cache

@lru_cache(None)
def calc(r, th, coords_0):
    coords_0 = np.array(coords_0)
    diff = coords_0 - np.array((r*np.cos(th), r*np.sin(th), 0.0))
    return diff * ((diff)**2).sum()**-1.5

def calc3():
    rmin, rmax = 0.8, 1.2
    thmin, thmax = 0, 2.*np.pi

#     s = X.shape

    eps = 1E-4
    y0  = 0
    x = np.arange(-2,    2.1, 0.2)
    z = np.arange(-1.55, 1.6, 0.2) # avoid z=0 plane for integration.
    X, Z = np.meshgrid(x, z)

    calc_axis = lambda r, th, coords_0, axis: calc(r, th, coords_0)[axis]

    values = []
    for x0, z0 in zip(X.flatten(), Z.flatten()):
        coords_0 = (x0, y0, z0)
        Excalc, Eycalc, Ezcalc = (partial(calc_axis, coords_0=coords_0, axis=i) for i in range(3))
        # use of lambda in lieu of function calls https://stackoverflow.com/a/49441680/3904031
        Ex, Exerr  = dblquad(Excalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
        Ey, Eyerr  = dblquad(Eycalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
        Ez, Ezerr  = dblquad(Ezcalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
        values.append((Ex, Ey, Ez, Exerr, Eyerr, Ezerr))
    print(calc.cache_info())
    values = np.array(values).T.reshape(6, *X.shape)

    e_vec = values[:3]
    e_mag = np.linalg.norm(e_vec, axis=0)

    e_vec_err = values[3:]
    e_mag_err = np.linalg.norm(e_vec_err, axis=0)
    return e_vec, e_mag, e_vec_err, e_mag_err, values

Apparently, about halve of the calls to calc were cached, but moving the calculation to this method resulted in a net slowdown.

numba

What did result in a speed increase was numba

just adding @jit before def calc(r, th, coords_0): made the calculation 3 times as fast


Passing parameters by reference? Let me fix that for you

Starting from this

var procedures = node.FindAllProcedures().Where(procedure => procedure.Parameters.Any(parameter => !string.IsNullOrEmpty(parameter.Instruction.Value)));
var targets = procedures.Where(procedure => procedure.Parameters.Any(parameter => parameter.IsImplicitByRef)
                                        && !procedure.Instruction.Line.IsMultiline);

return targets.SelectMany(procedure => procedure.Parameters.Where(parameter => parameter.IsImplicitByRef)
    .Select(parameter => new ImplicitByRefParameterInspectionResult(Name, parameter.Instruction, Severity)));

Let's collapse it into one expression

return node.FindAllProcedures()
    .Where(procedure => procedure.Parameters.Any(parameter => !string.IsNullOrEmpty(parameter.Instruction.Value)))
    .Where(procedure => procedure.Parameters.Any(parameter => parameter.IsImplicitByRef)
                                        && !procedure.Instruction.Line.IsMultiline)
    .SelectMany(procedure => procedure.Parameters.Where(parameter => parameter.IsImplicitByRef)
    .Select(parameter => new ImplicitByRefParameterInspectionResult(Name, parameter.Instruction, Severity)));

Move the last Select out of SelectMany

return node.FindAllProcedures()
    .Where(procedure => procedure.Parameters.Any(parameter => !string.IsNullOrEmpty(parameter.Instruction.Value)))
    .Where(procedure => procedure.Parameters.Any(parameter => parameter.IsImplicitByRef)
                                        && !procedure.Instruction.Line.IsMultiline)
    .SelectMany(procedure => procedure.Parameters)
    .Where(parameter => parameter.IsImplicitByRef)
    .Select(parameter => new ImplicitByRefParameterInspectionResult(Name, parameter.Instruction, Severity));

Now it seems like procedure.Parameters.Any(parameter => parameter.IsImplicitByRef) is redundant, so let's remove that and join the successive Wheres

return node.FindAllProcedures()
    .Where(procedure => procedure.Parameters.Any(parameter => !string.IsNullOrEmpty(parameter.Instruction.Value))
                        && !procedure.Instruction.Line.IsMultiline)
    .SelectMany(procedure => procedure.Parameters)
    .Where(parameter => parameter.IsImplicitByRef)
    .Select(parameter => new ImplicitByRefParameterInspectionResult(Name, parameter.Instruction, Severity));

It's not clear why procedure.Parameters.Any(parameter => !string.IsNullOrEmpty(parameter.Instruction.Value)) is necessary -- if it is, a comment is required, otherwise we can just write

return node.FindAllProcedures()
    .Where(procedure => !procedure.Instruction.Line.IsMultiline)
    .SelectMany(procedure => procedure.Parameters)
    .Where(parameter => parameter.IsImplicitByRef)
    .Select(parameter => new ImplicitByRefParameterInspectionResult(Name, parameter.Instruction, Severity));

Which is looking more much manageable. Or if you prefer the alternative syntax

return from procedure in node.FindAllProcedures()
       where !procedure.Instruction.Line.IsMultiline
       from parameter in procedure.Parameters
       where parameter.IsImplicitByRef
       select new ImplicitByRefParameterInspectionResult(Name, parameter.Instruction, Severity);


Create D lists of nodes where D is the depth of the binary tree

Are TreeNode and Solution in separate files? If the shown code is a single file, then it will not compile as you cannot have 2 top-level classes in the same file in Java.
Edit: Turns out it's fine as long as there is only one top-level public class.
Otherwise, just a few minor issues that I can see.
Diamond Operators
You have used the diamond operator <> for haMap and nodeDepth, but you should also use it on outputList and queue.
For example, instead of initializing outputList like:
List<List<Integer>> outputList = new ArrayList<List<Integer>>();

you should initialize it like:
List<List<Integer>> outputList = new ArrayList<>();

and similarly for queue, just like how you did for haMap and nodeDepth.
Favor interfaces over classes
When you define your collections, you should use an interface instead of specifying a specific implementation. That way you can change the implementation easily.
For example, you have done this for outputList and queue, but you should also do it for haMap, nodeDepth, and tempList.
haMap should be defined as:
Map<Integer, List<Integer>> haMap = new HashMap<>();

and similarly for nodeDepth.
Variable Names
Some of your variable names are decent, such as nodeDepth and outputList. They tell me what the object is used for as opposed to what it is. However, queue and haMap could be better. What is queue a queue of? What is being stored in haMap?


Enable more compiler warnings

I get

gcc-8 -std=c11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds      -Wconversion    199801.c    -o 199801

199801.c:21:35: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]
     int* counts = calloc(greatest + 1, sizeof(int));
                          ~~~~~~~~~^~~
199801.c: In function ‘main’:
199801.c:45:21: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]
     size_t length = argc - 1;   // number of integers to sort

The second of these can simply be silenced with a cast (since we have confirmed that argc >= 2), but the first probably indicates that greatest should be an unsigned type.  In fact, as we only accept positive values as input, we should probably use that same unsigned type for all the values we accept.

Match allocations and types automatically

You can help your code adapt better to changes in type (and make it easier to review), by allocating memory in terms of the pointer being assigned to:

int* counts = calloc(greatest + 1, sizeof *counts);

inputs = calloc(length, sizeof *inputs);

Now, if you decide to change type of counts is changed (perhaps to unsigned short), then it only needs to be changed in the one place, and there's less risk of inconsistency.  For inputs, it's now clear to reviewers that the type matches, without having to search back for the declaration (that said, in this case, it's probably better to declare it where it's initialized - we're not in C89 any more!).

Don't compare element 0 against itself

This is a trivial change, but will show understanding:

int greatest = arr[0];
for (size_t i = 0; i < len; i++)
    if (arr[i] > greatest)
        greatest = arr[i];

There's no need to compare arr[0] within the loop.  So we can change the for line to:

for (size_t i = 1;  i < len;  i++)

Beware of atoi()

This function doesn't report failures very well - if its input can't be converted, it just returns 0, which is indistinguishable from atoi("0").  I recommend you look at using strtol() and family for conversion:

char *end;
long val = strtol(argv[i], &end, 10);
if (val < 0 || val > INT_MAX || !argv[i][0] || !*end) {
    fprintf(stderr, "Failed to convert input value '%s'\n", argv[i]);
    return EXIT_FAILURE;
}
inputs[i - 1] = val;

Note that my error message doesn't make assumptions about the value of INT_MAX as yours does.

Use malloc() when memory doesn't need to be cleared.

I know you've been advised to use only one of malloc() and calloc() in your program, but I disagree.  Use calloc() when you want the extra behaviour of clearing the contents (or where the product of the two arguments might overflow a size_t), and use malloc() for allocations where you will be writing to the memory yourself.

Use puts() in preference to printf()

We can avoid the complexity of printf() when we output a simple newline-terminated string:

/*printf("\n");*/
puts("");    /* simpler */

Similarly:

    fputs(stderr, "Memory allocation error");


Extract Element and its Followers from List

The current version of the function does not take into account the cases:

(as @itsbruce mentioned) if the list starts with a value other than '1'
if there are consecutive '1's

The second case is using wildcards, but instead it'd better directly match a list starting with '1':

case 1 :: tail => {
  // we take only the following elements different from 1
  val followers = tail.takeWhile(_ != 1)
  // we drop the 'followers' prefix for the recursive call
  val remainder = tail.drop(followers.size)
  (1 :: followers) :: leadingOnesGroup(remainder)
}

Of course, this block can be shortened to two lines only, but it will be less readable.

Since it is not clear how to process lists that do not start with '1', a generic matcher with an explicit exception can be added:

case _ => throw new IllegalArgumentException("Unexpected start of list: " + xs)


You only need to compute half the table because it is symmetrical; for your line

a1[1..-1].each do |y|

instead do

a1[x..-1].each do |y|

and if you ever need to look up a * b where b > a, instead look up b * a

This will create a multiplication table that looks like this:

# old table
  1  2  3  4  5
1 1  2  3  4  5
2 2  4  6  8 10
3 3  6  9 12 15
4 4  8 12 16 20
5 5 10 15 20 25

# new table
  1 2 3  4  5
1 1 2 3  4  5
2   4 6  8 10
3     9 12 15
4       16 20
5          25

# final multiplication table
arr = [
  [1,2,3,4,5],
  [4,6,8,10],
  [9,12,15],
  [16,20],
  [25]
]

To access a*b where a >= b, the answer is in arr[a-1][b-a]
To access 3*4, the answer is in row 3-1, element 4-3 = arr[3-1][4-3] = arr[2][1] = 12
To access 5*2 (= 2*5), the answer is in row 2-1, element 5-2 = arr[2-1][5-2] = arr[1][3] = 10
To access 100x100 (assuming the range goes high enough), arr[99][0]

You'll need to do something slightly different if you are passing an array that isn't 1..x - in that case, first look up the index of each of the two numbers in the original array and use THEM in the arr[a-1][b-a] lookup.  I suspect you'll need to subtract 1 from the indices but I haven't worked it out in my head.


Uniformly generate a number from 0 to n-1 that isn't on a blacklist

The problem is backwards. You would never present a exclusion list for random values, rather you would present a list to randomly pick from.
Anyways to fit the problem.
Two ways this can be done

Guessing
Deterministically

Guessing
Your method use a random guess, you guess that the number is not in the list. If it is you guess again. This works well when the list contains only a small set of the numbers.
However when the exclusion list gets larger you need to make more guess to find one that is not in the list. The number of guess grows very fast as your exclusion list gets closer to excluding all.
This is the worst possible performance at \$O(m^{-(1/n)})\$ it has an Infinity
The other problem with guessing is that you can not know how long the function is going to run for. This makes it totally unsuitable for many real time applications.
Deterministically
You can improve the overall performance and have a function that has a known fixed time to get a result.
However is is much slower when the exclusion list is relatively small.
The performance is linear at \$O(n)\$
If the exclusion set does not change between calls it get even less complex at \$O(1)\$ which is the best you can get.
Example
The \$O(n)\$ solution
It returns undefined if it can not find a number rather than throw. You should not be solving the calling function problems as the other answers suggest.
const getRandNotInList = (n, list) => {
    const picks = [];
    const getPickable = () => {
        var i = 0; dir = Math.sign(n);
        list = new Set(list);
        while (i !== n) {
            !list.has(i) && picks.push(i);
            i += dir;
        }
    }
    n = Math.floor(n);
    if (n === 0) { return list.includes(0) ? undefined : 0 }
    getPickable();
    return picks[Math.random() * picks.length | 0]; // (| 0) same as Math.floor
                                                    // (only for positive ints).
}


Count number of nodes in a binary tree the OO way

I agree with the other posters that a visitor pattern would be a viable solution. One important reason being, that a node usually holds some payload, not just other nodes, and you want to have a mechanism that allows you to be very versatile on what you want to do with the data in the tree.

You may want to count the number of nodes, you might also want to count the number of nodes, where the payload matches some criteria, or you want to count the number of nodes that do not have a left and a right sub node or whatnot. You don't want your node to contain a method for every possible question you want to ask your tree.

You might want to read my blog post on the LOD and structure agnostic access for a rather freaked out, but general solution. But be warned it's possibly not the kind of code you might be used to and you might not find it particularly "pretty", as it trades type safety for "simplicity".

But a visitor is not the only good solution out there. You may prefer to implement a method that returns an iterator, or even a Stream of nodes. This way you could use the Java stream API and be very versatile.

As for the interview: I often feel that programming tasks in interviews are misplaced. The résumé should give you enough of an idea if you've got an experienced programmer or not. Once the person is hired, code conventions, code reviews and tests should shape the quality and style of the person's code to your needs anyway - and there's a probation period to see if the person is not up to your standards or toxic. The only thing that a little piece of code is good for, in my opinion, is to sort out freshmen and students who don't know how to code, but claim to do so. In job interviews I might like to talk about a piece of code and discuss its style, not for the sake of labeling the answers "right" or "wrong", but to see how they think about code: Are they the pragmatic kind of programmer, are they code-poets with a love of style and readability, will you have to brake their tendency for over-engineering or will you have to nurse them a bit more? Do they make good points, are they the timid or the outspoken kind of person? You might feel you lack the one or the other kind in your team and that might make a difference in the end. But I feel that, if I look at a résumé with plenty of projects on it, that I should be able to assume they know how to code and I don't want to insult them with giving them programming tasks that are not related to their daily work at this company, but rather to their first year in algorithms and data structures class.

Discussing your piece of code above, I would, for example find it perfectly reasonable, if the candidate said: "This is a pragmatic solution for counting nodes and maybe something similar, so if that's all there is to it, I'd be fine with it. Still, if it is foreseeable that we need more than just two or three queries, we should have another object do the query." That'd be bang on.


Searching local drive for multiple files

This seems to be faster by 5 seconds on 12:

Public Function DriveSearch(directory As String, pattern As String) As String()
    Dim filesFound As List(Of String) = Nothing

    Try
        filesFound = GetFilesRecurively(directory, pattern)
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try

    Return filesFound?.ToArray
End Function

Private Function GetFilesRecurively(directory As String, pattern As String) As List(Of String)
    Dim filesFound = IO.Directory.EnumerateDirectories(directory) _
                                 .AsParallel() _
                                 .SelectMany(Function(subDirectory) GetFilesRecurively(subDirectory, pattern)) _
                                 .ToList()

    filesFound.AddRange(IO.Directory.EnumerateFiles(directory, pattern))

    Return filesFound
End Function

This version beats them all taking only few milliseconds:

Public Function DriveSearch(directory As String, pattern As String) As String()
    Dim filesFound As List(Of String) = Nothing

    Try
        filesFound = IO.Directory.EnumerateFiles(directory, pattern, SearchOption.AllDirectories).ToList()
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try

    Return filesFound?.ToArray
End Function

You can also validate the arguments and save yourself a Try..Catch:

Public Function DriveSearch(path As String, pattern As String) As IEnumerable(Of String)
    Return If _
        (
            ArgumentsValid(path, pattern),
            Directory.EnumerateFiles(path, pattern, SearchOption.AllDirectories),
            Enumerable.Empty(Of String)
        )
End Function

Private Function ArgumentsValid(path As String, pattern As String) As Boolean
    If Not Directory.Exists(path) Then
        Console.WriteLine("Invalid path")
        Return False
    End If

    If pattern Is Nothing Then
        Console.WriteLine("Invalid pattern")
        Return False
    End If

    Return True
End Function