Populating dropdowns that are based on others

Your data doesn't mean much. I would suggest an array of objects so that the data will have meaning. Also, I would not recommend naming your variables based on data type. JS doesn't have strict types. You can easily assign anything to the variable. This means your dadArray may not be an array at some point.

var dads = [
  {id: 1, name: 'Dad1'},
  {id: 2, name: 'Dad2'},
];

var sons = [
  {id: 1, dadId: 1, name: 'Son1'},
  {id: 2, dadId: 1, name: 'Son2'},
  {id: 3, dadId: 3, name: 'Son3'},
  {id: 4, dadId: 2, name: 'Son4'},
];

So your operation involves:

Populating the dads dropdown.
On dad selection, populate the sons dropdown depending on the dad.

I notice that in your code there's duplicates. Let's split them up into functions to be reusable. Based on the operations, you should have something like:

function populateDads(dads){...}
function populateSons(sons){...}

Let's start first with the dads. I would discourage using .html(). While it does work, what happens is that jQuery does not clean up after itself. Handlers that are assigned to elements that are replaced will linger on your page. Suggesting you use .empty() if your current set is the parent of the elements to remove or .remove() if your current set are the elements to remove.

$('select').empty(); // Empties the options

As far as I know, jQuery's .val() should be able to extract the value from a <select>. No need to find the selected <option> from the <select>.

var selDad = $('#dadDrop').val();

If both your select boxes are static throughout the life of the page, you can simply just store their jQuery object in a variable. That way, you won't be querying the DOM every now and then.

var dadSelect = $('#dadDrop');
var sonSelect = $('#sonDrop');

There's also a neater way to construct elements in jQuery. It goes like:

$('<tagName />', { attr: value });

Running with all these, the code should look like:

var dads = [
  {id: 1, name: 'Dad1'},
  {id: 2, name: 'Dad2'},
  {id: 3, name: 'Dad3'},
];

var sons = [
  {id: 1, dadId: 1, name: 'Son1'},
  {id: 2, dadId: 1, name: 'Son2'},
  {id: 3, dadId: 3, name: 'Son3'},
  {id: 4, dadId: 2, name: 'Son4'},
];

var dadSelect = $('#dadDrop');
var sonSelect = $('#sonDrop');

function populateDads(dads){
  dadSelect.empty();
  $.each(dads, function(index, dad){
    $('<option />', {value: dad.id}).text(dad.name).appendTo(dadSelect);
  });
}

function populateSons(sons){
  sonSelect.empty();
  $.each(sons, function(index, son){
    $('<option />', {value: son.id}).text(son.name).appendTo(sonSelect);
  });
}

dadSelect.on('change', function(){
  // .val() returns a string. Coerce the value to a number using the
  // prefix "+". Acts like parseFloat most of the time.
  var selectedDad = +dadSelect.val();
  var dadSons = sons.filter(function(son){ return son.dadId === selectedDad; });
  populateSons(dadSons);
});

populateDads(dads);

// Trigger change for first load to prepopulate children
dadSelect.trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="dadDrop"></select>
<select id="sonDrop"></select>


Locate a number in an array with ascending even and descending odd entries

Let's call the array x:

x = 2 4 6 8 1 9 7 5 3

I'm assuming you don't have the array stored in a variable (in which case this question boils down do: find(x==z)), and that you don't need the array either (in which case this question is really: "How do I create x?").

First off:

Don't use length as a variable name. length is a builtin function, and overloading it is a bad idea. Although it's better to use the builtin numel instead of length, overloading length is not a good idea. It might cause all sorts of strange bugs. Choose another variable name (I'll use len, you might use something else).

x has a fairly straight forward setup, and can be created quite simply using concatenation and the colon operator.

x = [2:2:len, 1, fliplr(3:2:len)]

If you can guarantee that len is odd then it's simply:

x = [2:2:len, 1, len:-2:3]

Now, you have x, and you know z. The only thing remaining is a simple call to find:

col = find(x==z);


Can only one loop be used to calculate percentage?

No, totatVal won't be a totalVal until you loop through all the rows to find it.
It might be solved by a single loop with some fancy standard functions but at the end it will come down to 2 loops.

It's pure math - you need to count your total value first in order to find a correct % of each of your values.


Improving a shortcode replacement routine PHP and regex

Why are you having them write that all in one box? And with custom tags no less!

I'd just create a form with each of these fields in it (section, year, event), with a JS "add" button below the event to add additional events to the DOM. Then if you want to give them the option of adding multiple sections at a time, then you can add another "add" button below the section that will duplicate an unmodified version of the original form so that they can do it all over again.

This is much better than having your client learn your custom tags for your program. And if you were to continue this route you'd end up recreating BB code, which there are plenty enough out there that you'd be better off downloading one instead. Not to mention that the above method is also easier on you. No need to create a custom parser at that point, just extract the proper keys from the POST data. I'm not going to put the code here, simply because a simple google search will find what you're looking for easier and faster than I could write it all here.

As for improvement to your code, I'd steer clear of Regex, but that's just me. I wasn't born on whatever planet that language came from.


Next lexicographic permutation of a list

I'm a beginner at Haskell as well, so take my opinion with a big rock of salt.

nextPerm :: (Ord a, Num a) => [a] -> [a]
nextPerm [] = []
nextPerm a

I wouldn't use a as a type variable and a variable at the same time.
I like to name lists xs, ys, cs, etc. I feel this is more descriptive, and it works well with pattern-matching, e.g. (x:xs), where x is the head of the list, xs is the tail.

swap = foldl (\acc x -> if x <= (last acc) then acc ++ [x] else [x]) [(-1)] a

Here you are going through the list from the front. When you use last, the program has to go through the whole list, because lists are kind of like linked lists, think [1,2,3] = 1 : 2 : 3 : [], so accessing an element takes \$O(n) \$ time.
For the same reason, (++) is expensive, while (:) is cheap. Try running swap on a list of \$ 10^5 \$ size; it's slow.

Other than the speed factor, I think your implementation is OK!

If you want to make it faster, first of all you should change swap. For example, first reverse the list, then work on it - as lists are made to be accessed from the front, not the back. Let me show you an improved version of swap along with a few other changes.

nextPerm :: Ord a => [a] -> [a]
nextPerm xs
  | null xs || pivotIndex == -1 = xs
  | otherwise = prePivot ++ swapVal : swapWithPivot
  where pivotIndex = length xs - length swap - 1
        prePivot = take pivotIndex xs
        pivotVal = xs !! pivotIndex
        swapVal = foldl1 (\acc x -> if x > pivotVal then x else acc) swap
        swapWithPivot = insert pivotVal . delete swapVal . reverse $ swap
        swap = reverse . fmap fst
                       . takeWhile (uncurry (>=))
                       . (<*>) zip (\ls -> head ls:ls)
                       . reverse $ xs

As you can see, this way, you don't even need to restrict yourself to the class Num.
To make it even better, figure out how to use span instead of take, and takeWhile. If you do that, you won't even need indexing anymore.   Use Hoogle, play around in ghci, look at types using :t <typename> e.g. :t span - type signatures (and names) will usually tell you what a function does.

Lists are weak at random access, but kind of good at being sliced up; therefore I'd definitely drop the whole indexing thing.

Anyway, I will include how I'd write it, hopefully it'll give you some new ideas.

nextPerm' :: Ord a => [a] -> [a]
nextPerm' = uncurry (++) . uncurry swap
                         . (fmap fst *** fmap fst)
                         . span (uncurry (>=))
                         . (<*>) zip (\ls -> head ls:ls)
                         . reverse
    where swap rpost [] = ([], rpost)
          swap rpost (pivot:rpre) = (reverse rpre, ins . span (<= pivot) $ rpost)
              where ins (le,[])   = le ++ [pivot]
                    ins (le,a:as) = a:le ++ pivot:as

If you want to test an implementation, issue

(sort . permutations $ [1,2,3,4,5]) == (take 120 $ iterate nextPerm [1,2,3,4,5])

If it works, the result will be True.


You should not hard-code category values into the code, but rather make them configurable, so that your code may be re-used with other top/bottom category values. Since you have a specific sorting algorithm, it is probably best to create a custom comparator, which encapsulates all of the sorting logic. That comparator would be initialized with the values allowed for top/bottom categories, and would do the sorting, taking these values into account.

Using the comparator should be as simple as:

    List<String> allCategories = Arrays.asList(
            "A", "B", "C", "D", "E", "F",
            "G", "H", "I", "J", "K", "L",
            "M", "N", "O", "P", "Q", "R"
            );
    List<String> topCategories = Arrays.asList("C", "F");
    List<String> bottomCategories = Arrays.asList("M", "P", "R");
    Collections.sort(allCategories, new CategoryComparator(topCategories, bottomCategories));

There are many ways to implement such a comparator.The main idea is to extend the comparison logic: in addition to comparing values, you also compare their belonging to a particular category, and adjust the score consequently. As a result, values belonging to the top category should be put on top, and if two values belong to the same category, they should be compared according to their natural order.

public class CategoryComparator implements Comparator<String> {

    private static final int POSITIVE_SCORE = +1;
    private static final int NEGATIVE_SCORE = -1;
    private static final int TOP_SCORE_ADJUSTMENT = -2;
    private static final int BOTTOM_SCORE_ADJUSTMENT = +2;

    private Set<String> topCategories;
    private Set<String> bottomCategories;

    public CategoryComparator(Collection<String> topCategories, Collection<String> bottomCategories) {
        this.topCategories = new HashSet<>(topCategories);
        this.bottomCategories = new HashSet<>(bottomCategories);
    }

    @Override
    public int compare(String o1, String o2) {
        return normalizeScore(o1.compareTo(o2)) + ajustScoreForCategory(o1) - ajustScoreForCategory(o2);
    }

    private int normalizeScore(int score) {
        if (score < 0) {
            return NEGATIVE_SCORE;
        }
        if (score > 0) {
            return POSITIVE_SCORE;
        }
        return 0;
    }

    private int ajustScoreForCategory(String value) {
        int scoreAdjustment = 0;
        if (topCategories.contains(value)) {
            scoreAdjustment += TOP_SCORE_ADJUSTMENT;
        }
        if (bottomCategories.contains(value)) {
            scoreAdjustment += BOTTOM_SCORE_ADJUSTMENT;
        }
        return scoreAdjustment;
    }
}


Modify array of arrays to create custom array of objects

Overview

You're overwriting the name array in defining the mapping param.
You don't need to assign to a new object. This is done for you.

Rewrite

function modifyArray(arrays) {
    return arrays.map(array => {
        return { coordinates: array.slice(0, 2), reach: array[2], power: 0 };
    });
}


Unfortunately, as far as I know, there is no chunks methods in the standard library.
But this makes things rather neat.

from itertools import chain, islice

def chunks(iterable, n):
   "chunks(ABCDE,2) => AB CD E"
   iterable = iter(iterable)
   while True:
       yield chain([next(iterable)], islice(iterable, n-1))

l = ...
file_large = 'large_file.txt'
with open(file_large) as bigfile:
    for i, lines in enumerate(chunks(bigfile, l)):
        file_split = '{}.{}'.format(file_large, i)
        with open(file_split, 'w') as f:
            f.writelines(lines)


Look for common functionality

The real power of inheritance comes from the existence of common functionality.  In this case, the dealing of cards and the calculation of totals will be common to both players and dealers, and so having both of these in the parent class would be a good choice.

Look for differing functionality

A dealer will have rules on when they hit and when they stay.  A player will likely have an amount bet and a chip balance.  These would be candidates for inclusion in the child classes.


So far, your code has some general problems that are much more urgent than performance:

You are using namespace std;.  This is an extremely bad habit and will ruin your life ("this is a contest and I write everything in main" is not an acceptable excuse).  See Why is using namespace std; considered bad practice?.
The main function is very long and a reader cannot tell at a glance what it does.  If you need so many comments, you should consider refactoring your code.  (Also, why do your comments end with //?)
You are not making enough use of the standard library.
There is too little space.  And the indentation is inconsistent.
The variable names are not helpful.  What is sum1?  s3?
j++ is being used instead of the correct ++j.  See Difference between pre-increment and post-increment in a loop?.

Also, please avoid std::endl when not necessary.  Use '\n' instead.  See C++: std::endl vs \n.

And str.erase() is much less intuitive than str.clear().  (In fact, I didn't know until today that erase can be invoked this way.)

Here's I would write the same code, at the very least: (30 seconds code, not tested comprehensively)

#include <iostream>
#include <numeric>
#include <string>

int hash_code(const std::string& pattern)
{
    // note: c - 'a' + 1 is not portable
    return std::accumulate(pattern.begin(), pattern.end(), 0,
                           [](int x, char c){ return x + (c - 'a' + 1); });
}

void search(const std::string& string, const std::string& pattern)
{
    const int pattern_hash = hash_code(pattern);
    for (std::size_t i = 0; i + pattern.size() <= string.size(); ++i) {
        auto str = string.substr(i, pattern.size());
        if (hash_code(str) == pattern_hash)
            std::cout << str << " " << i << "\n";
    }
}

int main()
{
    int n;
    std::cin >> n;

    for (int i = 0; i < n; ++i) {
        std::string string, pattern;
        std::cin >> string >> pattern;
        search(string, pattern);
    }
}

(Also, the input style is quite strange, I have to admit, but that seems to be beyond your control.)

Incidentally, I don't think you properly implemented the sentence "If no match is found, print -1."


Your answer makes an implicit assumption:

  Racket's built-in shuffle assigns each list element with a random number as a sort key, then sorts the list, which provides an O(n log n) runtime. However, I'd like something that's O(n), and that's where Fisher-Yates comes in.

That assumption is that O(n) will necessarily be faster than O(n log n). I don't think that's true for this particular case.

Considering you referenced Racket's shuffle by name, I figured I'd do some simple profiling using that function compared to your implementation. Just for completeness, I decided to benchmark both of your shuffle implementations. I've renamed the version that uses for/fold to fisher-yates-shuffle*.

All of these procedures operate on lists, and since they're not doing any sorting or anything like that, I just decided to test them on lists generated using Racket's range function. My test harness ended up looking like this:

(define lst (range 10000))

(define (shuffle-lst shuffle-proc)
  (for ([i (in-range 10000)])
    (shuffle-proc lst)))

Using Racket's for, the result is discarded, so the only thing being profiled is the algorithm itself. I then used the following code to actually time the three procedures:

(time (shuffle-lst shuffle))
(time (shuffle-lst fisher-yates-shuffle))
(time (shuffle-lst fisher-yates-shuffle*))

I adjusted the length of the list being shuffled as well as the number of times it was shuffled in a few different ways to figure out how the algorithms interacted with different sizes of lists.

I did some initial, relatively simple benchmarking, and it seemed to indicate that your algorithm was basically never faster than simply shuffling a list. This seemed unlikely to me for a variety of reasons, so I decided to optimize everything to give your algorithm as wide a benefit as I could possibly give it.

I compiled the file using Racket's bytecode compiler and ran it with all optimizations enabled. Here were my results:

==============================================================================
|           list length |       100 |   1,000 | 10,000 | 100,000 | 1,000,000 |
|-----------------------|-----------|---------|--------|---------|-----------|
|       loop iterations | 1,000,000 | 100,000 | 10,000 |   1,000 |       100 |
|=======================|===========|=========|========|=========|===========|
|               shuffle |    11,585 |  11,929 | 12,020 |  12,394 |    16,119 |
|-----------------------|-----------|---------|--------|---------|-----------|
|  fisher-yates-shuffle |     9,676 |   9,816 |  9,888 |  10,730 |    13,285 |
|-----------------------|-----------|---------|--------|---------|-----------|
| fisher-yates-shuffle* |    10,738 |  11,112 | 11,162 |  11,895 |    14,978 |
==============================================================================

There we go. Now fisher-yates-shuffle seems to be coming out on top. That seems sort of odd, though... why did it all suddenly reverse, and why is the manual loop version so much faster than the one using for loops?

Actually, I realized there was another factor in play—the random number generator. This is a rather odd factor to even matter at all. Why would Racket's random be different from its own implementation of random-integer from SRFI 27? The answer is: I don't know.

Either way, normalizing all the implementations to use random instead of random-integer, and I got some slightly different times.

==============================================================================
|           list length |       100 |   1,000 | 10,000 | 100,000 | 1,000,000 |
|-----------------------|-----------|---------|--------|---------|-----------|
|       loop iterations | 1,000,000 | 100,000 | 10,000 |   1,000 |       100 |
|=======================|===========|=========|========|=========|===========|
|               shuffle |    12,191 |  12,178 | 11,497 |  12,733 |    16,763 |
|-----------------------|-----------|---------|--------|---------|-----------|
|  fisher-yates-shuffle |    11,313 |  11,601 | 10,831 |  12,559 |    16,002 |
|-----------------------|-----------|---------|--------|---------|-----------|
| fisher-yates-shuffle* |    11,441 |  11,269 | 10,814 |  12,716 |    15,766 |
==============================================================================

Obviously, none of this is conclusive evidence one way or the other. That said, I think some valid conclusions can be drawn.

The difference between your implementation of the Fisher-Yates shuffle and the default shuffle built-in to Racket is pretty trivial. I find it unlikely that any use-case would have shuffling as a bottleneck, of all things.
The performance differences likely vary wildly across implementations. Scheme is really just a standard, and micro-optimizing for "Scheme" doesn't really make sense unless you have a specific implementation you can micro-optimize for.
Any benchmarks are just as likely to be representative of your sorting algorithm as they are of your random number generator. Pseudorandom number generation is not free, and the higher quality generator you use, the more time it will take.

My advice? Don't worry about it. The built-in shuffle is fine, and it's standard. Use it.

Oh, your code? It's fine, I guess.


Looking through a directory tree for certain folders

It looks like your script's output will look more like this:

FOLDER 1
    NOT INVOICED FOLDER 1
    NOT INVOICED FOLDER 2
FOLDER 1
    NOT INVOICED FOLDER 1
    NOT INVOICED FOLDER 2
FOLDER 3
    NOT INVOICED FOLDER 1

It happens because for each subdirectory which contains NOT INVOICED you'll print containing directory name and all subdirectories. It can be easily fixed by adding an extra break in the end of the first if.

Now to the question. First of all, PEP 8 recommends using 4 spaces per one ident, neither tabs, nor 8 spaces. Also, you are free to omit the else branch in your ifs - no need in pass and extra lines.

I would separate checking of whether the directory should be printed (with some subdirectories) and the actual printing - that would kill inner for loop. Moreover, it will also make it impossible to output a directory twice:

import os
import re

rootDir = '.'

with open('names.txt', 'w') as f:
    for dirName, subdirList,fileList in os.walk(rootDir):
        shouldPrint = False
        for fname in subdirList:
            if re.match("NOT INVOICED", fname):
                shouldPrint = True
        if shouldPrint:
            f.write(dirName + '\n')
            for i in subdirList:
                if re.match("NOT INVOICED", i):
                    f.write('\t%s\n' % i)

Next things that I'd do are:

Calculate not invoiced subdirectories just once with list-comprehension. That will remove redundant for+if pair and also lower the risk of misspelling one of regexes.
Replace fileList variable with wildcard as it's unused
Run pep8 tool (can be installed with pip install pep8) on the code to make sure it corresponds with PEP 8. It'll report some whitespace issues in the very first for loop.
Make sure that only only style of quotes is used across the code - ' or ".

And now we have:

import os
import re

rootDir = '.'

with open('names.txt', 'w') as f:
    for dirName, subdirList, _ in os.walk(rootDir):
        notInvoiced = [fname for fname
                       in subdirList
                       if re.match('NOT INVOICED', fname)]
        if notInvoiced:
            f.write(dirName + '\n')
            for i in notInvoiced:
                f.write('\t%s\n' % i)

Also, if you're Python 3 user, I'd recommend using str.format() instead of % operator - the latter is kind of deprecated.


Checking and converting [[HH:]MM:]SS input format

Here are my suggestions:

The printExit() prints an error message, but does not exit.  It would be better to actually exit or rename the function.
Your regex in isnumeric() has two minor issues.  Putting a ^ at the beginning will make it clear that the regex matches the whole string.  While this is implicit with expr it does not fit with how most implementations work.  Another issue is that the * quantifier means 0 or more so it might match 0 or none of the what you're looking for.  So an empty string would match what you have since it would be zero digits followed by the end of the string.  I couldn't reproduce this failure mode, but I'd recommend this line instead which works for my tests:

if ! expr "$1" : '^[[:digit:]]\+$' > /dev/null; then

It would be nice to explain what you're trying to do with those string manipulations with a few comments
More of your variables could be localized so they don't leak out of the function they are used in.
Using the in variable names to avoid conflicting with generic names works, but if you can find more descriptive names it would be easier to follow.  Along the same lines all variables are temporary so that doesn't help explain why the variable exists.  Maybe checkTime or even check_time.
All of the math is integer math.  You won't get any decimals with bash or expr math.  https://stackoverflow.com/questions/12722095/how-can-i-get-float-division explains that you can work around with bc.
Optimization Using expr is fine, but it calls an external program.  Using bash's builtin math would avoid spawning a new process and would cut out a lot of the script's time.
    ((just_minutes = just_minutes + trunc_seconds/60))


You are using prepared statements which is good, but why does your query return all columns ? A simple SELECT USERID FROM TABL0001 WHERE USERID = ? would be enough and if multiple users access this code, the database load would be low which is good.

The checkUserID() method is returning an int which only will be either 0 or 1 and this is screaming for a boolean which also would simplify the method. Also the name of the method is a little bit  misleading. A better name would be existUserID

Like

public boolean existUserID (String userID) throws SQLException {

    String sql = "SELECT * FROM TABL0001 WHERE USERID = ?";

    PreparedStatement pstmt = conn.prepareStatement(sql);
    pstmt.setString(1,  userID);
    resultSet = pstmt.executeQuery();

    return resultSet.next();
}

You aren't closing the database connection. Also, because you are  always creating a new CustomerInfo you really should make the former checkUserID() method static and create the connection there.

If you are using Java 7 or above you should use try with ressources to ensure that for any exception that the ressources are closed.

If you are using Java prior version 7 you should use a finally block where you the close the ressources.

The name readInput does not really say much. You should always use meaningfull names for classes, methdos and parameters. Also readInput would let me think I would get something back, but no, the method is void.

boolean UserIDExists = false;

should be named using camelCase casing.

Instead of while(!userIDExists) you should just make while(true) and if the userid does not exists just break; out of the loop.

while (true) {

    this.userID = input.readLine();

    while (this.userID.length() != 10) {

        System.out
                .println("Input must be 10 digits. Type again: :");
        this.userID = input.readLine();

    }

    // assuming existUserId() is static
    if (CustomerInfo.existUserId(this.userId)) {
        break;
    }
    System.out.println("UserID exists already. Type again:");
}

by extracting the reading from the input stream to a separate method this can be simplified some more and will reduce the responsebilities of the method.

private String readUserInput(String message) {

    System.out.println(message);

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    return input.readLine();
}

leading to

String message = "UserID (10-digits):";
while (true) {

    this.userID = readUserInput(message);

    while (this.userID.length() != 10) {

        this.userID = readUserInput("Input must be 10 digits. Type again: ");

    }

    // assuming existUserId() is static
    if (!CustomerInfo.existUserId(this.userId)) {
        break;
    }
    message = "UserID exists already. Type again:";
}

Based on the comment I changed the above implementation to break if the userId does not exists. But hey, the variable you formerly used UserIDExists is very very very !! misleading. One would assume (like I did) if a userId exists then the boolean variable UserIDExists would become true !


for num in nums[1:] is the prefered way to iterate over a partition of an array; if you are worried about performance, it actually is faster, because accessing by index is more expensive in python than copying then iterating values (you can play with snippets of timeit to verify that claim, but I'm fairly sure of that - accessing by index in python involves way more checks and operations than it does in a language like C).

The performance issue with your program, if there is one, isn't there. The copy is just done once in the outter loop, and since it is repeated by num your inner loop is way more costy. Mind this: since every iteration can in the worst case double the number of items in keys, your program is actually of complexity O(2^n) where n is the array length.

In a matter of using more efficient structures you can also use Counter from collections that saves a bit of verbosity (it has zero as default value) and computation time (it is optimized C structure).

Without optimizing the algorithm, which I believe is part of the challenge :

from collections import Counter

class Solution:

    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        counts = Counter()
        counts[-nums[0]] += 1
        counts[nums[0]] += 1
        for num in nums[1:]:
            new = Counter()
            for key in counts.keys():
                new[key + num] += counts[key]
                new[key - num] += counts[key]
            counts = new
        return counts[S]


Replace template based on placeholder values

The best way to improve the performance of this code is probably by using the preg_replace_callback()-function. This function allows you to search for a regex in a string, and call a function for every match. This function then returns the replacement. This avoids running multiple str_replace() operations over the string, which can be costly for large strings.

Secondly, we can use a capture group in the regex to avoid the use of explode(). I.e. by changing the regex from /{ITEM-.*?}/ to /{ITEM-(.*?)}/ we can ensure that we get the matched item identifier directly.

Applying those two modifications, we would end up with something like:

$content = 'Here is the item list {ITEM-100}  {ITEM-110}  {ITEM-200}';
function get_replacement($matches) {
    $value = $matches[1]; // Index 1 is the first capture group, which contains our item number.
    return get_item_card($value);
}
$content = preg_replace_callback('/{ITEM-(.*?)}/', 'get_replacement', $content);
echo $content;


Your first example (switch-case) is so poorly thought of in the Object Oriented community that there is a refactoring designed specifically to replace it with your third implementation: Replace Conditional With Polymorphism.

To be honest, I would have never thought of your second implementation. It isn't completely heinous, though I would probably use the constructor to create an array of method objects that you can index into directly - rather than run through a for loop every time you want to make a call.

Between a revised second implementation (array with annotation/reflection) and the third implementation (inner classes) I would personally be more fond of the "inner class" version. I don't think that memory or performance is going to be a factor at this level and I think the third, inner class, version is much more readable (at least in Java - in other languages, you could implement something like the second approach directly).


Is this a safe/correct way to make a python LogHandler asynchronous?

It would seem to me that writing a class would be better:

class AsyncHandler(threading.Thread):
    def __init__(self, handler):
         self._handler = handler
         self._queue = Queue.Queue()

         self.daemon = True
         self.start()

    def run(self):
        while True:
           record = self._queue.get(True)
           self._handler.emit(record)

    def emit(self, record):
        self._queue.put(record)

Patching objects can be useful, but its usually clearer to create another object like this.


Ruby install script; packages+installs as a .deb or .rpm from source

First,I would like to point out that not all .deb-based distributions are as fond of sudo as Ubuntu is. For example, Debian doesn't use sudo out of the box.

It appears that you're trying to build a newer version of Ruby than is available in the stock package repository. In that case, why not make a proper .deb package with its .dsc and publish it in a private APT repository?  Then, everything integrates properly into the distribution the way package management is supposed to work, including the build process and subsequent updates.  Everyone will have a better experience when you work with the system instead of against it.


For reference, in case anyone stumbles across this page later, and as discussed in your thread here.

Something like this would do the trick:

parseFW=: (i.@{:@$@] e. 0,+/\@[) <;.1"1 ]

(Though when I test against your input, I'm tripped up by a leading space on each line of your 'input' value, which does not match the specific width values you have used here. Need to also deal with that issue somehow. I would recommend either manually removing those spaces, or dropping the first character on each row before handing off to either implementation of parseFW).

That said, to get an exact workalike to your parseFW (throws an error because the record size is wrong, rather than slicing at the "wrong" column positions on the larger records), you could do this:

parseFW=: (i.@(+/) e. 0,+/\)@[ <;.1"1 ]


Simple anagram game with names of colors

In your __init__() function, you have defined words as a parameter but you are assigning None to _words

class AnagramGame:

def __init__(self, words=None, rword=None, inp=None,
             anagram=None, is_corr_word=False):
    self._words = None
    # ...

You may either remove this parameter or assign the value to _words

Instead of using an infinite loop while True:, you should have created a bool object. Something like this:

checker = False
while not checker:
    # ...

I see the purpose of while True: is to make the user play the game endlessly. It would have been great to have an exit criteria too. Else, you could have skipped the infinite loop.

You don't have to re-initialize the object and reload the file on each loop run. You may initialize them before the loop, load the files and let the game run on its own.

To reset the values, you may create another function that would only reset the relevant data-members and continue the game further.

As you have already mentioned, please have proper comments and doc-strings in the code. It is always better to add them during development. Else mostly they get ignored!


Other than maybe adding some comments for documentation, this seems pretty sane. This:

    System.out.println(String.format("OrderProcessingActor %d %s order received for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()));
    //process order here.
    getSender().tell(String.format("OrderProcessingActor %d %s order processed for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()), getSelf());

is a classic don't-repeat-yourself situation. Make a toString() method on Order:

String toString() {
   return String.format("OrderProcessingActor %d %s order for instrument %s with price %f", orderId, orderType, instrument, price);
}

Then, the prior code can be

    System.out.println(String.format("%s has been received", order));
    //process order here.
    getSender().tell(String.format("%s has been processed", order));


Sum of Subset of an Array equals a given number

Let's start with a subtle bug in your code:

unsigned long two_pow_n = 1 << n;

According to the problem description, n is at most 20, so using
unsigned long is good, an int is only guaranteed to have
16 bits according to the C standard. But 1 is an int and if n
exceeds the number of bits in an int then the behaviour of 1 << n
is undefined. So

Either you know that int has (at least) 32 bit on your platform. Then
you don't need to use long at all.
Or you don't want to make that assumption: Then it must be

unsigned long two_pow_n = 1UL << n;

using an unsigned long int literal.

Now some remarks to your current implementation. First, I would
put the computation into its own function and separate it
from the I/O:

bool hasSubsetSum(unsigned numbers[], unsigned n, unsigned targetSum) {
    // ... return true or false
}

That makes the program structure more organized, and allows to add
test cases easily. I have used bool from <stdbool.h>. If that
is not available with your compiler, replace it by int.

Next, your code to update the teller array looks a bit obfuscated
to me. Actually you don't need that array at all: You already
test all bit positions of j in

if (j % (1 << k) == 0) { ...

so you can use the same test to update either sum1 or sum0.

You compute both a sum and a complementary sum at once, which is a
good idea to cut the (maximal) number of iterations into half. But the loop

for (j = 0; j < two_pow_n; ++j)

does not reflect that, you only need to iterate over 2^(n-1) combinations.

Finally, a variable should be declared at the narrowest possible scope.
In particular, loop variables should be declared in the loop statement:

for (unsigned int j = 0; j < two_pow_n; ++j)

Putting it all together, you code could look like this:

bool hasSubsetSum(unsigned numbers[], unsigned n, unsigned targetSum) {

    unsigned long two_pow_n1 = 1UL << (n - 1);

    for (unsigned long j = 0; j < two_pow_n1; ++j) {
        unsigned sum0 = 0, sum1 = 0;
        for (unsigned k = 0; k < n; ++k) {
            if ((j & (1UL << k)) == 0) {
                sum0 += numbers[k];
                if (sum0 == targetSum) {
                    return true;
                }
            } else {
                sum1 += numbers[k];
                if (sum1 == targetSum) {
                    return true;
                }
            }
        }
    }

    return false;
}

Alternatively you could compute the totalSum of all numbers in advance
and then compare both sum1 and totalSum - sum1 with the target sum.

This should be a bit faster than your original approach, but
it is still the "brute-force" algorithm to solve the
"subset sum problem"
and has complexity O(2^n).

For positive integers (as in your case) there is a better algorithm
using "dynamic programming".
The rough idea is to incrementally compute a list of all sums which
are achievable with the given numbers, and then check if the target
sum is in that list.

One possible implementation is to use a boolean array hasSum with indices from
0 up to targetSum. Initially, only hasSum[0] is true.
Then for each number x in the given array and all
possible indices j in hasSum,
hasSum[j + x] is set to true if hasSum[j] == true.

Here is a sample implementation of that algorithm:

bool hasSubsetSum(unsigned numbers[], unsigned n, unsigned targetSum) {

    bool hasSum[targetSum + 1];
    for (unsigned i = 0; i <= targetSum; ++i) {
        hasSum[i] = false;
    }
    hasSum[0] = true;

    unsigned maxIndex = 0; // Highest index in `hasSum` which is `true`

    // For all numbers in the given array ...
    for (unsigned k = 0; k <= n; ++k) {

        // For all `j` for which `hasSum[j] == true` ...
        for (unsigned j = maxIndex; j != (unsigned)(-1); --j) {
            if (hasSum[j]) {

                unsigned sum = j + numbers[k]; // New achievable sum
                if (sum == targetSum) {
                    return true;
                } else if (sum < targetSum) {
                    hasSum[sum] = true;
                    if (sum > maxIndex) {
                        maxIndex = sum;
                    }
                }
            }
        }

    }
    return false;
}

The inner loop is traversed in decreasing order, so that updating the boolean array
does not influence the computation for the current number[k].


Imitate UITableView reordering interaction

Technically this is not true recursion - dispatch_after(...) adds the block to whatever queue you assign it, so there's no chance of a stack overflow (although I'm not sure what will happen if you add too many blocks to the queue...)  The block is handled by GCD so there's no chance of a retain cycle either.  Plus, the block creation is inexpensive so it's not too inefficient (although the screen refreshes every 1/60 or ~0.017 seconds, so there is an inefficiency in having your timer interval at 0.0005s, about 33x faster than the refresh rate).  Overall, however, this method is very hacky and there is a more conventional way to do this, using a CADisplayLink.
Two pointers for you:

Refactor the code that actually does the scrolling into a new method, instead of having it all in one place.
Use a CADisplayLink to call that method, thus managing the scrolling behavior.

Can provide code example if necessary.
Food For Thought
Unless you are challenging yourself, optimizing existing technology, or doing some research, it's good practice in general to skip reinventing the wheel.  Why are you using a scroll view when you can get the functionality you desire, plus cell recycling and memory management for free with a UITableView?
In the context of your original question, I say it is far safer and more efficient to use technology that's already been proven to work.  For example, here's one I use a lot, that supports long-pressing to reorder :  https://github.com/hpique/HPReorderTableView


Making adjustments based on biblatex style

It seems I needed Aristotle to save my project -- with the help of Saving Aristotle: How can Biblatex redefinitions be made conditional on the style selected? the code can me massively simplified to the following example:
\documentclass{beamer}

\usepackage[
%   style=numeric,
%   style=numeric-comp,
%   style=numeric-verb,
%   style=authoryear,
%   style=authoryear-comp,
%   style=authoryear-ibid,
   style=authoryear-icomp,
]{biblatex}

\addbibresource{biblatex-examples.bib}% included in full tex distributions or from http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/examples/biblatex-examples.bib

\makeatletter
\newcommand{\fixnumericstyles}{%
    \setbeamertemplate{bibliography item}{\insertbiblabel}
}

\newcommand{\fixauthoryearstyles}{%
    \newlength{\beamer@bibiconwidth}
    \settowidth\beamer@bibiconwidth{\usebeamertemplate*{bibliography item}}
    \setlength{\labelwidth}{-\beamer@bibiconwidth}
    \addtolength{\labelwidth}{2\labelsep}
    \addtolength{\bibhang}{\labelsep}
}

% from https://tex.stackexchange.com/a/365563/36296
\def\beamer@blx@splitfile#1-#2\@null{#1}
\edef\beamer@blxbase{\expandafter\beamer@blx@splitfile\blx@cbxfile-x\@null}
%
% numeric styles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\edef\beamer@namenumeric{numeric}
\ifx\beamer@blxbase\beamer@namenumeric
    \fixnumericstyles
\fi
%
% author year styles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\edef\beamer@nameauthoryear{authoryear}
\ifx\beamer@blxbase\beamer@nameauthoryear
    \fixauthoryearstyles
\fi

\makeatother
\begin{document}

\begin{frame}
\cite{sigfridsson}
\printbibliography
\end{frame}

\end{document}

Update 2020
In the mean time, the biblatex developers were so nice to add some hooks which can be used for this purpose, see https://github.com/plk/biblatex/pull/973 for more details. This simplifies the solution dramatically and makes it much more versatile.
The following code was added to beamer to make the necessary adjustments:
% Adding patches to some biblatex styles
\csappto{blx@filehook@postload@numeric.bbx}{%
  \mode<presentation>{\setbeamertemplate{bibliography item}{\insertbiblabel}}}
\csappto{blx@filehook@postload@alphabetic.bbx}{%
  \mode<presentation>{\setbeamertemplate{bibliography item}{\insertbiblabel}}}
\csappto{blx@filehook@postload@authoryear.bbx}{%
  \mode<presentation>{%
      \newlength{\beamer@bibiconwidth}
      \settowidth\beamer@bibiconwidth{\usebeamertemplate*{bibliography item}}
      \setlength{\labelwidth}{-\beamer@bibiconwidth}
      \addtolength{\labelwidth}{2\labelsep}
      \addtolength{\bibhang}{\labelsep}
  }}
\csappto{blx@filehook@postload@authortitle.bbx}{%
  \mode<presentation>{%
      \newlength{\beamer@bibiconwidth}
      \settowidth\beamer@bibiconwidth{\usebeamertemplate*{bibliography item}}
      \setlength{\labelwidth}{-\beamer@bibiconwidth}
      \addtolength{\labelwidth}{2\labelsep}
      \addtolength{\bibhang}{\labelsep}
  }}


Complexity for two approaches of finding next biggest palindrome of a number

I did some digging on this and i think the 2nd one is more efficient. I can not determine the complexity though but i know why the first one will take more time than the 2nd one.

In the first i approach, i did some arithmatic addition on the given input directly like here a = str(int(a) + 1) or here firsthalf = str(int(firsthalf) + 1) rather than just doing arithmatic on a single number like in the 2nd approach center = str(int(center)+1). So apparently a being a huge number and doing arithmatic on it will take a considerable amount of time.

This is the easiest explanation i can come up with. If anyone can do a more elaborate explanation with the given complexity for both the algorithms please feel free to do so.


Printing 80 (or more) times the same character

String constants in Java are very efficient. In practice, your code is very high-performing. The issue here is not about how fast the code runs, because, essentially, it cannot be run any faster than this.

If you want to have more efficient code in terms of space, then the practical thing to do is to declare the value as a string constant, something like:

private static final String DASHES =
              "----------------------------------------"
            + "----------------------------------------"
            + "----------------------------------------";

And then, in your code, you just:

System.out.println(DASHES);

This will be just as fast, but the code is easier to read.

If the one place where you declare the dashes is still unsightly, then you can compute the value using the other mechanisms shown in other answers... e.g. :

public static final String DASHES = new String(new char[80]).replace("\0", "-");

but that is overkill, and unnecessary.

Edit:

In your comments you raised the issue of having multiple different-length values. I would recommend that you create a constant for the longest one (whether you use the String-constant or some other generator method), and then do a DASHES.substring(0, length) on that to get the shorter constants...

alternatively, I would consider a helper function as useful for this problem....

private static final String repeatChar(char c, int length) {
    char[] data = new char[length];
    Arrays.fill(data, c);
    return new String(data);
}

and then your constants can be initialized with:

private static final String DASH80 = repeatChar('-', 80);
private static final String SPACE40 = repeatChar(' ', 40);

etc.


Data import "upsert" from a SSIS package

I can pretty much guarantee it's the concatenation that's the problem.  Use the columns as columns; you don't want to handcuff the optimizer when it puts together your query plan.  Here's a pretty typical "upsert" pattern:

  UPDATE [dbo].[vwMP_VOD]
  SET [Org] = inserted.Org
  ,[id_vend] = inserted.id_vend
  ,[id_org_orig] = inserted.id_org_orig
  ,[id_vchr_nbr] = inserted.id_vchr_nbr
  ,[id_vchr_line] = inserted.id_vchr_line
  ,[id_vchr_line_dist] = inserted.id_vchr_line_dist
  ,[id_glac_exp] = inserted.id_glac_exp
  ,[text_ref_4] = inserted.text_ref_4
  ,[amt_exp_hcur] = inserted.amt_exp_hcur
  ,[amt_rem_hcur] = inserted.amt_rem_hcur
  ,[id_tax] = inserted.id_tax
  ,[code_type_chrg] = inserted.code_type_chrg
  ,[id_vchr_line_chrg] = inserted.id_vchr_line_chrg
  FROM inserted
      INNER JOIN (
         SELECT ORG, ID_VEND, ID_ORG_ORIG, ID_VCHR_NBR, ID_VCHR_LINE, ID_VCHR_LINE_DIST, CODE_TYPE_CHRG, ID_VCHR_LINE_CHRG
         FROM [dbo].[vwMP_VOD]
    ) AS V
      ON inserted.Org = V.Org
        AND inserted.ID_VEND = V.ID_VEND
        AND inserted.ID_ORG_ORIG = V.ID_ORG_ORIG
        AND inserted.ID_VCHR_NBR = V.ID_VCHR_NBR
        AND inserted.ID_VCHR_LINE = V.ID_VCHR_LINE
        AND inserted.ID_VCHR_LINE_DIST = V.ID_VCHR_LINE_DIST
        AND inserted.CODE_TYPE_CHRG = V.CODE_TYPE_CHRG
        AND inserted.ID_VCHR_LINE_CHRG = V.ID_VCHR_LINE_CHRG;

INSERT INTO [dbo].[vwMP_VOD]
SELECT inserted.*
FROM inserted
    LEFT JOIN (
         SELECT ORG, ID_VEND, ID_ORG_ORIG, ID_VCHR_NBR, ID_VCHR_LINE, ID_VCHR_LINE_DIST, CODE_TYPE_CHRG, ID_VCHR_LINE_CHRG
         FROM [dbo].[vwMP_VOD]
    ) AS V
      ON inserted.Org = V.Org
        AND inserted.ID_VEND = V.ID_VEND
        AND inserted.ID_ORG_ORIG = V.ID_ORG_ORIG
        AND inserted.ID_VCHR_NBR = V.ID_VCHR_NBR
        AND inserted.ID_VCHR_LINE = V.ID_VCHR_LINE
        AND inserted.ID_VCHR_LINE_DIST = V.ID_VCHR_LINE_DIST
        AND inserted.CODE_TYPE_CHRG = V.CODE_TYPE_CHRG
        AND inserted.ID_VCHR_LINE_CHRG = V.ID_VCHR_LINE_CHRG
WHERE V.Org IS NULL;

What I've done here is to take the your WHERE IN condition and replicate it with a join instead.

In the "update" case, you wanted all rows in the INSERTED table that are also in the [dbo].[vwMP_VOD] table.  Textbook inner join.  Joining on the key columns should be pretty quick.  If not, make sure your table has a PRIMARY KEY defined on these columns; if you have a surrogate key (ID column) instead, then you can still add a UNIQUE INDEX on the columns used to identify the rows in this upsert.

In the "insert" case, you want all rows in the INSERTED table that are not in [dbo].[vwMP_VOD].  To avoid concatenating all the key columns together, I simulated the effects of the EXCEPT operation by using a LEFT JOIN from INSERTED to [dbo].[vwMP_VOD], joining on all key columns, and adding a WHERE condition that checks that a non-nullable column from [dbo].[vwMP_VOD] is null.  That reliably indicates that there was no row present in the right-hand table ([dbo].[vwMP_VOD]).


Area under curve and its volume as solid of revolution

Here's how I would rewrite this:

First, pipe everything that you can. It's easier to follow the linear transition of a |> b |> c rather than c (b a).

Second, compose where possible. Compositions are powerful, and can allow you to abstract things away much more effectively.

Third, order function parameters by most -> least generic. We see f a b, but F# sees let f = f a; f b, so make sure your parameters are ordered by least-significant first.

module Calculus =
    let area f a b =
        let dx = 0.001
        { a .. dx .. b }
        |> Seq.sumBy (f >> (*) dx)

    let rotate f x =
        let multX = x |> f |> (*)
        Math.PI |> multX |> multX

    let volume = rotate >> area

[<EntryPoint>]
let main args =
    let shape = (2.0 |> (*), 1.0, 10.0)
    printfn "%f" (shape |||> Calculus.area)
    printfn "%f" (shape |||> Calculus.volume)

This ends up being three lines longer, but it's clearer. It's completely obvious what is happening, and the piping makes it easier to follow. We replaced the custom sequence generator with a basic one, and used sumBy to make our intent clearer. We want to sum f(x) * dx.

This also ends up one line shorter, and that's only because we rewrote volume as a pure composition, and pushed it to a one-line definition. I recommend doing this for things that are 2-3 steps. (So even let volume f = f |> rotate |> area would be acceptable.)

Instead of building the f in the main, we build the shape itself, and then pipe all three arguments of that shape to our area and volume methods. (Since the arguments are the same for each call.)

This means our shape is reusable, and we could build a function:

let printShape s =
    printfn "%f" (s |||> area)
    printfn "%f" (s |||> volume)

let shapes =
    let f = 2.0 |> (*)
    [(f, 1.0, 10.0); (f, 2.0, 10.0)]
shapes |> List.iter printShape

Now we can build more test-cases pretty easily and functionally. Because printShapes takes a single parameter of a (float -> float) * float * float, we can pass the entire shape to it and then pass each portion of the tuple as individual parameters.


Getting the character index of recurring substring

I don't believe hashing the key provides any functionality: storing the searched string directly into the map would work.

Your map variable is effectively working as a list of hashed keys, not as an actual key-value mapping. Instead of pushing the keys to the collection, override the existing key if it exists, and set the value to be the last found index.

Utilizing the map this way, your code simplifies immensely, and it no longer relies on third-party libraries:

function multiIndexOf (s) {
  var map = [];
  return function (key) {
    var nextIndex = map[key] + 1;
    map[key] = s.indexOf(key, nextIndex);
    return map[key];
  }
}

var find = multiIndexOf('hello world, hello darling')

// Example usage
console.log(find('hello')) // => 0
console.log(find('hello')) // => 13
console.log(find('hello')) // => -1
console.log(find('hello')) // => 0
console.log(find('hello')) // => 13
console.log(find('el')) // => 1
console.log(find('ell')) // => 1
console.log(find('ell')) // => 14


Interpolating code delimited with character that can appear in code

I see an extra unnecessary variable that you can get rid of, or change another variable so that it makes more sense.

int opening = i;

you use this inside of a for loop.  You can do 2 things with this.

Just use the variable i where ever you had the variable opening
change the i variable to opening in the for loop like

for (int opening = 0; opening < str.Length; opening++)

hopefully this shows you how unnecessary that extra variable is, it isn't used anywhere else for anything other than the loops.

Other than that I would need to play with it and spend some time with it to see if it plays well with others.


Arguments in constructors matching fields

I've personally always found the _parent or Hungarian-notation letters at the beginning far uglier than just saying this. this is very straightforward, especially if somebody else is reading your code. If I inherit somebody else's code and they use _ I change it immediately.


I fail to see if the code actually worked, because the isinstance should raise an exception:

    elif isinstance(input, list, tuple):
TypeError: isinstance expected 2 arguments, got 3

The second argument should be a tuple of types:

    elif isinstance(input, (list, tuple)):

but that might be a simply copy-over error.

In your code you do not need to force conversion to a list. The .join function can take an iterator as its argument. You free up a little memory for your program execution.

if isinstance(input, dict):
    return "{{{}}}".format(",".join(("{}:{}".format(convert_to_string(key), convert_to_string(value)) for key, value in input.iteritems())))
elif isinstance(input, list, tuple):
    return "[{}]".format(",".join((convert_to_string(element) for element in input)))

Since you already have imported the types module, I'd suggest that you be consistent, and use types.ListType, types.DictType etc. as well.


You should clean up every Select and Activate and use objects instead

You'd better use the object model of VBA.
For instance, if you only want to copy the value of a cell:

Don't do

Range("A1").Select
Selection.Copy
Range("A2").Select
Selection.Paste

Do

Range("A2").Value = Range("A1").Value

Another example:

Don't do

Cells.Find(...).Activate
lastrow = Selection.Row - 1
colno = Selection.Column
firstrow = Selection.End(xlUp).Row + 1

Do

Dim mycell as Range
Set cell = Cells.Find(...)
lastrow = mycell .Row - 1
colno = mycell .Column
firstrow = mycell .End(xlUp).Row + 1

And so on, especially on your Sheet objects.

Example to copy-paste between sheets

You only have to adapt this kind of statement to your specific case:

Worksheets("Sheet1").Range("A1").Copy
Worksheets("Sheet2").Range("A2").PasteSpecial xlPasteFormulas

Other tips

You can also have a look at the very good website of Chip Pearson

Edit

Instead of:

Sheets(i).Activate
Range("A6").EntireRow.Select
Range(Selection, Selection.Offset(1000, 0)).ClearContents

You can try:

Dim lastCol as Long
With Sheets(i)
    lastCol = .Cells(6, .Columns.Count).End(xlToLeft).Column
    .Range("A6", .Cells(1000, lastCol)).ClearContents
End With

This will find the last column where you have data (so that you don't have to clear contents of the entire row) on the 6th row and then it will clear the content of the Range between A6 and the last column and the 1000th row.

Another edit

You also have a minor issue in your declaration part.

This:

Dim mycell As Range, LastRow, ColNo, FirstRow, i As Integer

doesn't work, you have to do:

Dim mycell As Range, LastRow As Integer, ColNo As Integer, FirstRow As Integer, i As Integer


First, I think you've flipped the assigning without noticing that you're assigning null values to the meeting properties (e.g meeting.Id = mvm.Id;) notice that you've already create a new instance of Meeting object, and yet, you replaced the actual values with the new instance values, while you are expected to do the opposite.
So, I assumed you meant to do this mvm.Id = meeting.Id;.
If you need to add the Meeting object to the model based on the Type property. You can do this :
foreach (var meeting in meetingList)
{
    // if this element's Type property is null or empty
    // then skip and go to the next one
    // this condition will be applied on all meeting types
    if(string.IsNullOrEmpty(meeting.Type)) { continue; }

    meetingviewmodel.Add(meeting);
}

this will add all meeting objects that have defined Type, this will include System and Config types along with any other defined types.
if you only need to add System and Config types  meetings, and ignore the rest, you can do this :
foreach (var meeting in meetingList)
{
    // if you want to only add System & Config meetings
    // you can use this condition
    if(!string.IsNullOrEmpty(meeting.Type) && (meeting.Type == "System" || meeting.Type == "Config"))
    {
        meetingviewmodel.Add(meeting);
    }
}

or if you into LINQ :
var meetingviewmodel = meetingList
            .Where(x=> !string.IsNullOrEmpty(x.Type) && (x.Type == "System" || x.Type == "Config"))
            .ToList();


Implementing a Stack with Templates and Smart pointers

Readability

Please put a space after the include and before the <

#include<iostream>
#include<string>
#include<memory>

Don't do this

You can read any other C++ revue on this site.

using namespace std;

See: Why is “using namespace std” considered bad practice?

Don't add useless comments

// Template Node
template <typename T>
struct Node

Thanks but I can read the code I can see it is a template and a class called Node. Useless comments are worse than no comment.

// Template Stack
// Note: T type is used to set the Node type
template <typename T>

Again you are describing what the code does. If you write nice well formatted code it should explain itself (with good method and variable names).

// Notice <T> after the class name, it is the syntax requirement
template <typename T>
void Stack<T>::push(const T &data) {

Don't explain the compiler rules. The compiler does not care nor do I.

Pass parameters by reference

Here you pass the parameters by value.

    Node(T d, shared_ptr<Node> n) : data(d), next(n) {}

This means you are copying the data to the parameters than you are making a second copy of the data into the member variables.

Try this:

    Node(T const& d, shared_ptr<Node>& n) : data(d), next(n) {}

You can even use move semantics. I'll cover that more in the push() below.

    Node(T&& d, shared_ptr<Node>& n) : data(std::move(d)), next(n) {}

Push

You don't need that if block.

void Stack<T>::push(const T &data) {
    shared_ptr<Node<T>> temp = make_shared<Node<T>>(data,nullptr);
    if (head == nullptr) {
        head = temp;
    }
    else {
        temp->next = head;
        head = temp;
    }
}

You always assign temp to head. The value assigned to temp.next is nullptr if the head is nullptr or it is head. In both cases the value of head is assigned to next.

void Stack<T>::push(const T& data) {
    head = make_shared<Node<T>>(data, std::move(head));
}

You pass the data by reference, which is good. Make sure that node also takes the parameter by reference.

In some situations we also want to add move semantics to the class. So it can also be useful to add a push() that takes an r-value reference. This allows for a much more efficient push when T is large (like an vector).

void Stack<T>::push(T&& data) {
    head = make_shared<Node<T>>(std::move(data), std::move(head));
}

Also in the vain of push. Sometimes T is expensive to build and copy but its arguments can easily be passed. In this case it is worth allowing the user to pass the parameters to the constructor of T and then building the T object in place (rather than passing it around).

template<typename... Args>
void Stack<T>::push<Args>(Args...&& args) {
    head = make_shared<Node<T>>(std::move(args));
}

template<typename... Args>
Node<T>::Node<Args...>(Args...&& args)
    : data(args...) // Use the constructor of T
{}

Top

Here you return the result by value. This means a copy is probably generated. This could be expensive so it I would return a reference rather than a value. The user can then decide if they want to copy the reference explicitly into a value.

T Stack<T>::top() const {
    return head->data;
}

Change to

  T const& Stack<T>::top() const {
//  ^^^^^^
      return head->data;
  }

Print

Looks fine.

void Stack<T>::print() const {
    // shared_ptr<Node<T>> temp;
    for (auto temp = head; temp != nullptr; temp = temp->next)
        cout << temp->data << '\n';
}

The thing I would change is to pass a stream as a parameter (std::cout is not the only stream you want to print to). It can default to std::cout for backward compatibility.

Also the standard way of printing in C++ is using operator<< so it would be nice to define that in addition.

void Stack<T>::print(std::ostream& str = std::cout) const
{
    for (auto temp = head; temp != nullptr; temp = temp->next)
        str << temp->data << '\n';
}

std::ostream& operator<<(std::ostream& str, Stack<T> const& value)
{
    value.print(str);
    return str;
}


Have I missed some obvious XSS vulnerabilities?

It would help if you explained exactly why you think this approach is more robust than using strip_tags. It will certainly be likely to be a lot slower.

From a quick inspection it doesn't seem to filter CSS behaviours nor data URIs.

If it were me I'd be building on to strip_tags rather than trying to start from scratch.


Balanced smileys check algorithm (part 4)

Correctness

I suggest you add a test to verify(':):)(():(:(', False).  Perhaps your counters need to be reset?

Algorithm

The great thing about your algorithm is its simplicity.  However the algorithm now requires scanning the loop twice. The problem can be evaluated in a single pass with a different strategy, should you wish to consider performance.

Coding

Consider whether every line in your algorithm is actually relevant to the result.  Specifically, if you don't use smile in the first loop or frown in the second loop, why count them?

Beyond that and the stylistic comments I made previously, you might sit back in your chair and scan your solution.  Where the meaning, intent and motivation are unclear you might consider augmenting it by variable name selection and with comments.

Alternate Strategy

As an example of an alternate strategy that only requires scanning once, you might

keep a count of unpaired parens, opt_open, opt_close
borrow from opt_open as needed to pair with excess close parens
ensure opt_close never exceeds unpaired parens count since those are out of scope
ensure final unpaired parens count does not exceed opt_close

def check_balance(src):
    opt_open = opt_close = 0
    count = 0
    has_eyes = False

    for char in src:
        if char == '(':
            if has_eyes:
                opt_open += 1
            else:
                count += 1

        elif char == ')':
            if has_eyes:
                opt_close += 1
            elif count > 0:
                count -= 1
            # if needed pair with an optional parens
            elif opt_open > 0:
                opt_open -= 1
            else:
                return False

        if opt_close > count:
            opt_close = count

        has_eyes = (char == ':')
    return count <= opt_close


I realize this question is old now, but it's intriguing and still getting a number of views, so I though I would give it a shot.
Now days there's a very easy solution to this: Just use async/await syntax instead so that you can use normal flow-control statements to get the job done. However, I'll write this under the assumption that this task needs to be done in legacy es5.
Lets take a simplified example. A lot of the links in your promise chain tended to have a structure such as this:
firstTask()
    // before...
    .then(function () {
        return asyncTask()
            .catch(function (err) {
                // handle catch
                return Promise.reject('DONE'); // This gets caught at the end of the promise-chain and ignored
            });
    })
    // after...

You're right in assuming that it's not such a great idea to be rejecting with a sentinel like that in order to skip over future .then()s. The proper solution is to restructure this in order to make it so there's nothing that needs to be skipped over. The following would have the same effect, but without needing to reject with a sentinel.
firstTask()
    // before...
    .then(asyncTask)
    .then(
        function () {
            // after ...
        },
        function () { /* handle catch */ }
    )

While this does fix the issue, you'll notice an important problem: The // after ... part is now nested a couple levels deep. Each time we need this skip-to-the-end behavior, we will have to add even further nesting, and that's just gross  - we just got ourselves right back into the callback hell that promises were designed to prevent. This is an unfortunate limitation to promises, however, even callback hell can be tamed with some good coding practices. If we split up the logic into multiple functions, then we can avoid having too much nesting happening in one place.
firstTask()
    // before...
    .then(asyncTask)
    .then(
        doAfter,
        function () { /* handle catch */ }
    )

function doAfter() {
    // after ...
}

And now we have a recipe to fix up this code! Below I have an (untested) version of the original code that's been fixed up so it doesn't need to break out of a promise chain anymore. I did make one change that simplified things a bit: I took out the places where you would catch an error, then re-reject it like this Promise.reject({ text: 'file rename failed', err: err }), which you later re-caught, logged the error, and returned the text to the user. The end-user doesn't need to know what specific internal detail went wrong, simply giving back "Internal Server Error" should be good enough.
var id = req.param.id;

promisifiedWriteFile('src.txt', 'foobar')
    .then(function () { return exec('my-command src.txt') })
    .then(onExecute, onExecuteError)
    .then(function (response) { res.send(response) })
    .catch(function (err) {
        res.status(500).send('Internal server error');
        console.error(err.message);
        console.error(err.stack);
    });

function onExecute (ret) {
    var fileHasBadName;
    return isFileNameBad()
        .then(function (fileHasBadName_) {
            fileHasBadName = fileHasBadName_;
            if (fileHasBadName) return fixBadFileName(id);
        })
        .then(function () {
            return fileHasBadName ? 1 : countPagesInOutput(id);
        })
        .then(function (pages) {
            return { output: ret.stderr, id: id, pages: pages };
        });
}

function onExecuteError (err) {
    return { error: err.stderr, id: id, pages: 0 };
}

function isFileNameBad() {
  return promisifiedStat('resultWithBadName.txt')
    .then(function () { return true }, function () { return false })
}

function fixBadFileName(id) {
    return promisifiedRename('resultWithBadName.txt', 'result' + id + '.txt')
}


Class name and general comments

Your class is named Flowers but there is a comment here that says:

/* (...) Your class should be named Solution. */

Although I think that Flowers is a much better name, personally.

Generally, I understood your code better than the assignment description, so well done there.

Array instead of ArrayList

Instead of using an ArrayList <Integer>, that by the way would be better to declare as List<Integer> (use interface for declaration, implementation for initialization), you could use an int[] instead, as you know the exact size of the list. There's no need to do any dynamical resizing of the list, so a int[] would be just fine.

Small spacing nitpick

A little nitpick would be to use a bit more spacing, I am a bit allergic to lines like this:

for(int i = 0; i<numFlowers;i++){

better would be:

for (int i = 0; i < numFlowers; i++) {

And also:

total +=(flowersBought+1)*price;

becomes:

total += (flowersBought + 1) * price;

Closing statement

Again, your code was very readable and your approach is good, and indeed it is a greedy algorithm

As said on Hackerrank:

  A greedy algorithm is an algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum.

This is indeed what your code does. It always picks a way to buy the flower in the cheapest way.


Your code doesn't actually work, because your two lambdas both used x as the parameter name, and the inner one shadows the outer one. Here's a fixed version:

(define (tridiagonal n)
  (build-list n
              (lambda (x)
                (build-list n
                            (lambda (y)
                              (cond
                                [(= x y) 2]
                                [(or (= x (sub1 y))
                                     (= x (add1 y))) 1]
                                [else 0]))))))

This works, but in Racket, it's probably more idiomatic to use for/list for creating a list:

(define (tridiagonal n)
  (for/list ((i (in-range n)))
    (for/list ((j (in-range n)))
      (max 0 (- 2 (abs (- i j)))))))

As you can see, I've taken the liberty of simplifying your cond expression too, into a single (max 0 (- 2 (abs (- i j)))) expression.


In my experience, FTP can use up a lot of network packets and CPU time just negotiating the starting and finishing of a single file.  If there exists the option of having an archive uncompressed at the destination, I would suggest zipping the images into a single file for transport.

To get even more performance for the end user making the CF request you could perform the FTP transfer in an asynchronous thread via cfthread.  Launch the thread that zips and sends the file and let the user know that the data is on its way.

Hope this helps, or at least inspires some new ideas.


Don't limit Cartesian products to arithmetic types
You shouldn't limit your class to only allow products of vectors of a type that satisfies std::is_arithmetic. Why shouldn't I be able to do a Cartesian product of a std::string and a std::chrono::time_point for example? There is no actual multiplication involved in a Cartesian product after all.
Your class will likely force copies of vectors to be made
In this constructor:
cartesian_product(std::vector<std::vector<T>> const& sequences) {...}

The parameter sequences is a reference, so you might think that this doesn't cause any copies to be made. However, that is only true if the caller already has a vector of vectors lying around. In your own example usage in main(), you have four vectors a, b, c and d, but then you create the vector of vectors s which causes a copy to be made of the four original vectors. And the following line constructs a temporary that also makes copies:
cartesian_product<int> r(std::vector<std::vector<int>>{ a, b, c, d });

Support more containers besides std::vector
You only support products of std::vector<T>, but what if I have my data in a regular array, a std::array, a std::list or any other container? Again, it is an unnecessary restriction. Try to rewrite it so any type of container works. Either have it accept a reference to a container object directly, or have it accept iterators like the STL algorithms do.
Return a tuple instead of a vector
A std::vector will allocate memory on the heap, which will impact performance. And since you know the size of the result, you can return a std::tuple instead, which has the advantage that it can be unpacked using C++17's structured bindings. Apart from that, with a std::tuple the value types of each input vector/array/etc can be different, whereas your solution requires all of them to be the same,
Add iterators to your class
Indeed, it makes sense to add iterators to your class. In fact, it already basically keeps track of everything that an iterator would do, and next() is the equivalent of an iterator's operator++(). Ideally, you want to be able to write something like:
std::vector<std::string> a_vector{"foo", "bar", "baz"};
std::list<int> b_vector{4, 5, 6, 7};

for (auto [a_element, b_element]: cartesian_product(a_vector, b_vector))
    std::cout << a_element << ", " << b_element << "\n";

And then expect the following result:
foo, 4
foo, 5
foo, 6
foo, 7
bar, 4
bar, 5
...

This also avoids the need for a has_next() function.


Finding the lowest and highest values in an array... with "Poor Man's DI"

First of all, kudos for exercising OOP and DI! Coding against interfaces is going to make your life easier in so many wonderful ways!

I agree, no problem is too simple to solve with SOLID principles, especially for learning purposes. Shifting from procedural to object-oriented code takes practice.

The first key to proper OOP is abstraction.

These are the abstractions I see in your code:

IMathPerformer, an interface that gets some answer given an int[]. Implementations are responsible for computing the Min or Max value, or any other operation that returns an int given an int[].

That's unfortunately all. Unfortunate, because I see these requirements in your code:

Collecting the data (the int[] to work with)
Determining what to do with the data
Outputting the result

And from these requirements, I see these responsibilities:

Interacting with the console

Validating user input

Collecting the data
Knowing what to do with the data

Creating the menu with each available command

Performing the appropriate command
Outputting the result
Coordinating the sequence of operations

If a class should be responsible for one thing, then there should be at least 5-6 types in this program.

Back to your code: the Math class doesn't seem to really "fit in" anywhere in the above list - or rather, it's redundant: the command to execute is already known when the class gets created, and it acts as a middle man that doesn't really do anything that the IMathPerformer can't do just as well without it; it's forcing dependency injection, but there's nothing that justifies it because the abstraction level in the calling code is too low.

Abstraction levels are crucial. The entry point of your program (the Main method) should have a very high abstraction level, and is usually pretty short. For example:

public static void Main(string[] args)
{
    var app = CreateApp(args);
    app.Run();
}

We create an app object and call its Run method. The CreateApp method might look like this:

private static ArrayOpsApp CreateApp(string[] args)
{
    var validator = new UserInputValidator();
    var console = new ConsoleUserInterface(validator);
    var argsParser = new CommandLineArgsParser();
    var collector = new IntConsoleCollector(console, argsParser, args);

    var commands = new[] {
        new MinValueFinder(),
        new MaxValueFinder(),
        new AvgCalculator(),
        new StdDevCalculator(),
        //...
    };
    var commandSelector = new ConsoleCommandSelector(console, commands);
    var app = new ArrayOpsApp(console, collector, commandSelector);

    return app;
}

This method has a very special role: it's the only place in the application we're allowed to new up one of our concrete types - everywhere else, we are coding against interfaces. It's the application's composition root, where we compose the application's dependency graph.

Just by looking at this code, you can get a grasp of how the entire application is structured, because every type has its dependencies injected through the constructor.

You know that the IntConsoleCollector is the specific implementation for what the rest of the code sees as some abstract IDataCollector, or even a generic IDataCollector<int>.

You know that the user input will be validated somehow.

Because that type takes a ConsoleUserInterface implementation for what might be its IUserInterface dependency, we know that the type needs an object that's responsible for dealing with UI concerns, and because it takes an IArgsParser, we can infer that we can specify the input with command-line arguments and that the collector might just spit them back and skip prompting the user for them. Perhaps it's also used for parsing the user's input if the args array is empty or doesn't contain anything useful - but that's an implementation detail.

We know exactly which commands will be available for the commandSelector, and again we know that the selector will work with the console, because we're giving it console for its IUserInterface dependency; we can infer that the selector will be iterating the available commands to create a menu interface using the console.

The method then injects the collector and the selector dependencies into a new ArrayOpsApp, which will obviously be responsible for consuming these dependencies and coordinating the sequence of operations.

The Main method in your code has both hands into that sequence of operations; it's responsible for collecting the data, dealing with the user's input, determining which concrete types to use, ... it does pretty much everything except actually computing the min/max values.

You started implementing DI, but stopped somewhere along the way. Half-implemented DI unfortunately doesn't get half the benefits of DI: the only testable code is the code that you've extracted into an interface... which makes the IMathPerformer interface pretty much useless, since if you test the implementations you don't really need the interface it's implementing.

There is no way to write a test that documents what happens when the user enters invalid input. Sad, because you would have found out that you get a FormatException when the int.Parse call fails.

Because of the high coupling and low cohesion of the Main method, most of the code can't be unit-tested at all. You'll want to reverse that, and achieve low coupling and high cohesion.

SOLID isn't everything though: it doesn't really touch on the minute implementation details. This is where things like the DRY principle kick in:

if (choice == 1){
    math = new Math(new HighestNumber(), arr);
    Console.WriteLine("Answer: " + math.returnAnswer());
}
else if (choice == 2){
    math = new Math(new LowestNumber(), arr);
    Console.WriteLine("Answer: " + math.returnAnswer());
}

Don't Repeat Yourself. That Console.WriteLine call doesn't belong in either branch of that conditional:

if (choice == 1){
    math = new Math(new HighestNumber(), arr);
}
else if (choice == 2){
    math = new Math(new LowestNumber(), arr);
}
Console.WriteLine("Answer: " + math.returnAnswer());

But then again, implementation details are also impacted by the high-level structure of the code - for example with a higher abstraction level and injected dependencies, the entire ArrayOpsApp might look like this:

public class ArrayOpsApp
{
    private readonly IUserInterface _ui;
    private readonly IDataCollector _collector;
    private reaodnly ICommandSelector _selector;

    public ArrayOpsApp(IUserInterface ui, IDataCollector collector, ICommandSelector selector)
    {
        _ui = ui;
        _collector = collector;
        _selector = selector;
    }

    public void Run()
    {
        var data = _collector.CollectData();
        var command = _selector.SelectCommand();
        var result = command.Execute(data);
        _ui.OutputResult(result);
    }
}

Notice you can write a test that validates that ArrayOpsApp.Run() calls the CollectData member of its IDataCollector dependency, the SelectCommand member of its ICommandSelector dependency, and the OutputResult of its IUserInterface dependency. If we also mock the output of the selector's SelectCommand method we can also verify that the command's Execute method is called, so we can write tests that document what the Run method is supposed to be doing; how it does it doesn't matter.

Writing SOLID OOP code makes your code testable, right. But writing SOLID OOP code is much easier if you start by writing the tests, or rather, by asking yourself how you would want to be able to test the code. Don't just rush into implementing the functionality - of course you can implement the functionality, it's just a very simple exercise after all! It's not about the functionality itself, it's about properly separating concerns and doing things right. Remember:

Single Responsibility Principle: a class should have one single reason to change.
Open/Closed Principle: the design is extensible, so instead of modifying a class to add functionality, you just add a new one that implements it.
Liskov Substitution Principle: all implementations of an interface fulfill the same contract - substituting one implementation for another doesn't break the program. IUserInterface could very well be a WinForms or a WPF UI, makes no difference. Or a console UI. Or no UI at all, just a mock.
Interface Segregation Principle: interfaces should be specialized. Remember modifying an interface is a breaking change.
Dependency Inversion Principle: depend on abstractions, not concrete types.

(SOLID)


Cut and paste rows to new sheet based on different criteria in Column A

As long as all the rows in your working sheet have a valid identifier, you can simplify this process a lot by looking at each row and looking up the Sheet you're supposed to copy the row to.

This allows you to write a single loop instead of a loop for each ID there is:

Dim source As Worksheet
Dim target As Worksheet
Dim targetRow As Long

Set source = ThisWorkbook.Worksheets("Working Sheet")
' As long as there is a row to cut and paste
Do While source.Cells("A2").Value <> vbNullString
  ' select where the row is supposed to go
  Set target = ThisWorkbook.Worksheets(source.Cells("A2").Value)
  targetRow = target.Cells(target.Rows.Count, "A").End(xlUp).Row + 1
  ' and transfer it using copy & delete
  With source.Range("A2").EntireRow
    .Copy target.Range("A" & targetRow)
    .Delete xlShiftUp
  End With
Loop

Of course if that's not the case, this simplification still applies: Iterate the rows of the worksheet once and only Copy&Delete the rows where the identifier matches one of the allowed identifiers.

If deleting the rows from the working sheet is not correct, or you don't want to move every row, you will need to iterate using a For Loop.


Alternative to null check after DOM traversal?

Stuff I noticed:

You're missing a semi-colon:

var elementText = element.innerText

The elementClass variable could have a slightly more descriptive variable name. "targetClass" for instance, to indicate that this is the class we're going to look for.

This loop condition is overly complicated:

while(element && !((" " + element.className + " ").indexOf(" " + elementClass + " ") > -1)){

Your code says "if x is not greater than -1", which is the same as simply saying "if x is -1", i.e. x == -1 (or better yet, strict equality: x === -1), so that would clean things up.

Also, instead of all the string-concatenation, you could:

Use element.classList.contains('menu-parent') if you're targeting modern browsers (Internet Explorer 9 and below don't support classList)
Or use element.className.split(' ').indexOf(...) to look through an array of discrete class names (basically emulating classList)
Or use a regular expression like /(^|\s)menu-parent(\s|$)/i.test(element.className)
Or add the spaces in the elementClass variable, so you don't have to add them every time you want to check.

I'd use #2. This gets us:

while(element && element.className.indexOf(elementClass) === -1) {

More on this later.

Then there's this:

  if (element == null){
    console.log('equals null - ' + elementText);
  }else{
    var anchor = element.querySelector("a");
    var clean = (anchor.innerText || anchor.textContent).toLowerCase() + " : " + elementText;
    console.log('does not equal - ' + clean);
}

For one, the indentation's wrong. For another, as you yourself wrote, you don't need the == null in the condition.
In fact, you've already used the plain element in the while loop's condition. There you checked if element "was anything" which is exactly the same thing you're doing here.

Also, don't leave console.log statements in your production code. Like the 25, this is probably just a test-thing, right? Still, it's good to know that some JS runtimes don't have a console, so calling console.log will just cry "console is undefined!" and stop everything.

If you insist on using it, at least check whether console exists first:

if(console) { console.log(...); }

You could also throw that into a function, so you're sure to always have a check, and so you have 1 place in which to simply turn off logging.

Now, getting back to the loop: I'd change it up, making the "find ancestor by class name" a function:

function getAncestorByClassName(from, className) {
  while(from) {
    if(from.className.split(' ').indexOf(className) !== -1) { # or any of the other options
      return from; // found a match, return it (stops the loop, exits the function)
    }
    from = from.parentNode; // go up a level and repeat
  }
  return null; // if the loop just ended normally, we didn't find anything
}

Now we've got a generic function you can use whenever necessary. This makes the rest of the code a lot simpler:

var element = document.getElementsByClassName('gtm_navHeader')[25],
    ancestor = getAncestorByClassName(element, 'menu-parent'),
    anchor, clean; // declare all your variables up top; just good practice

if(ancestor) {
  ...
} else {
  ...
}


Count number of ways that sequences contain at least one of the given subsequences

Use numpy!

Don't roll your own matMul. It's not worth it. numpy will outperform you and will be simpler to use. The same goes for matPow, though (I'm not sure) you may still need to write a thin wrapper around numpy.

Python names

Use snake_case for functions and variables, such as

get_sub_prob

Make a main function

...to pull your last six lines out of global scope.


Ruby Exercise: Implement your own "#group_by" method

Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect almost all of the style violations I am going to point out (and even some more), and was able to autocorrect almost all of them.
Testing
There is no automated testing in your code. Apart from the single example at the very end (which is not automated), there is no testing at all.
You should always strive to have as close to 100% test coverage as possible. It doesn't really matter if you have unit tests, functional tests, integration tests, end-to-end tests, or a mix of them, but you should have tests, and they should be automated.
In this particular case, since you are implementing a Ruby core method, there are already plenty of tests written for you in the Ruby/Spec project as well as the YARV test suite.
Running the Ruby/Spec tests against your code yields 3 errors, 1 failure, and only 3/7 passing tests.
The YARV test suite has 1/2 passing assertion and 1 error.
Indentation
The standard indentation style in the Ruby community is 2 spaces, not 4.
Empty parameter list
When you define a method without parameters, don't write out an empty parameter list. Just leave out the parameter list completely.
Instead of
def gruppiere()

you should have
def gruppiere

Naming
ret and tmp aren't really good variable names. Try to make them more expressive so that they reveal their intent. Okay, so it's a temporary variable, but what does it do, what is it for, why is it there?
Normally, the reason to introduce a temporary variable is to give an intention-revealing name to some sub-expression. But tmp is not very intention-revealing.
At least, spell them out. You are not going to wear out your keyboard by writing temp instead of tmp, I promise.
Unnecessary self
self is the implicit receiver in Ruby if you don't explicitly provide one. There is no need to explicitly provide self as the receiver (except in some very limited special circumstances).
Instead of
self.each

just write
each

Block delimiters
The standard community style for block delimiters is to use { / } for single-line blocks and do / end for multi-line blocks.
There is a small minority that follows a different style: { / } for functional blocks and do / end for imperative blocks
Whichever style you follow, your block should use do / end since it is both multi-line and imperative.
Explicit equality check against nil
You should not check for equality with nil. There is a method Object#nil? which returns false for all objects, and the only override of this method is NilClass#nil?, which returns true. In other words: the only object that will ever respond with true to nil? is nil.
Instead of
ret[key] == nil

you should write
ret[key].nil?

Unnecessary array mutation
In this piece of code:
tmp = []
tmp << item

You assign an empty array to tmp, then immediately append item to the empty array. That's exactly the same as assigning an array with one item to tmp in the first place:
tmp = [item]

Unnecessary temporary variable
Once we have made the above change, this piece of code:
tmp = [item]
ret[key] = tmp

doesn't really need the temporary variable anymore:
ret[key] = [item]

See? The reason why you didn't find a good name for that variable, is that it shouldn't even be there!
Hash default value
Actually, we can get rid of that whole conditional expression by instead making sure our result hash automatically initialized non-existent keys with an empty array the first time the key is accessed:
def gruppiere
  ret = Hash.new {|hash, key| hash[key] = [] }

  each do |item|
    key = yield item
    ret[key] << item
  end

  ret
end

This, by the way, also gets rid of one of the things Rubocop was complaining about but was unable to auto-correct: the method was too long.
Higher-level iteration methods
each is a very low level iteration method. It is usually barely needed in Ruby. As a general rule, in Ruby

When you are writing a loop, you are definitely doing something wrong.
When you use each, you are very likely doing something wrong.

The pattern you use in your code looks like this: you create a result object, then accumulate results in this object, and at the end return it. This pattern is actually a Fold. In Ruby, fold is provided by Enumerable#inject (and its alias Enumerable#reduce) and Enumerable#each_with_object.
Here is what the method would look like using Enumerable#each_with_object:
def gruppiere
  each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |element, result|
    key = yield element
    result[key] << element
  end
end

Iteration protocol
It is standard that iterator methods return an Enumerator when called without a block. We can use the Object#enum_for method to create an Enumerator for our method. We just put the following code as the first line of our method:
return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

This actually fixes all of the test errors we had.
Test failures
Unfortunately, we have introduced one new test failure with our refactoring to auto-initialize the hash. group_by should not return a Hash that has default_proc set.
We have two choices:

Set default_proc to nil.
Create a new hash.

I opted for the latter, to create a new empty hash and Hash#merge onto it, to be 100% sure that the default_proc as well as any internal flags are reset to defaults:
def gruppiere
  return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

  {}.merge(
    each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |element, result|
      key = yield element
      result[key] << element
    end
  )
end

Hash#fetch
There is actually a better option than using a default_proc. Hash#fetch will get the value corresponding to the key if the key exists and otherwise return a value of our choosing:
def gruppiere
  return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

  each_with_object({}) do |element, result|
    key = yield element
    result[key] = result.fetch(key, []) << element
  end
end

Monkey patching core classes / modules
Monkey patching core modules is generally frowned upon. If you do it, it is good practice to put your monkey patches in a separate mixin with a clear name, and mix that into the class or module you want to monkey patch. That way, it shows up in the inheritance chain, and people can use the name in the inheritance chain to make a guess at the filename, when they find this strange method in their array that they have no idea where it comes from.
Refinements
NOTE! This advice is controversial.
When monkey patching, it is a good idea to wrap your monkey patch into a Refinement, so that consumers can only pull it in when they need it, and it doesn't pollute other parts of your code.
Unfortunately, most Ruby implementations don't implement Refinements, so as nice as the benefits are, it essentially makes your code non-portable.
The Result
If we put all of the above together, we end up with something roughly like this:
module EnumerableGruppiereExtension
  def gruppiere
    return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

    each_with_object({}) do |element, result|
      key = yield element
      result[key] = result.fetch(key, []) << element
    end
  end
end

module EnumerableWithGruppiere
  refine Enumerable do
    include EnumerableGruppiereExtension
  end
end

using EnumerableWithGruppiere

puts [1, 2, 3, 4].gruppiere(&:even?)
#=> { false => [1, 3], true => [2, 4] }

Addendum: Functional Programming
You tagged your question with functional-programming, but there is nothing functional about your code. There's looping, there is mutation, there are side-effects.
It is, however, not easy to program in a functional way in Ruby. Neither the core and standard library data structures nor the core and standard library algorithms really lend themselves to Functional Programming.
Here is a purely functional version that does not use mutation, side-effects, or looping:
def gruppiere
  return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

  inject({}) do |result, element|
    key = yield element
    result.merge({ key => result.fetch(key, []) + [element] })
  end
end

Now, you might ask yourself: that actually doesn't look that bad. Why did I say that Ruby is not amenable to Functional Programming?
The reason for this is performance.
Because Hash and Array are mutable, operations such as Hash#merge and Array#+ can only be implemented by copying the entire data structure. Whereas if Hash and Array were immutable, as they are in a collections library for a functional language, these operations could be implemented by what is called structural sharing, which means that Hash#merge and Array#+ would not return a full copy of the original but rather would return only the updated data and a reference to the old version. This is much more efficient.
For example, here is what the same code would look like in Scala:
def [A, B](seq: Iterable[A]).gruppiere(classifier: A => B): Map[B, Iterable[A]] =
  seq.foldLeft(Map.empty[B, IndexedSeq[A]]) {
    (result, element) => {
      val key = classifier(element)
      result updated(key, result.getOrElse(key, IndexedSeq.empty[A]) :+ element)
    }
  }

Iterable(1, 2, 3).gruppiere { _ % 2 == 0 }
//=>Map(false -> Iterable(1, 3), true -> Iterable(2))

As you can see, it looks more or less identical. Some names are different (e.g. foldLeft instead of inject, getOrElse instead of fetch, etc.), and there are some static type annotations. But other than that, it is the same code. The main difference is in the performance: Map.updated does not copy the map, it returns a map which shares all its data except the one updated key-value-pair with the original. The same applies to IndexedSeq.:+ (an alias for IndexedSeq.append).