O Levels 2210 Computer Science Pre-Release: Senior Citizens Trip Organizer

There are a few things to improve:

Task 1

the initial validation check is not correct. You are checking for a minimum number of people to be more than 2, while the error message says the minimum is 10:

  Sorry the range of people is 10 - 36. Please Try again.

I would use an inclusive ranges for readability. Also, you can use the chained comparison:

if 10 <= number_of_citizens <= 36

you can use a short if/else form when defining carer:

carer = 3 if number_of_citizens > 24 else 2

to avoid over-nesting things, I would handle the "negative case" first:

if not(10 <= number_of_citizens <= 36):
    print('Sorry the range of people is 10 - 36. Please Try again.')
    exit()

carer = 3 if number_of_citizens > 24 else 2

don't hardcode the coefficient values for costs and hires, define them as constants, or better in a separate configuration file or module

Task 2

Some of the things from the "Task 1" can also be applied here as well.

when you have a throwaway (not used, but syntactically needed) variable, it is agreed to use _ (underscore) variable name
looks like you don't have to keep the amounts in a list and can simply calculate the total amount, while only collecting names into a list
the range() starts at 0 by default, you can avoid specifying 0:

for _ in range(total_people):
     # ...

The definition step then might look like this:

names = []
total_amount  = 0

for _ in range(total_people):
    names.append(input('Name: '))
    total_amount += int(input('Amount: '))

when you print out the names, you can loop over the names in a list directly instead of looping over indexes:

for name in names:
    print(name)

Task 3

the break_even_value variable is set but never used

There were also some PEP8 violations in terms of code style, like missing spaces around operators or extra spaces after the function calls. Install a linter like flake8 or pylint to catch this kind of common violations.


Cleanest way to close over a counter in CoffeeScript

You could do this:

casper.on 'step.complete', do -> # invoked right away
  i = 0
  -> @echo "Step#{ ++i }" # implicitly returned function

Parentheses: None :-)

The do keyword is the equivalent of (-> ...)(), i.e. it means "invoke the  following function immediately" (it's also useful to avoid closure pitfalls in loops, by the way.)

The ++i will increment i before it's echo'ed, and CoffeeScript has implicit return, so the return keyword can be skipped.

Lastly, I left out the step function argument, as you're not using it for anything; you're always adding 1. You can always add it back in of course


Being given some generated code doesn't mean you can't criticize it. Unused imports, unused variables, meaningless variable names, unpythonic constructs… To organize things a bit more, you should also
Use functions
This is to separate the parsing of the input from the core of the computation. It can help you further test your logic without rellying on the input being fed through stdin. A basic layout could be:
def find_pattern_in_grid(grid, pattern, pattern_height=None, pattern_width=None):
    if pattern_height is None or pattern_width is None:
        pattern_height = len(pattern)
        pattern_width = len(pattern[0])

    return False  # Placeholder

def run_test_case():
    grid_height = int(input().split()[0])  # Dropping grid width, we don't use it
    grid = [input() for _ in range(grid_height)]
    pattern_height, pattern_width = map(int, input().split())
    pattern = [input() for _ in range(pattern_height)]

    return find_pattern_in_grid(grid, pattern, pattern_height, pattern_width)

def main():
    test_cases = int(input())
    for _ in range(test_cases):
        if run_test_case():
            print('YES')
        else:
            print('NO')

if __name__ == '__main__':
    main()

A few things to note here:

input() does not return the end-of-line character, so there is no need to strip() it;
even if it didn't, split() without argument have special logic to remove extraneous whitespace around words;
when building the grid or pattern you don't need to split since there is no whitespace in the rows. Even if it had, working with strings and sub-strings can be more efficient as you already do;
find_pattern_in_grid accept optional pattern_height and pattern_width so you can easily drop into an interactive session, import your file and feed this function with any pre-formatted input you want without having to bother computing the number of rows and columns beforehand;
dropping in an interactive session like that is the reason why it's a good habit to have an if __name__ == '__main__' clause that wraps all your top-level code.

As a bonus, having functions will let you return early so you might be able to remove flag variables.
Iterate over rows
Python makes it easy to iterate over content rather than using indexes to access the content. It is both faster and more pythonic. In case you need the indexes too, use enumerate:
def find_pattern_in_grid(grid, pattern, pattern_height, pattern_width):
    # search each potential matching row
    for y, row in enumerate(grid[:1-pattern_height]):  # [:-pattern_height+1]
        reduced_grid = grid[y:]  # Keep only the remaining row for further comparison

        # search vertically for every time that the first row in the search matrix matches
        match_index = row.find(pattern[0])
        while match_index != -1:
            # check to ensure row in outcome matches input
            for pattern_row, grid_row in zip(pattern, reduced_grid):
                grid_sub = grid_row[match_index:match_index+pattern_width]
                if grid_sub != pattern_row:
                    break
            else:
                return True

            # We didn't find the pattern, try another match
            match_index = row.find(pattern[0], match_index + 1)

    # Remaining of the grid turned out to be less than the pattern height
    return False

Here I used:

slicing (grid[y:]) and zip to iterate over both the remaining rows of the grid and the rows of the pattern at the same time;
for .. else to execute the else clause if (and only if) no break were reached within the for loop. Meaning no mismatch were found between the grid and the pattern.

I also incorporated the "match" condition directly within the while loop. But it lead to somewhat duplicated find as you can see, so not that ideal. And I removed the call to str since slicing a string already returns a string.


Create annotation to validate JWT in Spring controller instead of filter

I'd prefer the filter, just because then you don't have to worry about a missed annotation leaving your API wide open. I never found decoding JWTs to be expensive, and I suspect you're performing premature optimization.
value isn't especially descriptive. Perhaps @Authorize(users= would be better.
Your code can be simplified by returning early if a match is found, rather than counting failures and comparing them:

final JwtProperties jwt = JwtUtil.validate(webRequest.getHeader("Authorization"));
final String currentUser = jwt.getScope().get(0);

for (final String allowedUser : parameter.getMethodAnnotation(Authorize.class).value()) {
    if (allowedUser.equals(currentUser)) {
        return jwt;
    }
}

throw new UnauthorizedAccessException("Un-authorized access", 0xd1561);


Declare a local variable to hold the color:

var
  Color: TColor;

Then decide what the color should be:

if Temperatura<=15 then
  Color:=clBlue;
else if Temperatura<=18 then
  Color:=clAqua;
else ...

Then assign the color to the controls:

Form1.Label1.Font.Color:=Color;
Form1.Label2.Font.Color:=Color;
....

The labels could be stored in an array or a list. So that you can iterate over them to assign the color. You could declare the array like this, in the form class:

FLabels: TArray<TLabel>;

In the constructor assign it like this:

FLabels := TArray<TLabel>.Create(Label1, Label2, Label3, Label4, Label5);

To iterate over it setting the color do this:

var
  lbl: Tlabel;
....
for lbl in FLabels do
  lbl.Font.Color:=Color;

You appear to be using a global variable Form1. Your code will be better without that global variable, and having this procedure (and others like it) converted into a method of the form.


Prefer nullptr to NULL if you're using C++11.
<stdlib.h> and time.h are both C libraries.  Use the respective C++ libraries <cstdlib> and <ctime>.  The rest are okay.  You don't need to include <vector> in main.cpp.
Since you use a storage container for your deck, you can display it using iterators:

for (auto iter = m_deck.begin(); iter != m_deck.cend(); ++iter)
{
    std::cout << *iter << "\n";
}

If you're using C++11, use a range-based for-loop:

for (auto& iter : m_deck)
{
    std::cout << iter << "\n";
}

I don't know why you're using randomness to generate a card within the class.  The constructor should be given input to determine its rank and suit.  A card shouldn't create itself, and you wouldn't want this with an actual card game.  Remove the generate functions entirely, and instead allow the constructor to receive arguments to determine the card's value.
You also don't need to construct the deck within its constructor.  A deck can still start out empty until cards are passed to it.  That should be handled in client code, especially if someone doesn't want a 52-card deck (or a certain game uses something different).
As an alternative to using std::strings, consider enums for the ranks and suits:

// make sure the first rank is explicitly set at 1
// this will make the last rank equal 13
enum Rank { Ace=1, Two, /* ... */, Queen, King };

enum Suit { Spades, Hearts, Diamonds, Clubs };

With this, you'll no longer need the arrays nor the max constants.  Your m_rank and m_suit members should also be one of these enum type (Rank and Suit respectively).  The enums and the Card class declaration should all then be contained in a namespace.

Within your card class, you'll need functions to convert a given enum value to a char value for displaying.  You could, for instance, do this with a switch statement, which will serve as a look-up table.  This will also make it easier to maintain the ranks and suits.

std::string getRank(Rank rank)
{
    switch (rank)
    {
        case Ace: return "A";
        // ...
        default: throw std::logic_error("invalid rank");
    }
}

// same idea with suits

Also note the default statement.  If an invalid rank is passed in, an std::log_error exception will be thrown.  Regardless of what works best for error-handling, there should be a default statement here to properly handle it.
Rename Card2Str() to CardToString().  The former is just awkward wording.  It should also be lowercase as it's a function and not a type.
getOneCard() doesn't specify where in the deck the one card is drawn.  Since it takes a card from the top of the deck, just call it draw() or deal().  On the other hand, it's void and has no parameters, so it's not returning a card.  If this is supposed to just display a top card, then it's ineffective as it's still destroying the top card.

Better yet, consider having a draw() and a top() (perhaps you just need to peek at the top card).  The functionality also looks a bit unclear.  Since you're using std::vector, a storage container, make use of its member functions.  In this case, use back():

draw():

Card Deck::draw()
{
    Card cd = m_deck.back();
    m_deck.pop_back();
    return cd;
}

top():

// return by const& as this Card should only be read-only
// also make the function const as no data members are modified
Card const& Deck::top() const
{
    return m_deck.back();
}

For both of these functions, be sure the caller is first checking for an empty deck.

Side-note: You can use a different storage container if you, say, need to be able to insert into or draw from somewhere else in the deck besides the top or bottom.  For that, you can use an std::list (doubly linked list).  If you instead want to insert into or draw from the top and bottom, you can use an std::deque (double-ended queue).  Otherwise, stay with what you have.
Your deck is missing something: a shuffle function!  You could utilize std::random_shuffle from the STL to do it nicely for you:

void Deck::shuffle()
{
    std::random_shuffle(m_deck.begin(), m_deck.end());
}

You should also check for an empty deck prior to shuffling.


Project Euler Problem 35: counting circular primes below 1 million

Regarding the primes above 10. If they're prime and all of their rotations must be primes, then each digit must be in the set of 1, 3, 7 and 9. So for all 2 digits numbers,\$ 4^2 \$, for all 3 digits, \$ 4^3 \$, until 6. That's exactly 5456 numbers to check, which is very few, compared to 1 million. Now we have all the numbers possible and only those.

Also, you play with numbers with a max value of 1 million. You also only need to check if a number is prime. To do that, you only need to generate primes until 1000 and check if one of the candidates is divisible by any of those prime numbers. There are 168 primes under 1000. So you can store them in an array. It's faster than always generating the primes again and again.

This should already improve your timing by a really large factor.


Split a list into two parts with a given length

Let’s use a completely different approach: first try to solve the problem using predefined (complex) functions, then implement those functions with the primitive ones (recursion, car, cdr, etc.)

So, how could be solved your problem in Common Lisp with predefined functions? I would suggest this simple solution (note the use of values instead of list to return two different values);

CL-USER> (defun split (list count)
           (values (subseq list 0 count) (nthcdr count list)))
SPLIT
CL-USER> (split '(A B C D E F G) 3)
(A B C)
(D E F G)

In other words, copy the first count values from the list to a new list with subseq (reference), then simply return the elements of the list starting from count with nthcdr (reference).

Or, if you prefer to use a single predefined function, with the following definition we make also a copy of the second part of the list (which is not strictly necessary):

(defun split (list count)
  (values (subseq list 0 count) (subseq list count)))

Now let's assume subseq it is not predefined and try to implement my-subseq with just recursion and primitive functions:

(defun copy-to-end (l end)
  "copy the list l from beginning to the element at position end - 1"
  (if (zerop end)
      nil
      (cons (car l) (copy-to-end (cdr l) (1- end)))))

(defun my-subseq (l start &optional (end (length l)))
  "copy the list l from the element at position start to the element at position end - 1"
  (if (zerop start)
      (copy-to-end l end)
      (my-subseq (cdr l) (1- start) (1- end))))

So the final function will be:

(defun split (list count)
  (values (my-subseq list 0 count) (my-subseq list count)))

It is left as an exercise to define my-nthcdr with recursion and primitive functions to implement my first version of the function split.


It is almost never a good idea to catch all exceptions in one block.  If you are using a try block, there are probably certain types of exceptions that you are expecting.  If some exception shows up that you aren't expecting, you want to know about it.  It should be thrown -- stop the program -- let's deal with this.  Make a list of the exceptions that you want to catch.  Add them to your except line with parentheses around them and commas between them.  If you want to print the exception, add as e: to the end and put print e inside the block.  Doing print Exception means this is your output:

<type 'exceptions.Exception'>

I don't think that is what you want.

Getting key-value pairs in a dictionary is so common that Python made it easy.  You can use something like for call, response in self.searches.items(): in filter_speak().  Since you are using Python 2, it would be more memory-efficient to use .iteritems() (In Python 3, .iteritems() was removed and .items() changed to take its place.)

You seem to have a bug.  What if msg does not have the text key, does have the subtype key, but msg['subtype'] does not equal message_changed?  What if msg also has the user key and msg['user'] does not equal self.user_id?  Wheew, that takes a lot.  If all of that happens, your program will have a NameError because you never define body in that first sentence, but it is required in the second.  You need to combine the elif and the if inside it:

if msg['type'] == "message":
    if 'text' in msg:
        body = msg['text']
    elif msg.get('subtype') == "message_changed":
        body = msg['message']['text']
    else:
        ...

Your later if statements can be combined:

if msg.get('user') != self.user_id:
    ...

Ah, the wonderful advantage of dict.get().


I like blufox' solution, but remember you can replace explicit recursion by a fold, too:

explode f xs = filter (not.null) $ foldr go [[]] xs where
  go x (xs:xss) = if f x then []:xs:xss else (x:xs):xss


PHP/Apache - Production/staging consts file path

You are right, but there are better ways to do that.
One way is using dotenv. Trending way for managing configurations.

from dotenv project:

  Storing configuration in the environment is one of the tenets of a
  twelve-factor app. Anything that is likely to change between
  deployment environments – such as database credentials or credentials
  for 3rd party services – should be extracted from the code into
  environment variables.

So what you are doing is right, the way you are doing may not be best.

Since you are doing require_once(), you may want to check if file exists else it would be fatal error.

The problems I see with keeping that path in Apache:

You may need to modify apache config and restart / reload Apache for your new configurations
Not all developers in your team may have access to Apache config. If the config is in code itself, like .env, it would be easy for developers.
Debugging would be easy with .env
If you plan to unit test, mocking would be easy.


Textbased User Interface for user and program taking turns

The very first thing that jumps out at me is the indirection of maintaining both a list of possible words and a seen list. Picking a better representation for your state will make bookkeeping easier.

type Word = String
type Words = [Word]
type Moves = Map.Map Char Words

Now fill in the logically necessary functions needed to work with that state. We need to be able to construct a state blob—

makeMoves :: Words -> Moves
makeMoves = Map.fromListWith (++) . catMaybes . map tag
  where
    tag :: Word -> Maybe (Char, Words)
    tag []      = Nothing
    tag w@(c:_) = Just (c, [w])

Remove played words from one—

remove :: Word -> Moves -> Moves
remove []      = id
remove w@(c:_) = Map.adjust (delete w) c

And choose a new word from one given the constraint imposed by the last play.

move :: Char -> Moves -> IO (Maybe (Word, Moves))
move c ms =
  let possible = Map.lookup c ms
  in  case possible of
        Nothing -> return Nothing
        Just [] -> return Nothing
        Just ws -> do
          w <- pick ws
          return $ Just (w, remove w ms)

Note the separation from any logic in taking turns, or which player is currently up. Testing these operations will be much easier then (load them up in GHCi and try it out), and integrating them into our monadic game playing code should be pretty straightforward, just follow the types.

processUser :: Moves -> IO ()
processUser moves = do
    input <- getLine
    case input of
      "quit" -> return ()
      ""     -> do putStrLn "You must enter a word."
                   processUser moves
      w      -> processPC (last w) (remove w moves)

Note also how I have moved the logic for making a player move into the function where it makes sense to do so. User player code shouldn't drive computer player code, and vice versa. As an exercise, try making the necessary modifications and stylistic tweaks to processPC yourself.

You should make a best effort attempt at understanding all of the functions you write into your source. Copy and pasting pick in when you don't understand it is poor form, where'd you even find that definition? At least use a library. If you don't know what liftM is doing, just write the function out using do-notation as you would any other operation in the IO monad.

pick :: [a] -> IO a
pick xs = do
    i <- randomRIO (0, length xs - 1)
    return (xs !! i)

Spoilers—Here are the commit-level changes and final runnable code I produced while working through this.


jQuery plugin which will print to a printer an element or a jQueryUI Dialog

From a once over:

I am not a native English speaker but //Element to print HTML confused me. Maybe //HTML elements to be printed?
delete settings; is meaningless in destroy ( see comment )
elems=$(settings.elems); should be var elems = $(settings.elems); otherwise you pollute the global namespace
You declare var i twice in a for loop
You should consider removing the iframe in destroy

All in all very clean, maintainable code.


Is there a better way to loop through records and call an api?

There are two fundamental principles I would like to point out: "Don't Repeat Yourself" (DRY) and Single Responsibility. The principles should be self explanatory from their names. The very first thing I notice is that you have a "god" function. In other words, a function that is trying to do everything. This violates both of these principles. DRY because the code cannot be easily reused; Single Responsibility because functions should do just one thing. To avoid this you should separate this one function into multiple smaller ones. The best way to do this is to try and determine each individual task you are trying to accomplish and separate accordingly. I'll leave that bit up to you.

A small thing real quick before continuing. This is actually a method, not a function, and therefore the access modifier should be explicitly defined as public, private, or protected to avoid accidents. By default it resolves to the public scope, but you should not depend upon that.

public function admin_wtfTwitter() {

Internal comments are very detrimental to legibility and code size. You should avoid them except when debugging. If your code is self-documenting then most comments will become unnecessary and you will only need doccomments for the rest. Comments like "notify the log" or "get the twitter channels" should be inherently obvious from the context. If you do nothing else, removing these comments alone will dramatically increase overall legibility.

You should also avoid (un)commenting out a feature to simulate different environments. If you have a feature that you will sometimes need to activate, you should create a switch in your function's arguments to handle it. For instance:

function admin_wtfTwitter( $reportid, $jobid, $lag = FALSE ) {
    if( $lag ) {
        set_time_limit( 180000 );
    }

Though I should caution that you shouldn't override your time limit like that. First of all, it makes your server hang while it waits for the task to finish. Second, it could mask a much larger problem, such as an infinite loop. If your program is doing so much that it can't finish, then that should be a sign that there is something wrong and you should fix it, not mask it. There are a number of different methods you can use: manually limit the initial amount of work, dynamically limit it by breaking it up into chunks, and caching results to name a few. There are probably more, but those are the ones I'm familiar with. The method you chose depends upon your situation.

You should avoid single letter variables except when used in generic throw away values or incrementals. Using $c instead of $channel is rather abstract and can later lead to confusion, especially in larger chunks of code. The same can be said for non-common acronyms, in other words acronyms that are not HTML, PHP, etc...

Whitespace is your friend and PHP never minds a little over-zealousness in its use. Never cram multiple statements onto one line, even if it is legible, but especially avoid it when its not. Having more than one level of indentation wont hurt. That being said you should be aware of the arrow anti-pattern and ensure you aren't violating it.

if( $channel[ 'Reportdetail' ] [ 'small_tag' ] == NULL ) {
    $this->Reportdetail->set( array(
        'done' => -1,
        'note' => 'small_tag null'
    ) );
    $this->Reportdetail->save();
    continue;
}

Lets return to the first principle I mentioned: DRY. There are a few subtle aspects that are sometimes overlooked. Usually this principle is applied by breaking code up into functions or loops and most think that is enough. But it can also be used for something as simple as saving a reused array pointer to a variable. So, instead of continuously typing out $c['Reportdetail']['small_tag'], save that value to a variable, say $small_tag and use that instead. Later, should you decide to change the source or path, the initial value of the variable is the only line you will have to worry about.

Continuing on this line of thought, if you are setting multiple values to a resource, then the best way is to do it all at once. Not only does this follow DRY, it also saves processing time. Currently you are using $this->Reportdetail->set() method repeatedly to set multiple attributes. Always avoid accessing or manipulating resources multiple times when at all possible.

$attributes = array(
    'id' => $channel[ 'Reportdetail' ] [ 'id' ]
);

if( $small_tag == NULL ) {
    $attributes[ 'done' ] = -1;
    $attributes[ 'note' ] = 'small_tag null';

    $this->Reportdetail->set( $attributes );
    $this->Reportdetail->save();
    continue;
}

You can even go one step farther and create a "default" state. For example, if the $small_tag is NULL or bad the "done" attribute is set to "-1" and there is a "note" attribute. So if we set up our $attributes array with the null values as a default, we can manipulate or unset attributes as necessary. This sometimes even allows us to remove an if statement if done right.

$attributes = array(
    'id'   => $channel[ 'Reportdetail' ] [ 'id' ],
    'done' => -1,
    'note' => 'small_tag null'
);

$uri = "http://api.twitter.com/1/users/show.json?screen_name=$small_tag";
$data = file_get_contents( $uri );
if( $data === FALSE ) {
    if( $small_tag ) {
        $attributes[ 'note' ] = 'small_tag bad';
    }

    $this->Reportdetail->set( $attributes );
    $this->Reportdetail->save();
    continue;
}

$attributes[ 'done' ] = 1;
unset( $attributes[ 'note' ] );

There are a few things I want to point out about what I demonstrated above. The most noticeable is the new if statement structure. If we assume that file_get_contents() will return FALSE if $small_tag is NULL then we can reuse the set/save/continue for both "bad" statements, all we have to do is apply the proper "note" depending upon the value of $small_tag. There shouldn't be any noticeable difference in processing time as it should immediately fail, but you may want to check that.

Something a little less noticeable is the removal of the error suppressor @. First of all, you should never use the error suppressor. You should always explicitly check for errors and handle them. However, it isn't even necessary here. file_get_contents() only throws errors if using the maxlength or offset arguments, neither of which you are. The only "bad" return you have to worry about is a FALSE one.

Another not so obvious change is the removal of the unset( $data ); line. Micromanaging memory like this is unnecessary. The benefit is so negligible as to be nearly useless and the added clutter detracts from even that small appeal. The only reason to unset a value is if you may end up using it later and don't want it to have a value first. If you are in a loop and the next iteration of that loop automatically overwrites the previous values, then unsetting is unnecessary. This includes unsetting $uri and $content.

The final thing I wanted to point out is that you are recreating a boolean by using numerical TRUE/FALSE values with your "done" attribute. The difference between using an actual boolean and a pseudo-boolean is small but the abstractness can cause confusion. You should just use a real boolean unless absolutely necessary.

The rest is more of the same. There's only one last thing I noticed, and it goes along with what I said about the arrow anti-pattern earlier: Watch for unnecessary indentation. If you can reverse an if statement to reduce the amount of indented code then do so. For example:

foreach( $content as $t ) {
    if( empty( $t[ 'id_str' ] ) ) {
        continue;
    }

    //etc...
}

Hope this helps


Counting subsets with sum not exceeding some limit

The problem is actually with your algorithm, not with your C++ code. The time complexity of your solution is \$O(2^n \times \text{polynomial}(n))\$, which is too much for the given constraints.

You can use the meet-in-the-middle technique to make it \$O(2^{(n/2)} \times \text{polynomial}(n))\$, which is good enough.

The idea is as follows:

Let's split the array into two even parts (almost even if n is odd).
Let's generate all sums in the first in and in the second part and store them in vectors as and bs. This part requires \$O(2^{(n/2)})\$.
Now the problem is simpler: given two vectors A and B, compute the number of pairs of valid indices i and j such that as[i] + bs[j] <= S for a given value of S.
Let's sort bs and iterate over as. As bs is increasing, all valid elements of bs for a given element a from as are in some prefix of B. We can find its size as std::upper_bound(bs.begin(), bs.end(), a) - bs.begin()
That is, this part of this solution looks like:

for (const auto& a : as) {
    result += std::upper_bound(bs.begin(), bs.end(), a) - bs.begin();
}

The total time complexity is \$O(2^{(n/2)} \times \log(2^{(n/2)}) = O(2^{(n/2)} \times n)\$.


Refactoring while-do into tail recursion with F#

I think that learning functional programming should be about making your code more readable (and also better in other aspects), neither of your samples seems very readable to me.

I also think that when working with collections in functional programming, the most important concept is not recursion, it's higher-order functions.

If you use those in the form of a query expression, your code could look like this:

query {
    for row in 0..searchHeight do
    for col in 0..searchWidth do
    let pixel = largeArray.[row].[col]
    where (pixel = firstSmallPixel)
    select (row, col, pixel)
    head
}

The nice thing about this code is not only that it's more readable and shorter, it's that it emphasizes what you want to do, not how to do it.


Counting weather events for visualization using Gnuplot

I see a number of things that may help you improve your program.

Use the required #includes

The code uses std::map which means that it should #include <map>.  It was not difficult to infer, but it helps reviewers if the code is complete.  I believe that the full set of required includes is:

#include <string>
#include <iostream>
#include <fstream>
#include <map>

Use const where practical

The current getWeather() routine does not (and should not) modify the passed city string, and so it should be declared const:

void getWeather(std::map<std::string, int>& weather, std::ifstream& fin,
        const std::string& city){

For the outPut routine, both city and weather should be const.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Let the computer do the counting

The main() routine contains this:

std::string city[36] = {"TEXAS",
                        "OREGON",
                        // ... presumably 33 other states
                        "MISSOURI"};
for(int i=0;i<36;i++){

What would make more sense is to omit the 36 and simply iterate directly over the strings, using a "range for" since you're using C++11.  It's a bit peculiar to have 36 states since the United States hasn't had 36 states since 1867, when Nebraska became the 37th state, and even more peculiar that such an array is named city!  I'd write it like this:

std::string states[] = {"TEXAS",
                        "OREGON",
                        // .. maybe 47 other states?
                        "MISSOURI"};
for(const auto &state : states) {

Don't use eof for the loop condition

The code currently contains these lines:

while(!fin.eof()){
    getline(fin, line);

However, that's almost never what you really want.  Instead, write this:

while (std::getline(fin, line)) {

This is not only shorter and more direct, but it actually functions in the way you'd want and expect.

Avoid repeating code

In the getWeather() routine, we have a long list of if statements that looks like this:

if(line.find("Drought") != std::string::npos){
    weather["Drought"]++;
}else if(line.find("Flood") != std::string::npos){
    weather["Flood"]++;

This approach has a few problems.  First, it's needlessly repetitive since it repeats the event type twice in each pair of lines.  Second, it is subject to miscounting because it assumes that, for example, the word "Flood" appearing in the line always means that the event type was "Flood".  Assuming you're using this NOAA data, then it's easy to find a counterexample.  For instance, if you look at the 2014 data, there was an event on 3 August 2014 for which the event code is "Thunderstorm Wind" but the description contains the word "Flood".  This leads to my next suggestion.

Parse the file

An alternative to searching the entirety of each line would be to parse the lines, since it's a CSV file.  There are a number of ways to do so, and a number of third-party libraries for that, but I'd be inclined to use the regex part of the standard library.  In particular, this can be done with a std::regex_token_iterator.

Think carefully about data structures

Right now the code uses a std::map but since maintaining any particular ordering appears to be unimportant for this code, it would likely confer a performance benefit to use a std::unordered_map instead.

Rethink the algorithm

Right now, each input file is scanned once for every state and files are opened and closed with every iteration through the inner loop.  Wouldn't it make more sense just to make a single pass through each input file?  Further, each state's output is probably small enough that all of the data could be generated in memory and then written out when everything is parsed.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.

Results

Here' how I reworked the code to implement all of these suggestions:

#include <string>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <map>
#include <regex>

using StateWeather = std::unordered_map<std::string, std::unordered_map<int, std::map<std::string,int>>>;

std::istream &getWeather (std::istream &in, StateWeather &wx, int year) {
    static const std::regex re{R"x(("([^"]*)"|[^,]*),|$)x"};
    static const std::sregex_token_iterator regend{};
    static constexpr unsigned stateFieldNum{8};
    static constexpr unsigned typeFieldNum{12};
    static constexpr auto maxField{std::max({stateFieldNum, typeFieldNum})};
    std::string line;
    if (std::getline(in, line)) {
        auto it = std::sregex_token_iterator(line.begin(), line.end(), re, 2);
        std::string state;
        std::string type;
        for (unsigned i=0; i <= maxField && it != regend; ++it, ++i) {
            switch (i) {
                case stateFieldNum:
                    state = *it;
                    break;
                case typeFieldNum:
                    type = *it;
                    ++wx[state][year][type];
                    break;
                default:
                    // do nothing
                    ;
            }
        }
    }
    return in;
}

int main()
{
    static constexpr int startyear{1996};
    static constexpr int endyear{2013};
    StateWeather wx{};
    for (auto year = startyear; year <= endyear; ++year) {
        std::ifstream in{"stormdata_"+std::to_string(year)+".csv"};
        while (getWeather(in, wx, year)) {
        }
    }
    for (auto &statedata : wx) {
        std::ofstream out{statedata.first};
        for (auto year = startyear; year <= endyear; ++year) {
            out << statedata.first << '-' << year << '\n';
            auto &events = statedata.second[year];
            for (const auto &event : events) {
                out << event.first << '\t' << event.second << '\n';
            }
            out << '\n';
        }
    }
}

This code runs on the full data set, generating one file per "state" (the data contains "state" designations such as "GUAM" which is a territory, not a state, and "LAKE ERIE" which is a body of water) in 4.4 seconds on my 64-bit Linux machine.  I used gcc version 6.3.1 and -O2 optimization.


This really isn't bad, in terms of base Python. The only thing that stands out to me is this:

first_row = [row for row in reader(open('genre_scores.csv', 'r'))][0]

Firstly, you aren't closing the file. Always close the file after you're done.

'r' is implicit, so you don't need to write it in the arguments to open.

Also, you're building up an entire list in memory from the CSV file, and then throwing it all away only to use the first row. Instead, you should use something like:

with open('genre_scores.csv') as f:
    csv_reader = reader(f)
    first_row = next(csv_reader)

You also ask:

  I'd like to implement something that makes sure that lst isn't longer than three elements (since four dimensional plots aren't really a thing). The only way I know to do this is assert len(lst) <=3, which gets the job done but it would be nice if it also could raise a useful error message.

Fairly straightforward, and I'll also assume that the minimum is 2:

if not (2 <= len(lst) <= 3):
    raise ValueError(f'Invalid lst length of {len(lst)}')


Numbers of length N and value less than K

Optimise memory usage

You could optimise memory usage by not converting your iterators into list and by avoiding non-required steps (like join).

Changing a few others details (formatting, adding tests, etc), you'd get something like:

from itertools import product
from itertools import ifilter

def solve(A, B, C):
    c_len = len(str(C))
    if A == [] or B > c_len:
        return 0
    elif B < c_len:
        # Constraint is B
        if B == 1:
            return len(A)
        else:
            candidates = product((str(i) for i in A), repeat = B)
            return sum(x[0] != '0' for x in candidates)
    else:
        assert B == c_len
        # Constraint is C
        if B == 1:
            return sum(i < C for i in A)
        else:
            candidates = product((str(i) for i in A), repeat = B)
            return sum(x[0] != '0' and int(''.join(x)) < C for x in candidates)

assert solve([2],5,51345) == 1
assert solve([],1,1) == 0
assert solve([2, 3, 5, 6, 7, 9],4,42950) == 1296
assert solve([2, 3, 5, 6, 7, 9],5,42950) == 2592
assert solve([0],1,5) == 1
assert solve([0,1,2,5],1,123) == 4
assert solve([0,1,5],1,2) == 2
assert solve([3],5, 26110) == 0
assert solve([0,1,2,5],2,21) == 5

Another algorithm

I'm pretty sure the whole thing can be optimised further by not generating the various numbers to count them but just using mathematical tricks to get the solution with no counting.

The easiest case to handle is B < c_len:

elif B < c_len:
    # All combinations of B elements are valid
    return len(set(A)) ** B

Actually, as mentionned by Maarten Fabré, this does not handle 0s perfectly. The code below is updated to handle it better.

The last case is trickier. We can try to use recursion to solve smaller versions of the problem. I didn't manage to make this work properly...

from itertools import product, ifilter, dropwhile, product, takewhile
import timeit

def solve_naive(A, B, C):
    A = set(str(A))
    mini = 10 ** (B-1)
    maxi = min(10 * mini, C)
    cand = [str(i) for i in (['0'] if B == 1 else []) + range(mini, maxi)]
    valid = [i for i in cand if all(c in A for c in i)]
    return len(valid)

def solve_op(A, B, C):
    # print(A, B, C)
    c_len = len(str(C))
    if A == [] or B > c_len:
        return 0
    elif B < c_len:
        # Constraint is B
        if B == 1:
            return len(A)
        else:
            candidates = product((str(i) for i in A), repeat = B)
            return sum(x[0] != '0' for x in candidates)
    else:
        assert B == c_len
        # Constraint is C
        if B == 1:
            return sum(i < C for i in A)
        else:
            candidates = product((str(i) for i in A), repeat = B)
            return sum(x[0] != '0' and int(''.join(x)) < C for x in candidates)

def solve_maarten(A, B, C):
    if A == [] or B > len(str(C)):
        return 0
    c_tuple = tuple(map(int, str(C)))
    combinations = product(A, repeat=B)
    if B != 1:
        combinations = dropwhile(lambda x: x[0] == 0, combinations)
    if B == len(c_tuple):
        combinations = takewhile(lambda x: x < c_tuple, combinations)
    combinations = list(combinations)
    return sum(1 for _ in combinations)

def solve(A, B, C):
    c_str = str(C)
    c_len = len(c_str)
    if A == [] or B > c_len:
        return 0
    if B < c_len:
        a_len = len(set(A))
        if B == 1:
            return a_len
        non_0_len = a_len - (0 in A)
        return non_0_len * (a_len ** (B-1))
    assert B == c_len    # Constraint is C
    head, tail = int(c_str[0]), c_str[1:]
    nb_first_dig_cand = sum(i < head for i in A)
    if not tail or not nb_first_dig_cand:
        return nb_first_dig_cand
    if head in A:  # TODO: This case is not handled properly...
        # It should involve ret and solve(A, B-1, int(tail)) or something like that
        return solve_maarten(A, B, C)
    solve_c = solve(A, B-1, C)
    ret = nb_first_dig_cand * solve_c
    return ret

tests = [
    ([2], 4, 51345, 1),
    ([2], 5, 51345, 1),
    ([], 1, 1, 0),
    ([2, 3, 5, 6, 7, 9], 4, 42950, 1296),
    ([2, 3, 5, 6, 7, 9], 5, 42950, 2592),
    ([0], 1, 5, 1),
    ([0, 1, 2, 5], 1, 123, 4),
    ([0, 1, 5], 1, 2, 2),
    ([3], 5, 26110, 0),
    ([0, 1, 2, 5], 1, 21, 4),
    ([0, 1, 2, 5], 2, 21, 5),
    ([0, 1, 2, 5], 2, 201, 12),
    ([0, 1, 2, 5], 3, 2010, 48),
    ([0, 1, 2, 5], 4, 20108, 192),
    ([0, 1, 2, 5], 5, 201089, 768),
    ([0, 1, 2, 3, 4, 5, 7, 8], 5, 201089, 28672),
    ([0, 1, 2, 3, 4, 5, 7, 8], 6, 201089, 33344),
    ([0, 1, 2, 3, 4, 5, 7, 8, 9], 6, 200000, 59049),
    ([0, 1, 2, 3, 4, 5, 7, 8, 9], 6, 999999, 472391),
    ([1, 2, 3, 4, 5, 7, 8, 9], 6, 200000, 32768),
    ([1, 2, 3, 4, 5, 7, 8, 9], 6, 999999, 262143),
]
funcs = [solve, solve_op, solve_maarten, solve_naive]

for func in funcs:
    start = timeit.default_timer()
    for (A, B, C, exp) in tests:
        ret = func(A, B, C)
        if ret != exp:
            print "%s(%s, %d, %d): ret=%d, exp:%d" % (func.__name__, str(A), B, C, ret, exp)
    end = timeit.default_timer()
    print("Time for %s: %f" % (func.__name__, end - start))

def solve2(A, B, C):
    c_str = str(C)
    c_len = len(c_str)
    if A == [] or B > c_len:
        return 0
    if B < c_len:
        a_len = len(set(A))
        if B == 1:
            return a_len
        non_0_len = a_len - (0 in A)
        return non_0_len * (a_len ** (B-1))
    assert B == c_len    # Constraint is C
    head, last_dig = divmod(C, 10)
    nb_last_dig_cand = sum(i < last_dig for i in A)
    if head == 0:
        return nb_last_dig_cand
    ret = solve_naive(A, B-1, head - 1) * len(A)
    ret_dummy = solve_naive(A, B, C)
    print(ret - ret_dummy, A, B, C)
    return ret_dummy


I don't know much about C#, so this answer will focus solely on generic stuff. Performance problems in image processing applications usually happen inside loops over all pixels. I'm focusing on this section of the code:

for (int x = 0; x < tempImg.Width; x++)
{
    for (int y = 0; y < tempImg.Height; y++)
    {
        double distence = GetDistance(absPos.X, absPos.Y, x, y); //Distence from pixel to cursor
        int pixelIndex = x * 4 + y * imgRawData.Stride;

            for (int i = 0; i < 3; i++)
            {
                if (distence > rgbValues[pixelIndex + i])
                {
                    rgbValues[pixelIndex + i] = 0; //Sets pixel to black
                }
                else
                {
                    rgbValues[pixelIndex + i] -= (byte)distence; //Reduce pixel brightness
                }
            }
    }
}

You loop over all pixels, but only do something for those pixels close to absPos. The maximum distance over which your filter will have effect is 255, assuming that rgbValues is an 8-bit unsigned integer. Outside of that range, you always set pixels to 0.
Thus, you can loop over only those pixels within that range: x goes from max(absPos.X - 255, 0) to min(absPos.X + 255, tempImg.Width - 1), and similarly for the y-coordinate (maybe this is Math.Max and Math.Min in C#?). Outside of that range simply fill with zeros.

Next, GetDistance computes the square root, which is quite expensive. It is a lot cheaper to compute the square of a value. We also know that if a < b, then a*a < b*b. So instead write a function GetSquareDistance, which returns Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2), and compare the square distance to the square of the pixel's value. By not computing the square root, all operations can be done as integers, which might or might not be faster.

This function GetSquareDistance can actually be further improved by computing Math.Pow((y2 - y1), 2) once outside the loop over x, then adding only the square of the x-difference inside the loop.

Finally, the innermost if statement also duplicates work. I presume that a good optimizing compiler will correct this, but in principle distence > rgbValues[pixelIndex + i] computes the difference and compares to 0, then inside the loop you again compute the same difference. Using a max function would improve this conditional statement:

int diff = (int)rgbValues[pixelIndex + i] - (int)distence;
rgbValues[pixelIndex + i] = (byte)max(diff, 0); // again, maybe Math.Max?

(using int in case integer subtraction is faster than floating-point subtraction.)

Another issue I've just noticed: You loop over y in the inner loop, and over x in the outer loop. If you reverse these two loops, then the array will be accessed in storage order (pixelIndex = x * 4 + y * imgRawData.Stride will increase monotonically). With this access pattern, the cache will be used optimally, and the code should be quite a bit faster.

The code would look like this (not tested, sorry for any typo):

int firstX = max(absPos.X - 255, 0); // max and min could be Math.Max and Math.Min?
int lastX = min(absPos.X + 255, tempImg.Width - 1) + 1;
int firstY = max(absPos.Y - 255, 0);
int lastY = min(absPos.Y + 255, tempImg.Height - 1) + 1;
int pixelIndex = 0;
for (int y = 0; y < firstY; y++)
{
    SetRowToZero(rgbValues + pixelIndex, tempImg.Width); // This function iterates over a line of the image and sets it to 0
    pixelIndex += imgRawData.Stride;
}
for (int y = firstY; y < lastY; y++)
{
    int yDistance2 = absPos.Y - y;
    yDistance2 = yDistance2 * yDistance2;

    SetRowToZero(rgbValues + pixelIndex, firstX); // Here the function sets the first set of pixels in the line to 0

    int index = pixelIndex + firstX * 4;
    for (int x = firstX; x < lastX; x++)
    {
        int xDistance2 = absPos.X - x;
        xDistance2 = xDistance2 * xDistance2;
        int distance2 = xDistance2 + yDistance2;
        for (int i = 0; i < 3; i++)
        {
            int value2 = rgbValues[index + i];
            value2 = value2 * value2 - distance2;
            if (value2 <= 0)
            {
                rgbValues[index + i] = 0; // Sets pixel to black
            }
            else
            {
                rgbValues[index + i] = (byte)Math.Sqrt(value2); // Reduce pixel brightness
            }
        }
        index += 4;
    }

    SetRowToZero(rgbValues + index, tempImg.Width - lastX); // Here the function sets the last set of pixels in the line to 0

    pixelIndex += imgRawData.Stride;
}
for (int y = lastY; y < tempImg.Height; y++)
{
    SetRowToZero(rgbValues + pixelIndex, tempImg.Width);
    pixelIndex += imgRawData.Stride;
}

Additional comments:

Typo: "distence" should be "distance"
Don't leave commented-out code in your source files. They tend to be confusing. If you do, at least add a clear bit of comment text to indicate why the code is commented out.


Before thinking I didn't read well, I didn't want to rewrite everything: the final edit is at the bottom of the answer, but please read everything to understand it all. :)

If the code inside the CheckedChanged events for all the checkboxes is exactly the same, you should extract that code and place it in a method. Then, call this method from the events:

private void ProcessInput(CheckBox cb)
{
    if (cb.Checked)
    {
        var input = new frmInputBox();

        if (input.ShowDialog() == DialogResult.OK)
        {
            hash.Add("5", input.txtInput.Text);
            problems = problems + "5. Check Auger Motor: " + input.txtInput.Text + Environment.NewLine;
            this.txtProblems2.Text = problems;
            txtProblems2.Visible = true;
        }

        if (input != null)
        {
            input.Dispose();
        }
    }
}

//Example usage:
private void checkBox45_CheckedChanged(object sender, EventArgs e)
{
    ProcessInput(checkBox45);
}

private void checkBox1000_CheckedChanged(object sender, EventArgs e)
{
    ProcessInput(checkBox1000);
}

Another way of achieving the same is creating one event and assign this event to the CheckedChanged event of any checkbox that requires this:

private void AnyCheckBoxChanged(object sender, EventArgs e)
{
    var cb = (CheckBox)sender;

    if (cb.Checked)
    {
        var input = new frmInputBox();

        if (input.ShowDialog() == DialogResult.OK)
        {
            hash.Add("5", input.txtInput.Text);
            problems = problems + "5. Check Auger Motor: " + input.txtInput.Text + Environment.NewLine;
            this.txtProblems2.Text = problems;
            txtProblems2.Visible = true;
        }

        if (input != null)
        {
            input.Dispose();
        }
    }
}

//Assigning the events:
checkBox45_CheckedChanged += AnyCheckBoxChanged;
checkBox1000_CheckedChanged += AnyCheckBoxChanged;

Other notes:

The var keyword:

From the C# Programming Guide:

  The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code.

So lines like:

frmInputBox input = new frmInputBox();

would become:

var input = new frmInputBox();

Naming conventions:

Please follow the Capitalization Conventions for class names. The name of the class frmInputBox would become FormInputBox for example.

String manipulation:

This is about this line:

problems = problems + "5. Check Auger Motor: " + input.txtInput.Text + Environment.NewLine;

Concatenating literal strings with variables should be done using the String.Format method:

var result = String.Format("5. Check Auger Motor: {0}", input.txtInput.Text);

If this were in a loop and building large string, you'd be wasting memory. Use a StringBuilder instead (which has a method to append a string using a format, cfr. previous point):

var builder = new StringBuilder();
builder.AppendFormat("5. Check Auger Motor: {0}", input.txtInput.Text);
var result = builder.ToString();

Disposing of the form:

Since an instance of Form is disposable, I suggest using the using statement. No need to check whether or not it can be disposed or not, at the end of the statement it's automatically disposed:

using (var input = new FormInputBox())
{
    if (input.ShowDialog() == DialogResult.OK)
    {
        hash.Add("5", input.txtInput.Text);
        problems += String.Format("5. Check Auger Motor: {0}{1}", input.txtInput.Text, Environment.NewLine);
        txtProblems2.Text = problems;
        txtProblems2.Visible = true;
    }
}

Edit:

Since the code is not exactly the same, use the first way of solving the problem: by extracting the code into a separate method. Following code implements this:

private void ProcessInput(string hashKey, string problem, TextBox tb)
{
    using (var input = new frmInputBox())
    {
        if (input.ShowDialog() == DialogResult.OK)
        {
            hash.Add(hashKey, input.txtInput.Text);
            problems += String.Format({0}: {1}{2}", problem input.txtInput.Text, Environment.NewLine);
            tb.Text = problems;
            tb.Visible = true;
        }
    }
}

//Calling of the method:
private void checkBox45_CheckedChanged(object sender, EventArgs e)
{
    if(checkBox45.Checked)
        ProcessInput("5", "5. Check Auger Motor", txtProblems2);
}

private void checkBox47_CheckedChanged(object sender, EventArgs e)
{
    if(checkBox47.Checked)
        ProcessInput("26", "24. Service Access", txtProblems5);
}

Edit2:

I re-read your updated code and noticed you set the text of a different textbox too, this is now implemented in my code example above.


don't use using namespace std

You should not use using namespace std because it eliminates some important information, which may lead to some conflicts with your classes or classes of other libraries. It is not uncommon to have a vector class, which has a totally other meaning than the std::vector. And to be honest, it isn't that much more work, to type std:: in front of the classes/functions, is it?

use std algorithms

You do everything with for loops, which is bloated and error prone. Use the algorithms of the std namespace instead. I provide you with a short an clean example, how you could do the above task (and more) with less lines.

your algorithm itself

You should think about logical improvements. Is it necessary to store every score in a vector, when equal scores produce the same rankings, and the following scores just increments by one? Therefore I took the std::unique algorithm, which returns a forward iterator. std::unique doesn't erase anything itself. It just moves duplicates to the end of the range (our std::vector); you have to erase them manually.
But, before you can use std::unique you have to order your elements. I don't know if it's guaranteed to get the score input in a descending order; thus I simply use std::sort to ensure this.
After that, it's a simple std::lower_bound (which is a binary search instead a linear search) to get the first iterator to an element, which is not less than the provided score (ok, I had to pass an other function object, because we want to check for greater and not for less).
Iterators starts with a zero index. This means, we have to add 1 to our index, to get the official ranking.
Easy, huh?

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

int main()
{
    std::vector<int> scores { 100, 100, 50, 40, 40, 20, 10 };
    std::vector<int> aliceScores { 5, 25, 50, 120 };
    // sort and erase duplicates
    std::sort(std::begin(scores), std::end(scores), std::greater<int>());
    scores.erase(std::unique(std::begin(scores), std::end(scores)), std::end(scores));

    // just a lambda to make the output part more readable
    auto locateRanking = [](const auto& _scores, int _newScore){
        auto itr = std::lower_bound(std::begin(_scores), std::end(_scores), _newScore, std::greater<int>());
        return std::distance(std::begin(_scores), itr) + 1;
    };

    // output part
    for (auto newScore : aliceScores)
    {
        std::cout << locateRanking(scores, newScore) << std::endl;
    }
}

tl;dr

Sort the vector, remove the duplicates and use a binary search instead of your linear approach and you will discover a huge performance benefit.


Grabbing hashed password from a database

Regarding your questions, yes, that looks fine to me.

XSS

When echoing user input - or really any variable data - you need to protect against XSS attacks. Otherwise, attackers can inject JavaScript code, which will then be executed in the context of the browser of the victim, leading to bypass of CSRF protection, cookie stealing, phishing, or injection of JavaScript keyloggers.

Specifically, these statements are vulnerable:

echo 'Invalid password for the username: ' . $user;
echo 'The username, ' . $user . ', does not exist! Please try again.';

You can defend against XSS by using htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); when echoing data.

Nesting

Personally, I don't like these kinds of nested ifs. It's hard to see which if clause the different else statements close. With just two, it's still manageable, but when the code is extended, it will become very difficult to read.

A different structure might look like this:

if($numberofrows <= 0) {
    // return false or echo and die
}

if (!password_verify($password, $hashedPassword)) {
    // return false or echo and die
}

// return true, or start session, redirect

Now, it's a lot clearer which error message results from which check.

Misc

it's good practice to regenerate the session id when the state of the session changes to prevent session fixation (not an issue with default php.ini, but with some settings it is an issue). Use session_regenerate_id(true); for this.
using relative URLs in the Location header violates current standards, so if you can, use absolute URLs.
your comments don't really add any clarity to the code, so I would just remove them.
in PHP, it is generally standard to put curly brackets of if/else statements on the same line.
do you really need the call to store_result? It doesn't seem necessary to me.
your spacing is not internally consistent (eg $stmt2 -> close(), if().
I would either use print or echo, but not both for the same task.
as a security precaution, you should always die after a redirect as clients do not have to follow it, and thus code below the redirect can be executed as well. In this case, it doesn't matter because the redirect is for a successful login, but it's good practice.


This answer may come across as harsh, but it is not supposed to be.
Your code looks good, BUT it lacks any comments so it’s quite difficult for other people to understand what it’s purpose is.  I have no doubt that today you know what your code does, but if you are working in a professional capacity in three months time when you have written another several thousand lines you won’t remember.
You have used base classes, but we can’t see them, this means we have even less understanding of the code.
Your coding styles are nice and clean, but you need to decide which one to use for instance you’ve got camel case and underscores in variable names.
It’s possible that things are being done in the base classes that I can’t see, but you seem to be dereferencing pointers without verifying they are not null.  See *pData, which isn’t initialised.
And a really minor thing length could be a const variable.
You say you want to optimise the code.  What problems are there with it?  Have you benchmarked it’s current performance, where is most of the time spent?


The code makes good use of parameters.  However, I see a potential problem.
    if (0 == (DATA_WIDTH % 4)) begin

That code seems to imply that any multiple of 4 is supported.  But, if I try DATA_WIDTH = 20, then I see z values in the output.  Perhaps you should restrict values to be a multiple of 8 instead:
    if (0 == (DATA_WIDTH % 8)) begin

Conventionally, the word "check" means that you will compare an actual value to an expected value and report an error if the two do not match.  The check_swap task simply displays the values.  If that is all you are looking to do, then I suggest renaming the task as display_swap or monitor_swap.
However, you could add code to the testbench to do a comparison.  If your tool suite supports SystemVerilog features, then the following additions/modifications would provide automatic checking:
wire [DATA_WIDTH - 1 : 0] data_o;
generate
    if (0 == (DATA_WIDTH % 8)) begin
        assign data_o = {<< 8{counter_dir_value}};
    end else begin
        assign data_o = '0;
    end
endgenerate

task check_swap;
    repeat(ITERATION_NUMBER) begin
        @(posedge clk);
        $display("A direction value:  %h -> the swap value: %h", counter_dir_value, counter_swap_value, $time);
        if (data_o !== counter_swap_value) begin
            $display("ERROR: data miscompare", $time);
        end
    end
endtask

To create the expected data (data_o), I copied the generate code from the design and made some simplifications.  The {<< 8{counter_dir_value}} syntax is another way to perform the byte swap.  Refer to IEEE Std 1800-2017, section 11.4.14 Streaming operators (pack/unpack).  The '0 syntax is a simplified way of assigning all bits to 0, equivalent to what you have already.  If you plan to synthesize the design, and your tool chain supports this syntax, you could even use this code in your design module.
A minor note: with that type of task body, the begin/end keywords are now optional.


How can I clean up (DRY) this verbose jQuery code?

Factor out detailed code into subfunctions

One relatively mechanical thing you could do is transform all of the commented blocks into functions. For a small section, something like this

  // Kill all audio
  $('audio').each(function(){ this.pause(); this.currentTime = 0; });

  // Turn this switch off
  $('.switch01').removeClass('activated');

  // Kill all info cards showing the playback controls
  $('.audio-info-card').addClass('d-none');

becomes

  killAllAudio();
  turnSwitchOff( '.switch01' );
  killAllInfoCards();

  //...

function killAllAudio(){
  $('audio').each(function(){ this.pause(); this.currentTime = 0; });
}

function turnSwitchOff( switch ){
  $(switch).removeClass('activated');
}

// Kill all info cards showing the playback controls
function killAllInfoCards(){
  $('.audio-info-card').addClass('d-none');
}

After this, your top-level algorithm should be much clearer. At the top level it should almost look like pseudocode, except the comments are all calls to subfunctions which do one small named task.

Factoring out code into subfunctions also helps you see "more code" by abstracting away small details. With shorter functions, you can see more of them on the screen at once.


ASP.net Identity admin reset user password

One thing you should keep in mind is that when the Add fails, your user is left without a password as it's already been removed. When will this fail? Usually when your password does not pass the validation.

Of course, seeing how an admin is doing it, there's probably not so much of a problem as they can simply add a different one - as long as the message is clear enough to show there actually is a problem with adding the new password.

The way Microsoft wants you to tackle this is by using a PasswordResetToken.

var code = await _userManager.GeneratePasswordResetTokenAsync(user);
await _userManager.ResetPasswordAsync(user, code, newPassword);

For this you'll have to fiddle around a bit with the token generators that Identity provides.


One aside to mention: you should split your UI and business logic code.  For the sake of tossing it into a working example quickly (I'm doing this over lunch), I removed all the UI code and replaced any print-outs with Console.WriteLine calls.

I also did a little refactoring to split method calls.

Additionally, I renamed RecursiveSearch to RecursiveSearch2 so I could run it side-by-side with the original.

Finally, I made some of the non-static method static, but only to speed up running the project.  Pay no mind to these changes.

  public static void RecursiveSearch2 (string path)
  {
     try
     {
        RecursiveSearch2 (new DirectoryInfo (path));
     }
     catch (Exception ex)
     {
        Console.WriteLine (ex.Message);
     }
  }

Since I switched to use DirectoryInfo, I went ahead and made two overloads of the RecursiveSearch method.  One takes in the string for the initial search, but sub-directories can call the overload which takes in DirectoryInfo directly.  The first allows you to make the change without breaking your interface, while the second is more useful during processing work.

For speed, I pushed the try/catch up here and left out exception handling elsewhere, though you may want to add some at the lower level methods, if only to provide more descriptive logging/exception messages.

  public static void RecursiveSearch2 (DirectoryInfo dir)
  {
     foreach (var item in dir.GetFileSystemInfos ())
     {
        if (item is FileInfo)
           PrintFileInfo (item as FileInfo);
        else if (item is DirectoryInfo)
           RecursiveSearch2 (item as DirectoryInfo);
     }
  }

If you call the DirectoryInfo.GetFileSystemInfos method, it returns all directories and files in one call.  The upside is that it reduces the calls to the filesystem, which are generally going to be your bottleneck.  The downside is that you get a base type back, so some type handling may be necessary.

  private static void PrintFileInfo (FileInfo fi)
  {
     long FileLength = fi.Length;
     long FileLengthOnHarddisc = GetFileSizeOnDisk (fi.FullName, fi);

     if ((FileLength == FileLengthOnHarddisc && FileLength == 4096) || FileLength >= FileLengthOnHarddisc)
     {
        Console.WriteLine (fi.FullName + " - Größe - " + FileLength.ToString () + " - Größe auf Datenträger - " + FileLengthOnHarddisc.ToString ());
     }
  }

We are then left with handling the actual file, which I split off into a different method.  The only notable differences is that I changed the input to be a FileInfo type rather than string, since I already have the FileInfo object from the calling method's loop.

Running your method versus the modified version on my c:\downloads folder cut the time consistently between 1/4 to 1/2 the time of the original, though my sample size is far too small to be conclusive.  I would advise benchmarking it yourself, though.  It is possible that the performance characteristics change wildly based upon the folder structure, depth, and ratio of directories to files.


You are using many indexes in your code.

That is, you are using an imperative style of programming.

Functional style is more about decomposing the problem in smaller even tiny steps and using recursion where reasonable.

To print out as a spiral the outermost part of a matrix what do you do?

1    2   3   4
5    6   7   8
9   10  11  12
13  14  15  16

Output should be -

1 2 3 4     8 12 16
^           ^
First row   Last column reversed but avoiding repeating 4

15 14 13
^
Last row reversed (again careful on repetions)

9 5
^
First column reversed omitting both first and last

And then? How to print the inside as a spiral? You just remove the outside, the first and last columns and the first and last items of each row and apply this process again.

This allows you to think, as much as possible in terms in concepts (print given row or column maybe reversed) instead of indexes, you find a way to simplify the problem and then establish a trivial base case (matrix empty = do not print)

So you can a program like this, in pseudocode:

def nth_row
def nth_column
def except_first
def except_last
def reversed

def spiral_print(matrix):
    if len(matrix) == 0: end
    L = len(matrix)
    print(nth_row(0, matrix))
    print(except_first(nth_column(L, matrix)))
    # last row and first column handling missing
    print_spiral(inside_matrix(matrix))

I do not know Scala specifics semantics, but here is an implementation in Python:

def column(i, matrix):
    return [row[i] for row in matrix]

def spiral(matrix):
    if len(matrix) == 0:
        return
    print(matrix[0])
    print(column(-1, matrix)[1:])
    print(matrix[-1][::-1][1:])
    print(column(0, matrix)[::-1][1:-1])
    spiral([row[1:-1] for row in matrix[1:-1]])

[::-1] means "reversed", and [1:-1] means "except first and last"


Issue a redirect, trying several string replacements for the domain

Went for this:

var arr = new[] { "http://www.", "http://blog.", "http://forum.", "http://tracker.", "http://wiki.", "http://" };
var to = "http://forum.";

foreach (var from in arr)
{
    if (RedirectPermanent(from, to))
        break;
}


Remake of factoring/prime factorization calculator

Factors::calculate() can be sped up by:

performing two integer adds after each iteration to determine loop termination

std::sqrt()'s overhead, calculations, and casting can be slow
for-loops shouldn't increment towards a floating-point value
incrementing towards an integer value is faster and proper
adding is generally fast and can be done in place of multiplication

starting the loop counter at 2 or 3 (if integer is even or odd respectively)

fewer increments means fewer division operations (division is slow)

This integer add method replaces multiplication as such:

0*0 = 0
1*1 = 1 = 0 + 1
2*2 = 4 = 1 + 3
3*3 = 9 = 4 + 5
4*4 = 16 = 9 + 7
// etc.

Revised function with explanations:

Factors::FactorsList Factors::calculate() const
{
    FactorsList factors;
    std::uint64_t incr = 0;    // will increment by 2 each iteration
    std::uint64_t incrSum = 1; // will accumulate value of 'incr' each iteration

    // if integer is even, i starts at 2
    // if integer is odd, i starts at 3
    std::uint64_t i = (integer % 2 == 0) ? 2 : 3;

    // 'i' is only incremented by 1 for checking each number
    // value of 'incrSum' will determine loop termination
    for (; incrSum <= integer; ++i)
    {
        if (integer % i == 0)
        {
            factors[i] = integer / i;
        }

        incr += 2;
        incrSum += incr;
    }

    return factors;
}


What is the "proper" way to write this in Java?

One alternative, although I don't know if you think it's too complex, would be to apply a visitor pattern:

private interface Command {
    String apply(ItemServiceFacade facade) throws RemoteException, CoreException;
}

public String deleteItem(final Integer itemId, final String username, final String kpNumber) {
    return execute(new Command() {
        @Override
        public String apply(ItemServiceFacade facade) throws RemoteException, CoreException {
            return facade.deleteItem(itemId, username, kpNumber);
        }
    });
}

    // other methods...

private String execute(Command command) {
    try {
        return command.apply(getItemServiceFacade());
    } catch (RemoteException re) {
        String message = "5:unexpected error:" + re.toString();
        logger.error(message);
        return message;
    } catch (CoreException ce) {
        String message = "5:unexpected error:" + ce.toString();
        logger.error(message);
        return message;
    }
}

I used this pattern when faced with a similar though slightly more complicated situation (implementing optimistic locking for a few different operations).


Search for subsets within a 250k line text dataset

I'm assuming your code does some background processing, because otherwise the patient data would be stored in a database, not in a text file. In that scenario, 4 seconds is probably ok.

Instead of grouping the records, you could simply filter them. That saves two lines of code, but will probably not be much faster.


I think the primary question here is one of whether _generateStartingWeights or randMatrix are reusable; the secondary question is of naming conventions.

If _generateStartingWeights is not reusable, there's little reason not to write __init__ without the layers of helpers (and that's assuming there's not some better way to use numpy for this). Oh, and if it is reusable, you can just return this from it, instead of using a locally defined helper function:

def __init__(self, layerSizes):
    self.ws = [np.matrix(np.random.normal(0, 0.01, pair)) for pair in pairwise(layerSizes)]

On the flip side, if randMatrix is reusable, it needs to be somewhere other than local to another function.

As for naming conventions, a potentially heated subject, lots of people refer to PEP-8 (which I want to clarify is not a requirement for third party code unless you want to make it one). However due to its prevelance in the Python community, there seems to be a general preference for underscore_separated instead of camelCase names. Since it's not even always followed in the standard library, your project's preferences can overrule it. I only bring it up since I personally find camelCase names to be less in line with my view of "pythonic."


LSTM Model - Validation Accuracy is not changing

One possible reason of this could be unbalanced data. You should have same amount of examples per label. And if you don't have that data, you can use Loss Weights. It is a parameter in model.compile(). You can learn more about Loss weights on google.
Also, I noticed you were using rmsprop as the optimizer. Try using Adam optimizer, as it is one of the best optimizer.
If, doing all of these I mentioned above, doesn't changes anything and the results are the same, remove the Dense() Layers and just keep 1 dense() layer, that is, just keep the last Dense Layer, and remove all the other Dense() Layers.
This will surely improve the model. But, if still it doesn't changes anything, then have a look here


Applying Laplacian smoothing to vertices in a mesh

The code is not that bad at all.

Here are a few notes:

Use list comprehension – it's more readable than maps & lambdas

indices = [x.ID for x in neighbors]

indices isn't really necessary. Instead of

indices = map(lambda x: x.ID, neighbors)
z = len(indices)

help = []
for j in indices:
    help.append([mesh.VPos[j]])
final += [sum(x)/z for x in zip(*help)]

you can simply do this

help = ([mesh.VPos[j.ID]] for j in neighbors)
z = len(neighbors)
final.extend(sum(x)/z for x in zip(*help))

help is a generator expression here, since you don't really need a list. That will probably save some overhead of creating the list. You can also avoid creating a new list of sum(x)/z and directly append all values to final using the extend method.

Instead of reassigning a numpy array to final, I'd just do

mesh.VPos = np.array(final)

I'm not completely sure, but I think the inner lists [mesh.VPos[j]] combined with zip(*help) will amount to the same as just

for j in indices:
    help.append(mesh.VPos[j])
final += [sum(help) / z]

You can create a numpy.ndarray right at the beginning instead of using a Python list and then converting it.

So after the edits it'll look something like this

n = mesh.VPos.shape[0]
final = np.empty(n)  # change dtype if you need to

for i in range(n):
    neighbors = mesh.vertices[i].getVertexNeighbors()
    help = (mesh.VPos[j.ID] for j in neighbors)
    final[i] = sum(help) / len(neighbors)

mesh.VPos = final

Alternatively you can use numpy.mean to compute sum(help) / len(neighbors):

n = mesh.VPos.shape[0]
final = np.empty(n)  # change dtype if you need to

for i in range(n):
    neighbors = mesh.vertices[i].getVertexNeighbors()
    help = [mesh.VPos[j.ID] for j in neighbors]
    final[i] = np.mean(help)

mesh.VPos = final

Note that you cannot give a generator argument to numpy.mean, it has to be a list (or anything with __len__ method).


Is there a more concise way to write this Java string converter?

Sure. No need for the intermediary charactersAsList variable, nor the getAsCharacterList method.

Since you know in advance the final length of the StringBuilder,
it's good to pass that to the constructor when initializing.

// input is already lowercase
private static String mixedCase(String input) {
    StringBuilder result = new StringBuilder(input.length());
    int index = 0;

    for (char character : input.toCharArray()) {
        if (Character.isLetter(character)) {
            if (index % 2 == 0) {
                result.append(Character.toUpperCase(character));
            } else {
                result.append(character);
            }
            index++;
        } else {
            result.append(character);
        }
    }

    return result.toString();
}

Borrowing from the idea of @BrainFRZ to set the already lowercased input in StringBuilder, and from @ferada's comment to use a boolean to decide to uppercase or not, here's another variation that has some advantages:

private static String mixedCase(String input) {
    StringBuilder result = new StringBuilder(input);
    int index = 0;
    boolean toUpper = true;

    for (char character : input.toCharArray()) {
        if (Character.isLetter(character)) {
            if (toUpper) {
                character = Character.toUpperCase(character);
            }
            toUpper = !toUpper;
        }
        result.setCharAt(index, character);
        index++;
    }

    return result.toString();
}

This takes advantage of the input being already lowercased,
and naturally letting StringBuilder to use that.
With some of the conditions eliminated, this version is slightly more compact.


This is a rough draft, since I do not know the overall picture of your project. Some design might be improved to not even use this code (events, semaphores, mutexes, and other more predictable synchronization mechanisms). I rarely use this pattern for code that I control, more for code I cannot that I know is blocking. This approach is risky, as it can lead to undesired state and data loss. You have been warned! (http://thedailywtf.com/articles/My-Tales) for reference!)

If you stay on this path, I recommend A separate class/method be responsible for this sort of behaviour, to favour reuse, this also includes the possibility of having a CancellationToken passed in, just in case you change your mind about the request:

public async Task<T> WaitForActionCompletionOrTimeout<T>(Func<T> action, int timeout, CancellationToken? globalCancellation = null)
{
   var result = default(T); //return default for error

   var localCancellation = new CancellationTokenSource();
   var localAndGlobalCancellation =
            CancellationTokenSource.CreateLinkedTokenSource(localCancellation.Token,
                                                            globalCancellation.HasValue ?
                                                            globalCancellation.Value :
                                                            CancellationToken.None);

   Task cancelationTask = null;
   Task actionTask = null;

   try
   {
     cancelationTask = Task.Delay(timeout, localAndGlobalCancellation);
     actionTask = Task.Factory.StartNew(() =>
     {
       result = action.Invoke();
     }, localAndGlobalCancellation);
   }
   catch (Exception ex)
   {
     Trace.WriteLine(ex.Message);
     localCancellation.Cancel();
     return null;
   }

   await Task.WhenAny(actionTask, cancelationTask).ContinueWith(t => localCancellation.Cancel());
   return result;
}

Change the work method to return true or false, something like:

public bool CheckForUpdate()
 {
     using (var wcfmonitoring = new WCFMonitoring.MonitoringDatabaseClient())
     {
          var sw = new SpinWait();
          while (!wcfmonitoring.CheckForEquipmentUpdate(Authentication.GetSessionID(Session), Authentication.GetPTO(Session), ID)) //maybe  something shorter would work :) some variables are nice for debugging
          {
              sw.SpinOnce();  //magic Thread.Sleep(5) replacement with lots of goodies :) nice class to look at
          }

          Thread.Sleep(2000); //for the importer
          return true;
    }
}

And then:

var success = WaitForActionCompletionOrTimeout(() => CheckForUpdate, 600000 ); //I would so like 6.minutes.in.miliseconds.... ah dreams

This sort of approach (cancelling the worker)  could also be done with threads in a much shorter and brute-forcier way for a slow performance increase in case of very low timeouts.

I would also advise using using and if WcfMonitoring is not IDisposable, to make it IDisposable.

One more question: What is the intent/difference between calling Abort and Close in your code?


64-bit Mersenne Twister random-number generator; follow-up #1

Don't pay for what you don't use

I can imagine many situations where using the generator from one and only one thread would be quite reasonable. In that case, users would pay on each call to the function. It is one of the reasons why I prefer objects in these cases: it gives gun to hands of the users. Whether they shoot their foot or what they want to shoot is not my business any more. Though it is not excuse to make "easy to use incorrectly" interfaces.

C with classes interface

I'm not really sure why, but the exact kind of interfaces are prevalent. May be it is because I learnt modern C++ before learning anything else. Modern ways of doing things should come to mind first, and if they are not good fit, start searching for something else.

Modern (almost?) interface

Lets reconsider the interface (given you figured out how to share state, which leads to object):

template <typename ForwardIterator>
void generate_range(ForwardIterator first, ForwardIterator last)
{
    //state sharing mechanism

    while (first != last)
    {
        *first++ = number_distribution(random_number_generator);
    }
}

This enables following syntax:

std::vector<int> v(20);
generate_range(v.begin(), v.end());

But this requires resizing. Some people even might want to print 10 integers into something, like in your example. Lets handle that too:

template <typename OutputIterator>
void generate_some(OutputIterator d_first, std::size_t n)
{
    for (std::size_t i = 0; i < n; ++i)
    {
        *d_first++ = number_distribution(random_number_generator);
    }
}

This enable following:

generate_some(std::ostream_iterator<int>{std::cout}, 10);

Or, if you want to append into vector:

std::vector<int> v;
generate_some(std::back_inserter(v), 10);

And, just for symmetrical and intuitive interface:

generate_one()
{
    return number_distribution(random_number_generator);
}

Of course in all of the examples you'll get narrowing conversion warning, I was just too lazy to type out std::uint64_t (I don't have IDE autocomplete here). Also, maybe putting static_assert to check iterator types will output much better compilation error message.

User experience

Yes, yes, user experience. It is not only about graphical interfaces. What experience do you want your users to have? What use cases do they have? Usually you have a problem, then solve it. Creating an interface without use cases in mind is like solving non-existent problem.

I would design an interface using this algorithm:

Write usages out in declarative form
Write out some candidates
If list is empty, make usages more concrete, go back to 1
Narrow/order list based on "easy to use correctly, hard to use incorrectly"
Order the list based on implementation complexity
Start implementing from first to last, until the first working version
Think if they'll ever need more control, stop if not.
Port/factor out core functionality which has greatest amount of control, and base the interface on top of it. Usually template parameters with default arguments, function with default arguments, using declarations help. I've yet to see the cases where it would be impossible.


It seems that the ok fields plus the problem fields equal all the fields.

In that case, you should consider deriving problem fields from all fields and ok fields with the Underscore difference method.

So in short:

function stringLengthValidation( mergedModelAndFormFields ) {
    let fieldsToValidate = mergedModelAndFormFields.okFields

    // extracted function
    function checkStringLength() {
        return _.pickBy( fieldsToValidate, ( value ) => {
            return validator.isLength( value[ 'content' ], {
                'min': value[ 'validation' ].minLength,
                'max': value[ 'validation' ].maxLength
            } )
        } )
    }

    let okFields = checkStringLength()

    return {
        'okFields'     : okFields,
        'problemFields': _.difference( fieldsToValidate, okFields )
    }
}

Actually, I would probably not even encapsulate what is in essence 1 statement into a separate function, it seems subjectively overkill to me:

function stringLengthValidation( mergedModelAndFormFields ) {

    let fieldsToValidate = mergedModelAndFormFields.okFields
    let okFields = _.pickBy( fieldsToValidate, ( value ) => {
        return validator.isLength( value[ 'content' ], {
            'min': value[ 'validation' ].minLength,
            'max': value[ 'validation' ].maxLength
        } )
    });

    return {
        'okFields'     : okFields,
        'problemFields': _.difference( fieldsToValidate, okFields )
    }
}


Given some integers, return the k most frequent elements

Just the general C++ coding style treatment.

Do not use using namespace std;. It can introduce subtle bugs, makes the code harder to read and writing out the std:: prefix generally is not going to be to time intensive.
Keep your spacing consistent. Compare the following two lines

bool operator< (const Node& other)
vector<int> topKFrequent(vector<int>& nums, int k)

Why is one method name followed by a space while the other is not? Consistency is important! If you are not sure which spacing variant to choose, you should read a C++ style guide. The same applies to control structures, such as

for (auto n : nums )
if ( frequency.find(n) != frequency.end())
for ( auto f : frequency )

Use a member initializer list in your constructor. Although it does not matter in a lot of cases, it is a more concise way of expressing member initialization and leaves the constructor's body open for more complex setup tasks. The Node constructor would then look something like this:

Node(int value, unsigned frequency) : value(value), frequency(frequency) { }

Also, since you default constructor does not actually do anything, you should remove it and the initializers for value and frequency and add default values to the constructor parameters instead, so that Node's constructor becomes something like

Node(int value = 0, unsigned frequency = 0) : value(value), frequency(frequency) { }

Keep in mind, however, that this constructor allows implicit conversions from integer types, which you typically want to avoid. This is easily prevented by making the constructor explicit.
Most people prefer to not write this-> explicitly when not needed.
const-correctness is important. You should take the parameter nums in topKFrequent by const-reference since you do not actually modify it.
Always use curly brackets with if,else,for,while etc. This prevents a lot of errors from statements not being included in conditionally dependent blocks when they should be. In fact, this kind of error is so common that gcc even introduced a diagnostic for misleading indentation in version 6.


One thing that is quite important to really understand. It's something that is said all too often, but it's very true:

  Premature optimzation is the root of all evil

By your own admission, you're using wordpress, and post some 30-odd lines of PHP code, asking us what you could do to improve performance. Well, I can tell you that some parts of your code are perhaps not as optimal as they could be, but really: you won't notice any difference even if your code were written as efficiently as possible. The real overhead still is the fact that you're using wordpress, which means there's a ton of code being executed you've probably not even looked at.

Is that a bad thing? No, of course not. What does that mean for you? Well, that you shouldn't be focussing on writing the optimal code just yet. First, you should define "optimized code".

Code can be optimized for:

Readability. Very important if you're collaborating, and if ever you have to revisit a piece of code half a year after writing it
Debugging. Code that is optimized for debugging is well documented, well structured, and has a lot of functions that all do a distinct task, and do it well, without an awful lot of complexity.
Speed. This is, I think what you're after, but at this stage, you shouldn't be. You really shouldn't be thinking about this yet, because code written for performance tends to be error prone, harder to read, and difficult to debug. You can optimize code once you've thoroughly tested every single expression of every statement several times over.
Though we seldom see this kind of optimization today, not too long ago, code could also be optimized for storage. Back in the day where a 10Mb drive was worth the equivalent of a years' salary. This point is kind of irrelevant, but just for completeness' sake, I thought I'd mention is.

Having said that, I really do feel as though you should be focussing on writing clean code. Code that is easy to debug, easy to understand and is more self-documenting. I'll go through your code bit by bit, and give a couple of tips to optimize both in terms of readability and execution-time performance (though, again, in terms of speed, there won't be much between the two versions).

$permalink = get_permalink( $id );
$seo = get_the_title()." : "; //more on this var later
//camelCase the vars, it's more common and for many, more readable
$categoryLinks = ' Found in the ';
//spread out function calls that get too long
$termListCategory = wp_get_post_terms(
    get_the_ID(),//this way, you can comment on each param you're passing
    'listings_categories',//like so: this is some string
    array(
        'fields' => 'ids'//assoc array argument specifying something...
    )
);
/** only display children, if term has children, remove it from the array
 * Just like it might be a good idea to use multi-line comments
 * and don't use SHOUT CASE in documentation, why would you?
 */
foreach ($termListCategory as $k => $term)
{//whitespace is good, use it more
    //this assignment is a bit redundant
    $children = get_term_children(
        $term,
        'listings_categories'
    );
    //this is technically valid, but it's not safe
    //think back to apple's infamous goto fail; bug, use brackets
    if ($children)
    {
        unset($termListCategory[$k]);
    }
}

an alternative way to write this loop would be this:

foreach ($termListCategory as $k => $term)
{
    if (get_term_children($term, 'listings_categories'))
    {
        unset($termListCategory[$k]);
    }
}

That, to me at least looks a lot cleaner. This is assuming you can't do anything about the return value of wp_get_post_terms like: structuring the data differently, using different query methods and all that, so that you don't have to fetch data that you're just going to filter from the array anyway.

All that asside, let's continue:

$i = 0;//This doesn't belong. $i is a loop var (99% of the time), why declare + initialize it here?

$count = count($term_list_category);//this is a pointless count call, just write this:
if ($termListCategory) {
//instead of: if ( $count > 0 ){
//an empty array is falsy
    foreach ( $termListCategory as $termCategory )
    {
        $thisCat = get_term_by(
            'id',
            $termCategory,
            'listings_categories'
        );

        //Separate this out into a function!!
        $url = '{'slug'} . '" class="listing-links-cat" href="#" title="' . $thisCat->{'name'} . '" >' . $thisCat->{'name'} . '';

I've always gotten the hebejeebies when I see string concatenation like this. Please, separate it out into a function, with clear type-hints (if possible), and don't access properties using string constants the way you do. I'd simply write this:

function getUrlFromObject(stdClass $obj, $id)
{
    $url = 'slug . '" class="listing-links-cat" '
        . 'href="#" title="' . $obj->name . '" >' . $obj->name . '';
    return $url;
}
//call like so, inside the foreach
$url = getUrlFromObject($thisCat, $termCategory);

Well, since you've asked us not to go too technical, I've kept the string concatenation business like you're using, but just in case you want to look into something new, I'd actually use sprintf  here, I think, or an actual DOM parser/builder (like DOMDocument or SimpleXMLElement). Anyway, here's the sprintf version:

function getUrlFromObject(stdClass $obj, $id)
{
    return sprintf(
        '%3$s',
        $id,
        $obj->slug,
        $obj->name
    );
}

To my eye at least, that looks a lot cleaner than what you have now, but that might be a matter of personal preference, just like your adding spaces between a variable and the postfix-increment operator:

        $i ++;

Whereas I'd write either ++$i; or $i++;. Some people might claim that ++$i; is faster, but honestly: that's a myth that comes from the C-world where there can be a difference between ++i and i++ if the compiler optimization is switched off. Either way, in PHP it doesn't matter, but it's more common to see $i++; anyway (without the spaces).

        $seo .= " " . $thisCat->{'name'} . "";

        $Category_links .= " " . $url . "";

        if($count-1 == $i){
            $Category_links .= " and ";  $seo .= ", ";
        }elseif($count > 1 && $count !== $i){
            $Category_links .= ", ";  $seo .= ", ";
        }

    }
    $Category_links .= " Categories";
?>

I cannot, for the life of me, understand why you're closing the PHP tags, only to open them again and echo here:

<? echo $Category_links;  ?>

Lastly, what you're doing with these $seo and $Category_links vars is just very error-prone, and clunky-looking. I'd suggest you turn them into arrays, and simply add new values to them. An array of strings can be imploded using any delimiter you like so replace this:

$seo = get_the_title() . ' : ';
//...more stuff
foreach ($termListCategory as $termCategory)
{
}

With something more like:

$seo = array(
    get_the_title() . ' :',
);
$categoryLinks = array();//create empty array
//...more stuff
foreach ($termListCategory as $termCategory)
{
    $seo[] = $thisCat->name;//add this to the seo ARRAY
    $categoryLinks[] = getUrlFromObject($thisCat, $termCategory);
}
$seoString = implode(', ', $seo);//turns array into comma-separated string
$categoryLinkString = implode(', ', $categoryLinks) . ' and Categories';
//or simply directly output the string:
echo implode(', ', $categoryLinks) . ' and Categories';

Is this code faster? Well, probably not. Sure, I'm not calling count for no obvious reason, and I don't use string concatenation that often, but I am manipulating two arrays, which comes at a cost of its own. Using a custom function, and calling that isn't free either, but let's be honest: that's not going to be your major bottleneck. Besides, the upshot is: code that is a lot easier on the eyes:

/**
 * String object into link, pass object, then term (id)
 *
 * @param stdClass $obj
 * @param string $id
 * @return string
 */
function getUrlFromObject(stdClass $obj, $id)
{
    return sprintf(
        '%3$s',
        $id,
        $obj->slug,
        $obj->name
    );
}

$permalink = get_permalink( $id );
$seo = array(
    get_the_title() . ' :',
);
//this var was a string, but we've moved it to where we echo the imploded links array (before the imploded array, see below)
$categoryLinks = array();
$termListCategory = wp_get_post_terms(
    get_the_ID(),
    'listings_categories',
    array(
        'fields' => 'ids'
    )
);
foreach ($termListCategory as $k => $term)
{
    //if term does NOT have children, process it
    if (!get_term_children($term, 'listings_categories'))
    {
        $seo[] = $thisCat->name;//add this to the seo ARRAY
        $categoryLinks[] = getUrlFromObject($thisCat, $termCategory);
    }
    //if you want, you can add
    // an else { unset($termListCategory[$k]); } here
    // I just don't see the point of it here
}
$seoString = implode(', ', $seo);//turns array into comma-separated string
//Add the "found in the" bit here
echo 'Found in the ', implode(', ', $categoryLinks) . ' and Categories';

So after putting it all together I have:

Removed a lot of concatenation
Removed some function calls (count, for example)
Added other function calls
Added a function definition
Removed the secondary loop
Removed a fairly pointless if around the second loop
IMO simplified the code quite a lot, and made it easier to debug
Added some documentation


Creating a dictionary of all prefixes of a string in Python

It's hard to tell what is making the error occur without giving us the input, but it's certainly possible the input is too large for the system to store.

prefix_dict will contain len(a) entries so if your input is larger than 32-bit python allows for dictionary size on your machine, then that could be the issue.

I will note that instead of having prefix_dict[prefix] = len(prefix) you could just have prefix_dict[prefix] = j which would stop you from needing to do an extra length calculation each time (not that this would be the cause of the memory issue).

Take a look at the sample output (I modified the print statement and used an example string):

>>> prefix_dict = {}
>>> a = 'hello'
>>> for j in xrange(1,len(a)+1):
        prefix = a[:j]
        prefix_dict[prefix] = len(prefix)
        print j, len(prefix), prefix_dict

1 1 {'h': 1}
2 2 {'h': 1, 'he': 2}
3 3 {'hel': 3, 'h': 1, 'he': 2}
4 4 {'hel': 3, 'h': 1, 'hell': 4, 'he': 2}
5 5 {'hel': 3, 'h': 1, 'hell': 4, 'hello': 5, 'he': 2}