if you add the parent div class into the data attributes:

<button id="egyes" class="btn btn-danger" data-parentclass="progress-danger">Hide</button>&nbsp;some text
<button id="kettes" class="btn btn-warning" data-parentclass="progress-warning">Hide</button>&nbsp;other text
<button id="harmas" class="btn btn-info" data-parentclass="progress-info">Hide</button>&nbsp;some more text
<button id="otos" class="btn btn-success" data-parentclass="progress-success">Hide</button>&nbsp;last button
<button id="showall" class="btn">Show all</button>

or add it in via javascript:

$("#egyes").data("parentclass", "progress-danger");
// etc

then the javascript can work it out itself.

$(document).ready(function() {
    $("#egyes, #kettes, #harmas, #otos").click( function() {
        var $parent = $("div." $(this).data("parentclass")).parent();

        if ($parent.is(":visible")) {
            $(this).html("Hide");
        } else {
            $(this).html("Show");
        }

        parent.fadeToggle();
    });

    $("#showall").click( function() {
        $("div.container > div > div.progress").parent().fadeIn();
    });
 });


You have hard-coded the 1, 3 and 5 column index... and you don't really have a choice, given the shape of your data.

The problem is that your table is not a table: it's essentially a pivot. This would be a table:

If you can un-pivot your top table into an actual table like above, then you could have a much simpler, easier to read (and to maintain!) table formula - given a Table1 table name for the above table:

=INDEX(Table1[Category],MATCH([@Id],Table1[Id],0))

Excel likes data that's organized in rows and columns; if you have 2 levels of headings, and repeating columns under each heading, you haven't organized your data in rows and columns, and you've set yourself up for complicated lookups - as you've noticed.

By laying out your data in a table, you make a database-friendly list of records that can easily be sourced from a CSV or XML file, or directly from a database table or view.

Having 3 times the same [Id] and [Name] columns under a different heading, looks like you have 3 identical tables, with different values: by combining them into one (and adding a column to identify which of the 3 tables it's coming from), lookups become much, much simpler.

Other than that, I would add the following:

The bottom table should be turned into an actual table, so leverage table formulas. D19 would then say [@Id], which is much easier to understand.
The top table should be on its own worksheet, and adding rows in that table should not force you to update the formulas in the bottom one - as it stands, you'll have to be careful about that.
If you can't turn the top table into an actual table, consider using named ranges to abstract $C$12:$C$14 & friends behind a name. You'll still have to be careful when adding rows, that the new rows are included in the named range - but if the formulas in the bottom table refer to named ranges instead of addresses, you won't need to modify the formulas, just to verify the reference the named ranges point to.
If 1, 3 and 5 are the only valid values, you could name them:

That way you can replace the hard-coded 1, 3 and 5 by "Funding", "Lending" and "Example" in your formula, giving a meaning for these numbers:

=INDEX(
   Categories,0,
      IF(IFERROR(MATCH(D19,FundingIds,0),0),Funding,
      IF(IFERROR(MATCH(D19,LendingIds,0),0),Lending,
      IF(IFERROR(MATCH(D19,ExampleIds,0),0),Example,0
))))

But I would really push to remove the first-level heading and turn it into a column: logically, it's a piece of data - it belongs at the row level, not as a heading. Your worksheet will be much easier to extend that way.


Generic Implementation for Paging Class in c#

Some quick remarks:

Names shouldn't contain underscores etc: CountingCloud_DevContext. (The exception is the underscore at the start of a private member (e.g. _dbContext.)
If you have a Dictionary, do not use ContainsKey if you need to retrieve the value associated with that key. This is why the much more efficient TryGetValue exists.
Do not copy-paste magic strings (e.g. "PageSize") all over the place. Store them as const in a relevant class and use that.
But most importantly: what's the point of Dictionary<string, object> when all it contains is two specific key-value pairs? Why not make a PagingParameters class with PageSize and PageStart as nullable ints? Don't make things too generic, because all you end up is making things harder for yourself.
Also avoid making a generic Repository class. It likely will create more work and solve nothing.


Given a set of points and pairs of lines, count the number of points that are between the pairs of lines

You can get the intersection of a line described by 2 points with the y axis pretty easily using a simple formula.

First you sort the walls in increasing order. O(P log P)

For each point g you can get the intersection between the line g-E and x = 0 with g' = (g-E) / ((0-E.x) / (g.x-E.x)) + E (will need floating point operations) and you can search for g'.y in the walls array with a binary search. O(G log P)

Beyond that some comments about your code:

using namespace std; is usually a warning sign. This has several issues. Instead only use it to pull in specific thing you actually use or limit it to function scope.
Everything is in main. Reading the problem I'd expect a few functions like main, doSingleTest, readWalls and processPoints.
Declaring additional variables in the for initializer. This is very odd to see. Give each of them their own line in the body:

for (int j = 0; j < p; ++j) {
    //j can stay because it's the iterator value

    // you calculate them immediately after so join the declaration with initialization
    int signal1 = cross(exps,wall[j].p1,pos[k]);
    int signal2 = cross(exps,wall[j].p2,pos[k]);

Raw array usage. Instead use vector which will auto clean up when it goes out of scope.


Function to convert a decimal number as a string to hexadecimal

Code Review.

If this is a set of constants you want to chech against then it should by marked as constexpr  (or const), that way nobody can actually modify it. Also why pollute the global space with another variable; declare it inside the function (as a static so it only gets initialized once).

string digits = "0123456789abcdef";

Also there is a standard function to check if a character is a hex digit std:: isxdigit().

Pass objects by reference to prevent a copy.

string tohex(string number) {

Since you are not modifying number make it a const reference.

Note: You should return by value. The optimizer will remove the need to copy out of the function so you don't need to worry about a copy here.

Declare variables as close to the point of usage as possible. Here result is declared but not used until the next section of code. So When I start seeing result being used I need to scan up the function a long way to find it.

    long length = number.length();
    string result = "";

This is an interesting way to convert characters into digits.

    vector<long> nibbles;
    for ( long i = 0; i < length; i++ ) {
        nibbles.push_back(digits.find(number[i]));
    }

But: 1) You don't check for invalid input as a result you may push back std::string::npos (a big number that is converted is probably converted to -1 when assigned to long). 2) This is O(n) for every digit. it can be done in O(1).

The standard guarantees that the character-set has all the numbers 0 -> 9 in a contiguous range. So you can convert a character (that is a digit) into a number by subtracting the value of 0 from the character.

char d = number[i];
nibbles.push_back((d >= '0' && d <= '9)
                         ? d - '0'
                         : (d >= 'a' && d <= 'f')
                                ? d - 'a' + 10
                                : (d >= 'A' && d <= 'F')
                                     ? d - 'A' + 10
                                     : -1;

PS. Don't write that. Put it in a function.

I see what you are doing. But the functionality could be a lot neater.

    long newlen = 0;
    do {
        long value = 0;
        newlen = 0;
        for ( long i = 0; i < length; i++ ) {
            value = (value * 10) + nibbles[i];
            if (value >= 16) {
                nibbles[newlen++] = value / 16;
                value %= 16;
            } else if (newlen > 0) {
                nibbles[newlen++] = 0;
            };
        };
        length = newlen;
        result = digits[value] + result;
    } while (newlen != 0);
    return result;
}

This is how I would do it.

How about:

template<class T>
string to_string(T t, ios_base & (*f)(ios_base&)) {

  ostringstream oss;
  oss << f << t;
  return oss.str();
}

string tohex(string number) {

    long value = std::stoi(number, null, 10);
    return std::to_string(value, std::hex);
}


Pin an array in memory and construct a Bitmap using that buffer

I cannot complain about your code much. You declare variables as readonly where appropriate and you use the try/finally block to free the resources.

The only things I don't like are these properties

public int Width { get; set; }
public int Height { get; set; }

you don't want them to be settable. The setter should be private.

and the magic numbers here (and in other places).

_buffer[i + 1] = color.R;
_buffer[i + 2] = color.G;
_buffer[i + 3] = color.B;

I find you should use a helper class for them:

static class ColorOffset
{
    public const int Alpha = 0;
    public const int Red = 1;
    public const int Green = 2;
    public const int Blue = 3;
}

_buffer[i + ColorOffset.Red] = color.R;
_buffer[i + ColorOffset.Green] = color.G;
_buffer[i + ColorOffset.Blue] = color.B;


The array may be up to 105 elements long.  If you actually perform the rotation, then you will be copying at least 105 elements.  (You actually do ridiculously more work, as @JoeC and @OhadR have both pointed out.)

However, there will be at most 500 queries.  It would be nice if you didn't have to modify 105 entries just to satisfy 500 queries.  You don't actually need to perform the rotation — you only need to pretend to have performed the rotation.

import java.util.Scanner;

public class CircularArrayRotation {
    /**
     * Performs one query.
     *
     * @param a  The original array
     * @param k  The number of right circular rotations
     * @param m  The index of the rotated array to retrieve
     */
    public static <T> T query(T[] a, int k, int m) {
        int n = a.length;
        return a[(((m - k) % n) + n) % n];
    }

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

        int n = sc.nextInt(), k = sc.nextInt(), q = sc.nextInt();
        sc.nextLine();                          // End of first line

        String[] a = sc.nextLine().split(" ");  // Second line

        while (q-- > 0) {                       // Perform q queries
            System.out.println(query(a, k, sc.nextInt()));
        }
    }
}

Strictly speaking, you don't even need to parse the ai as integers — you just need to read and regurgitate them.  You also don't need to store all q queries — you can just reply to each one as soon as you read m.


First thing that pops in the eye is the unindented code, most IDEs do this automatically for us. That's fundamental for everyone's sanity, yours and whomever reads your code.
And you are missing two things from add_meta_box() parameters that will make the code reusable:

add_meta_box( $id, $title,$callback, $screen, $context, $priority, $callback_args );

One is that $screen can be an array, so the foreach $screens is unnecessary. And the other is the normally forgotten $callback_args, with it we can prepare an array that will build all our metaboxes using the same $callback function.
Notes:

$metaboxes is the reusable source, just add another item and a new metabox is created.
save_post receives 2 arguments, $post_id and $post_object.
I prefer to put all hook declarations at the beginning, as it gives a general panorama of all functions below.
Use of printf() to build complex HTML blocks.

add_action( 'add_meta_boxes', 'wp_cat_map_add_meta_box' );
add_action( 'save_post', 'wp_cat_map_data', 10, 2 );

function wp_cat_map_add_meta_box() {
    /* Our configuration vars */
    $screens = array( 'post', 'page' );
    $metaboxes = array(
        'map_lat' => array(
            'label' => 'wp_cat_map_lat',
            'title' => __( 'Add Latitude', 'wp_cat_map' ),
            'description' => __( 'Latitude', 'wp_cat_map' ),
            'name' => 'wp_cat_map_lat',
            'post_meta' => '_wp_cat_map_lat'
        ),
        'map_long' => array(
            'label' => 'wp_cat_map_long',
            'title' => __( 'Add Longitude', 'wp_cat_map' ),
            'description' => __( 'Longitude', 'wp_cat_map' ),
            'name' => 'wp_cat_map_long' ,
            'post_meta' => '_wp_cat_map_long'
        )
    );
    foreach ( $metaboxes as $meta_id => $meta_cont ) {
        add_meta_box(
            $meta_id,
            $meta_cont['title'],
            'wp_cat_map_callback',
            $screens,
            'advanced',
            'default',
            $meta_cont
        );
    }
}

function wp_cat_map_callback( $post, $post_object ) {
    /* Inspect the object */
    // printf( '
%s
', print_r( $post_object, true ) );
    wp_nonce_field( 'wp_cat_map_data', 'wp_cat_map_nonce' );
    $value = get_post_meta( $post->ID, $post_object['args']['post_meta'], true );
    printf(
        '%s',
        $post_object['args']['label'],
        $post_object['args']['description'];
    );
    printf(
        '<input type="text" id="%s" name="%s" value="%s"/>',
        $post_object['args']['label'],
        $post_object['args']['post_meta'],
        esc_attr( $value )
    );
}

function wp_cat_map_data( $post_id, $post_object ) { /* code */ }

Issue:
We need those meta names to use in the save_post callback. Instead of creating a global variable, it's preferable to create a class to encapsulate everything. This way we can send Screens and Meta Boxes when instantiating the class and have post_meta names available inside the save_post callback.
Class Code_Review_111019 {
    /* Class properties, available to all methods */
    private $screens;
    private $metaboxes;

    public function __construct( $screens, $metaboxes ) {
        /* Set properties when instantiating */
        $this->screens = $screens;
        $this->metaboxes = $metaboxes;
        /* Start our hooks at a safer point */
        add_action( 'plugins_loaded', array( $this, 'start_up' ) );
    }

    public function start_up() {
        /* Inside classes we don't need unique prefixes or names for the callbacks, better yet, they can be literal */
        add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
        add_action( 'save_post', array( $this, 'save_post' ), 10, 2 );
    }

    public function add_meta_boxes() {
        foreach ( $this->metaboxes as $meta_id => $meta_cont ) {
            add_meta_box(
                $meta_id,
                $meta_cont['title'],
                array( $this, 'build_metabox' ),
                $this->screens,
                'advanced',
                'default',
                $meta_cont
            );
        }
    }

    public function build_metabox( $post, $post_object ) {
        wp_nonce_field( 'wp_cat_map_data', 'wp_cat_map_nonce' );
        $value = get_post_meta( $post->ID, $post_object['args']['post_meta'], true );
        printf(
            '%s',
            $post_object['args']['label'],
            $post_object['args']['description']
        );
        printf(
            '<input type="text" id="%s" name="%s" value="%s"/>',
            $post_object['args']['label'],
            $post_object['args']['post_meta'],
            esc_attr( $value )
        );
    }

    /* NO CHECKS OR SECURITY WHATSOEVER, FOR DEBUGGING PURPOSES ONLY */
    public function save_post( $post_id, $post_object ) {
        foreach( $this->metaboxes as $mbox ){
            if( isset( $_POST[ $mbox['post_meta'] ] ) ) {
                update_post_meta( $post_id, $mbox['post_meta'], $_POST[ $mbox['post_meta'] ] );
            }
        }
    }
}

$Code_Review_111019 = new Code_Review_111019(
    /* Screens */
    array( 'post', 'page', 'portfolio' ),
    /* Metaboxes */
    array(
        'map_lat' => array(
            'label' => 'wp_cat_map_lat',
            'title' => __( 'Add Latitude', 'wp_cat_map' ),
            'description' => __( 'Latitude', 'wp_cat_map' ),
            'name' => 'wp_cat_map_lat',
            'post_meta' => '_wp_cat_map_lat'
        ),
        'map_long' => array(
            'label' => 'wp_cat_map_long',
            'title' => __( 'Add Longitude', 'wp_cat_map' ),
            'description' => __( 'Longitude', 'wp_cat_map' ),
            'name' => 'wp_cat_map_long' ,
            'post_meta' => '_wp_cat_map_long'
        ),
        'map_zoom' => array(
            'label' => 'wp_cat_map_zoom',
            'title' => __( 'Add Zoom', 'wp_cat_map' ),
            'description' => __( 'Zoom', 'wp_cat_map' ),
            'name' => 'wp_cat_map_zoom' ,
            'post_meta' => '_wp_cat_map_zoom'
        )
    )
);

Suggestion:
Instead of one Meta Box for each piece of information, I think it's better UX to have a single box for your plugin/feature and add the form fields there.


For Python 3.x you do not need to specify the encoding type you chose because it chips by default with UTF-8. So you can safely remove the directive: # -*- coding: utf-8 -*-
You should use timeit over time because the first one is more accurate.
As per PEP 8, you should leave 2 blank lines between the last import statement and the start of your code.
Better if you run this module by putting the guard if __name__ == "__main__"
The inline comments you used would be better used as docstrings instead.


First of all, you should avoid "getters" and "setters" whenever possible.  This is because they can be bad for encapsulation as they reveal the internal members.  This would be an ideal example if you were merely trying to understand getters and setters, but it's still not the best approach to learning how classes should work, especially when you start using them for more complex programs.

You should become aware of object construction.  That is, when you first create an object to hold some data at the start, it should be given to that object upon construction.

Instead of using setters, you should construct the object after getting the input:

X testObject(lNum_1, lNum_2, lNum_3, lNum_4);

This will construct the object right away with the initial values.  However, you'll first need to provide a constructor that will handle this.

You can use an initializer list:

X::X(int num_1, int num_2, int num_3, int num_4)
    : num_1(num_1)
    , num_2(num_2)
    , num_3(num_3)
    , num_4(num_4)
{}

As for the getter, it would only be useful if you need the value.  If you just need to display the members, then you can create a display() function:

void X::display() const
{
    std::cout << "num_1: " << num_1 << "\n";
    std::cout << "num_2: " << num_2 << "\n";
    std::cout << "num_3: " << num_3 << "\n";
    std::cout << "num_4: " << num_4 << "\n";
}

(Notice that I've made this function const.  Since it only displays data members and doesn't modify them, adding this keyword will prevent any accidental modifications.)

It would then be called by itself, rather than calling the getter for each member:

testObject.display();

There's much that can be said about all of this, but I've given you a basic idea on where to start.

Miscellaneous:

Try not to get into the habit of using using namespace std.  If you start writing larger programs, you may run into name-clashing issues if this is misused.  More info about that here.
Since you're not using <cmath>, it should just be removed.
_tmain() should just be main(); the former does not exist in C++.
You could leave out the command line parameters if you're not going to use them.

Otherwise, you could certainly replace your input with command line arguments:

./program_name 1 2 3 4

If you do this, you should also be sure to check the value of argc so that the program won't try to run with too few arguments:

if (argc < 5)
{
    std::cerr << "You must input four numbers!";
    return EXIT_FAILURE;
}

The program name is counted as an argument, so it should be 5.


Getting the last date where a given week day occurred

The most obvious point to make is that whenWasLast repeats the entire code of whenWasLastBasedOnDate. You can (and should) simply write the whole method by just calling whenWasLastBasedOnDate:

let whenWasLast (weekDay:DayOfWeek) =
    whenWasLastBasedOnDate(weekDay, DateTime.Now)

Another point is that you should write AddDays(-1.0) as AddDays -1.0. In languages with ML-like syntax it is generally discouraged to add redundant parentheses around function arguments because it encourages the misconception that the parentheses are part of the method call syntax.

On a somewhat more subjective note, I think that using if would read nicer than a match without any patterns.

On a more general design note it is generally considered good style in functional programming to use higher order functions to express the code more abstractly. For example instead of saying "Check if the given day was a weekDay. If so, return it, if not repeat with the day before" you could say "Look at the last seven days and return the one who is a weekDay". This is not only more idiomatic functional programming, but also makes it impossible to get into infinite recursion by getting the exit condition wrong. In code it would look like this:

[-6.0..0.0] |> Seq.map currentDate.AddDays |>
    Seq.find (fun d -> d.DayOfWeek = weekDay)


Optimizing puzzle game involving sequence numbers

I've dug into the concept a little bit and as a start here are some bits of code and discussion to help out. Obviously, the real meat here is doing the backtracking efficiently but I think starting with simplifying the problem a bit would help.

For starters, it seems that turning the grid into a simple list would make it easier to deal with the relevant code.

// Initialize game parameters
// --------------------------
$game = array();
$game['xlen']    = 4;
$game['ylen']    = 4;
$game['blocked'] = 1;
$game['size']    = $game['xlen'] * $game['ylen'];
$game['playing'] = 0;

// Initialize empty grid
// ---------------------
$grid = array();
for ( $i = 0; $i < $game['size']; $i++ )
  $grid[] = 0;

// Let's take a look
// -----------------
echo "Initialized game grid...

\n";
dump_grid($game,$grid,3);

So, here's a grid dumping function that will allow very detailed insight into the behavior of the running program in case it isn't doing exactly what one might expect.

// It's always important to be able to "see" what is happening to get insight
// into what is working and what isn't.
// --------------------------------------------------------------------------
function dump_grid($game,$grid,$indents = 0)
{
  // Build up indent value
  // ---------------------
  $indent = '';
  if ( $indents )
  {
    $indent = str_repeat("&nbsp;",$indents);
    echo $indent;
  }

  // Dump out grid contents
  // ----------------------
  $x = 0;
  foreach ($grid as $value)
  {
    echo "| " . sprintf("%02d",$value) . " ";

    $x++;
    if ( $x >= $game['xlen'] )
    {
      echo "|
\n$indent";
      $x=0;
    }
  }
  echo "
\n";
}

Using the above I can watch events unfold in the following manner... as I like to iterate code/test efforts by reloading the code in a browser page.

Initialized game grid...

   | 00 | 00 | 00 | 00 |
   | 00 | 00 | 00 | 00 |
   | 00 | 00 | 00 | 00 |
   | 00 | 00 | 00 | 00 |

Sample blocked square...

   | 00 | 00 | 00 | 00 |
   | -1 | 00 | 00 | 00 |
   | 00 | 00 | 00 | 00 |
   | 00 | 00 | 00 | 00 |

Starting position selected...

   | 00 | 00 | 00 | 00 |
   | -1 | 00 | 00 | 00 |
   | 00 | 00 | 00 | 00 |
   | 00 | 00 | 00 | 01 |

Of course, the hard part is left. What I would consider doing at this point is using the "grid" to store game state with respect to blocked squares and moves and maintaining a separate move tree to ensure that random selection doesn't end up trying failed branches over and over.

Using your game objects, or mine, a method of maintaining the known failing moves from a given state will be needed. That could be integrated into a move selection function. I have a rudimentary move selection function used to choose the blocked location and starting point in the above.

// Pick a random grid position. Optional parameter to force game placement
// rules to be applied when picking a position.
// --------------------------------------------------------------------------
function pick_open($game,$grid,$playing = 1)
{
  $open = array();
  for ($i=0; $i < $game['size']; $i++)
    if ( $grid[$i]==0 )
      $open[$i] = $i;

  if ( !count($open) )
    die("Attempting to pick an open spot when none are available!");

  if ( !$playing )
    return array_rand($open,1);

  die("Rules based open spot select not yet implemented!");
}

As I'm trying to help and not create the whole solution I'll have to leave that to you. However, I would strongly suggest making the effects of your code as visible as possible and looking for ways to simplify the problem.

Hint: Perhaps use the game state (the grid being output) as a key to determine if any moves from that state have already proven to be failures.

Note: If you weren't using random move selection you could just iterate through all possible moves and accept the first valid solution. However, a non-random iteration might make a game too predictable.


Longest consecutive sequence of ascending, descending, or equal integers

The code is generally good and clear.  I like the names you've used for your variables - it's very obvious what each does, with the possible exception of findIndex.

There's an issue with the problem statement (which might not be your fault): it doesn't say what to do if there's more than one "longest" sequence.  In this code, it appears that we use the first match if there's another of the same length; it's worth writing a comment to be clear that this is what we want (and including such a case in the tests, so that we know if that changes).

isSequence is a bit more long-winded than it needs to be.  This pattern is redundant:

if (condition)
    return true;
else
    return false;

It can always be replaced with

return condition;

In findSeq itself, we're doing pretty well.  I get a compiler warning about comparing (signed) i against (unsigned) vect.size(); that's easily fixed by changing i to be a std::size_t instead of an int.  Most of the other int variables would be better represented as std::size_t, too.

One thing we might want to do is to use iterators rather than indexes, to give us an opportunity to work with different collections in future.  And instead of printing to std::cout, we might want to return the start and end iterators of the longest matching sequence.  (If we do print the values, it's a good idea to separate them from each other, otherwise we can't tell 33,3 from 3,3,3, for example).

If we're using iterators, we'll want to remember the previous and ante-previous values, because we can't necessarily go back to them.  Equivalently, we can remember the previous value and the direction of difference.

I don't know if this is beyond your current knowledge, but this is what I came up with when I followed my own suggestions, and took it a little further to work generically as a template:

#include <iterator>
#include <utility>

// return the sign of a-b (or the sign of a, if b is defaulted)
// result: -1 if a<b, 0 if a==b, +1 if a>b
template<typename T>
int compare(T a, T b = {})
{
    // This is a "clever" way of determining the sign.  Some
    // compilers recognise this idiom and reduce it to a single
    // instruction.
    return (a > b) - (a < b);
}

template<typename ForwardIterator>
std::pair<ForwardIterator,ForwardIterator>
findSeq(const ForwardIterator first, const ForwardIterator last)
{
    if (first == last) {
        // empty range -> empty result
        return { first, first };
    }

    auto best_start = first;
    auto best_end = first;
    std::size_t best_length = 0;

    auto current_start = first;
    auto previous = first;
    int current_direction = 0;
    std::size_t current_length = 0;

    auto const update_best = [&](ForwardIterator end){
        best_start = current_start;
        best_end = end;
        best_length = current_length;
    };

    for (auto it = std::next(first);  it != last;  ++it) {
        const auto new_direction = compare(*previous, *it);

        if (new_direction == current_direction) {
            ++current_length;
        } else {
            if (current_length > best_length) {
                update_best(it);
            }
            current_direction = new_direction;
            current_start = previous;
            current_length = 1;
        }

        previous = it;
    }

    if (current_length > best_length) {
        update_best(last);
    }

    return { best_start, best_end };
}

// provide an interface compatible with the original
template<typename Collection>
auto findSeq(const Collection& c)
{
    using std::begin;
    using std::end;

    return findSeq(begin(c), end(c));
}

#include <array>
#include <iostream>
#include <forward_list>
#include <vector>

template<typename ForwardIterator>
void printSeq(std::pair<ForwardIterator,ForwardIterator> range)
{
    auto [first,last] = range;
    for (auto it = first;  it != last;  ++it)
        std::cout << *it << ' ';
    std::cout << std::endl;
}

int main()
{
    printSeq(findSeq(std::vector{8,3,6,9,2,6,12}));
    printSeq(findSeq(std::array{-0.1, -0.2, -0.3, -0.4, 0.1, 0.2, 0.3, -1.0}));
    printSeq(findSeq(std::forward_list<std::string>{
                "foo", "bar", "bar", "bar", "baz", "quux"}));
}


Improving performance of A* search in PHP

I managed to greatly increase performance by avoiding array resizing and memory reallocation. By allocating all array space I need by start and reusing those arrays instead of recreating and resizing them, the performance of the code has dramatically changed from one search every couple seconds to almost a hundred searches per second.

<?php

    /*

        1 ____ 2 ____ 3 ___ 5
        | \            ____/|
        |  \    ______/     |
        |   4__/            |
        |  /                7
        | /
        6

    */

    $points = [
        1 => [2, 4, 6],
        2 => [1, 3],
        3 => [2, 5],
        4 => [1, 5, 6],
        5 => [3, 4, 7],
        6 => [1, 4],
        7 => [5]
    ];

    $seen = $queue = [];
    foreach ($points as $key => $val)
    {
        $seen[$key] = 0;
        $queue[] = [0, -1];
    }

    function points_pathfind($from, $to)
    {
        global $points, $seen, $queue;

        if (!isset($points[$from]) || !isset($points[$to]))
            return null;

        if ($from == $to)
            return [$from];

        $queue[0][0] = $from;

        array_walk($seen, function (&$a) { $a = 0; });
        $seen[$from] = 1;

        for ($cur = $end = 0; $cur <= $end; ++$cur)
        {
            foreach ($points[$queue[$cur][0]] as $next)
            {
                if (!$seen[$next])
                {
                    if ($next == $to)
                    {
                        $result = [$to];
                        for ($jmp = $cur; $jmp != -1; $jmp = $queue[$jmp][1])
                            $result[] = $queue[$jmp][0];
                        return array_reverse($result);
                    }

                    ++$end;
                    $seen[$next]    = 1;
                    $queue[$end][0] = $next;
                    $queue[$end][1] = $cur;
                }
            }
        }
    }

    echo implode(' -=> ', points_pathfind(1, 7));

The general approach of the algorithm howover is still the same. I wonder if there is a more intelligent way.


Making a preselected drop-down selection box in HTML

You can use a lookup table for your values like this:

$values = array("magic" => "Magic points", ...);

and then loop over that to reduce the duplication:

foreach ($values as $key => $value) {
    ...


Run the most recently requested action after finishing current, skip middle tasks

Don't change the locks - You lock on _task, but inside the synchronized block - you change the reference to _task to a new object! This means that if threadA is in the block, threadB is waiting for the lock to release, and threadC calls the method exactly after threadA has run _task = ret; - threadC will be able to enter the block! This makes your lock mechanism fail.

If you want to lock a block - find a lock which defines the scope of your lock - and maintain it accordingly. In your example, the scope seems to be the instance of SingleTaskQueue. Since it is not advisable to do lock(this), create a private object _lock = new object(); and use it as your lock.

Mind your state - in ProcessLastAction you take your action from _action, to take only the last one, but you take the token as a parameter. This means that if two threads queue a new message before the last task finishes - the second _action may be invoked with the first token - which is already cancelled!

If the two objects are dependent of each other - maintain them together. Create a KeyValuePair<CancellationToken, Action> or a custom class to hold them both.

Is that lock necessary? I can't say if you really need the lock, as I don't know how would Task behave if ContinueWith is called twice on it:

If the last call overrides the previous call (in a thread-safe manner) - you could do away with your whole solution - it could come down to a one-liner :)
If calls are aggregated in an internal queue, and your manual maintenance of the last action is needed, you would have to synchronize your work.

Also, if you have only a single producer thread (only one thread which calls Queue) - you don't need to synchronize.


String parsing and saving ipaddress to file in Java

For starters you can simplify the first part by utilizing the fact that indexOf can accept a second character indicating start point. This would lead to something like the following:

// Find indices for IP-address
int startIndex = resp.indexOf('\"', resp.indexOf("ip=")) + 1;
int endIndex = resp.indexOf('\"', startIndex);

String ipString = resp.substring(startIndex, endIndex);

Secondly, you can simplify the conversion by utilizing the substring method a little, and improve a little on performance by using StringBuilder, like in the following:

StringBuilder ipAddress = new StringBuilder();
int lenIpString = ipString.length();

//get two and two bytes from hex string and append to ipaddress
if (lenIpString == 8) {
    long ipPart;
    for(int i = 0; i < lenIpString; i += 2)
    {
         ipPart = Long.parseLong(ipString.substring(i, i + 2), 16);
         ipAddress.append(String.format("%d.", ipPart));
    }

} else {
    throw new Exception("IP-string not long enough");
}

Note that this also does something if in the rare case the ipString is not 8 characters long. This also requires for the method to have an throws Exception added, and you should probably choose a better exception rather than Exception.

Finally your write to file can be enhanced to the following:

//write IP Address to file
File file = new File("SomeFilePath.txt");
FileWriter fileWriter;

try {
    fileWriter = new FileWriter(file);
    fileWriter.write(
        String.format("ip=\"%s\"",
                      ipAddress.substring(0, ipAddress.length() - 1)));

    fileWriter.flush();
    fileWriter.close();

} catch (IOException exception) {
    exception.printStackTrace();
}

Finally some general notes on coding style:

Consider splitting into three functions – These three code blocks could be extracted into (two or three) separate functions, where one serves as the output to the next. This would follow the single-responsibility principle of coding. One variant could change this function into:

void WritePublicIPAddressToFile(String resp, String filename)
{
   String ipAddress = findAndConvertIPAddress(resp);

   if (!ipAddress.isEmpty()) {
       writeIPAddressToFile(filename, ipAddress);
   }
}

Here I assume that the findAndConvertIPAddress() would return the empty string if the IP-address is not found as expected, and use that to bypass the file write if necessary. Now this function has a much clearer responsibility of finding and writing that IP-address to the file. No need to read lots of code to understand whats happening.
Use StringBuilder instead of String concatenation – In general try to avoid building new strings to a minimum, and use StringBuilder when building new strings, or a variation over String.format().
Consider having the filename as a parameter – Your code might be constructed specific for Code Review, but with a name like WritePublicIPAddressToFile I would expect that filename was one of the parameters.
Avoid using l as variable name – Especially in combination with i or 1, it can be really confusing to use lower-case L as a variable name. Use more descriptive names instead.


Your link has an assignment description, which I assume you have to follow, and I'll do so too. It says to use ES6 and class, but you have only used class for one of these, and even then you still use .prototype. You also shouldn't be using var, use let and const instead.

Comment class

Use class syntax. Save the image object instead of the imageId. Make the findImage function. commentEl should return a string, not a jQuery object.

class Comment {
    constructor(imageId, text) {
        this.id = Comment.all.length;
        this.image = this.findImage(imageId);
        this.text = text;
        Comment.all.push(this);
    }

    findImage(imageId) {
        const image =  Image.all.find(image => image.id === Number(imageId));
        image.comments.push(this);
        return image;
    }

    commentEl() {
        return `<li id='comment-${this.id}'>${this.text}</li>`;
    }
}

Comment.all = [];

CommentsController class

Use class syntax. Remove $addCommentForm since it's never used. addCommentFormListener doesn't add a listener, it is a listener (or handler, if you will). init is the one actually adding the listener. render can be simplified, since part of it is being done elsewhere. It is also being used like a static method.

class CommentsController {
    constructor() {
        this.addCommentFormListener();
    }

    addCommentFormListener() {
        $(".add-comment").each((index, element) => {
            element.addEventListener("submit", commentFormHandler);
        });
    }

    static render(commentObject) {
        const commentList = $(`#comments-${commentObject.image.id}`);
        commentList.append(commentObject.commentEl());
    }
}

// This could also be part of the class
function commentFormHandler(e) {
    e.preventDefault();
    const image = $(this).closest(".image");
    const imageId = Number(image.find("ul").attr("data-id"));
    const commentForm = $(this).find('input[name="comment-description"]')
    const commentContents = commentForm.val();
    if (commentContents.length) {
        const newComment = new Comment(imageId, commentContents);
        CommentsController.render(newComment);
        commentForm.val("");
    }
}

I'm not a fan of the way you're getting the imageId and comment. It's tied too much to the DOM and a bit confusing. But that's beyond this question.


Dynamically generating a HTML option list using Angular.js

I think it's a bad idea for several reasons:

It is possible to have an empty data set in real-world app but it should not affect your sorting options in any way.
It is possible to have some optional fields or fields that aren't suit for sorting - images, additional description (original step-4 actually has such field) etc
You should have a full control over what you're displaying and being able to change it with ease.
Pretty titles instead of field names 'as is' look much better.
In case of a huge list of options you may need to group them using 'disabled' options as delimiters.

The main idea is to keep the balance between decoupling and ease of reusability and extensibility of your functionality. One of solutions is to create an object that describes the way particular data can be sorted. You can implement it as following, for example: http://jsfiddle.net/ocLrt7vp/

Adding sorting options to phones

$scope.phones =
{
    sorting: [
        {title:"---Name---", disabled:true},
        {sortQuery: "name", title: "By name: A-Z"},
        {sortQuery: "-name", title: "By name: Z-A"},
        {title:"---AGE---", disabled:true},
        {sortQuery: "-age", title: "New first"},
        {sortQuery: "age", title: "Old first"}
    ],
    data: [
        {'name': 'Nexus S',
            'snippet': 'Fast just got faster with Nexus S.',
            'age': 2010,
            androidVersion:"Unknown"},
        {'name': 'Motorola XOOM™ with Wi-Fi',
            'snippet': 'The Next, Next Generation tablet.',
            'age': 2012,
            weight: 708},
        {'name': 'MOTOROLA XOOM™',
            'snippet': 'The Next, Next Generation tablet.',
            'age': 2011}
    ]
};

And changing index.html as following

    Search: <input ng-model="query">
    Sort by:
      <select ng-model="orderProp">
          <option value="{{sorting.sortQuery}}" ng-repeat="sorting in phones.sorting"
                  ng-selected="sorting.sortQuery == orderProp"
                  ng-disabled="sorting.disabled">{{sorting.title}}</option>
      </select>

        {{phone.name}}

{{phone.snippet}}

Weight: {{phone.weight}}g

Android Version: {{phone.androidVersion}}g

On the other hand detailed configuration may appear to be excessive for a regular real-world site. As well as passing data that changes once or two in a lifetime with each request should be considered as an example of a bad practice. You can achieve this behaviour in a number of different ways, better ways, but the goal of this comment is to share my vision with you, hope it helps :)


Android View Controller: Precondition vs ClassCastException

This is a relatively new area in Java, and best practice is not as well established....

... but, as I think about it, I think your reviewer has a point.

In your code base, consistency counts for a lot. If you check all your preconditions in a consistent way, and are disciplined about it, it will make a number of things easier to manage and maintain:

logs will be consistent
Exceptions will have more meaningful messages
Programmer's expectations are clearly shown

So, if the suggestions from your reviewer are consistent with the common-practice at your location, then, absolutely, do them.

Even if they are not common practice, still do them.

But, I have some comments to come after a small diversion.....

  You are correct that Spinner.class.cast(...) was introduced with Generics. The main purpose of this method appears to be related to the return value of methods with a Generic return type or where generic erasure makes internal manipulation of the data impossible without some help from the class (i.e. it counteracts the effects of erasure).

  These methods (or the class they are in) are supplied with an instance of the generic class, and they then use that class instance to cast the value.... for example, in Collections.checkedList(....). It is unusual to see this method (cast()) referenced from a static context Spinner.class.cast(value) when a simple (Spinner)value will suffice.

  On the other hand, it is interesting that, if you have multiple values being cast on a single line of code, the ClassCastException stack trace for (Spinner)value will be different to the trace for Spinner.class.cast(value). I need to verify this, but it may make traces slightly more useful.

  So, Spinner.class.cast(value) is not exactly the same as (Spinner)value.

Now, having said that, I can understand why Spinner.class.cast(...) may be recommended, but then I would have to question why Preconditions.checkArgument(view instanceof Spinner, ...) was recommended....

The view instanceof Spinner is logical to me, but, given the context of using Spinner.class.cast() I would also suggest that you should use Spinner.class.isInstance(view) as well.

If you are going to use these methods then I would suggest consistency.

Finally, I think that, unless there is the intention to turn this class in to a more generic-based one, that using the cast(...) and isInstance(...) is redundant. I would prefer the traditional (Spinner)view and view instanceof Spinner.

But, I fully agree that if you are going to check pre-conditions, that separating out the precondition check for instanceof is a good idea (although I would add the word 'The' to the beginning of the message).

So, if it were me, I would (given the context), suggest a compromise:

@Override
public void setView(@Nonnull View view) {
    super.setView(view);

    Preconditions.checkNotNull(view, "The view provided is null");
    Preconditions.checkArgument(view instanceof Spinner,
            "The view provided was not a Spinner view");
    mView = (Spinner)view;
}


Filter options of select box using input box value

I would start by moving the search term into the function definition, to save having to look up the DOM element. So I would change in the HTML

 <input type="text" id="search" name="search" style="margin: 10px;width: 165px;" onkeyup="filter(this.value)">

And then have function be defined with keyword as a parameter.

function filter(keyword) {
  ...
}

The other main change I would make is to use string.prototype.startsWith rather than substring checking, this is more explicit about what is trying to be done, and saves having logic to handle the empty string.

Also, rather than an If statement and then setting style.display, the display is set with either 'list-item' or 'none' with the ternary operator.

This leaves the function as

function filter(keyword) {
    var select = document.getElementById("select");
    for (var i = 0; i < select.length; i++) {
        var txt = select.options[i].text;
        var include = txt.toLowerCase().startsWith(keyword.toLowerCase());
        select.options[i].style.display = include ? 'list-item':'none';
    }
}

A further improvement you might want to look at may include moving the select element selection outside of this function to improve re-use.


I don't see what could be causing ever-decreasing performance since the only state outside the main loop is a counter, but adding calls to memory_get_usage as @jsanc623 recommends would help with that.

But you can definitely improve the performance by avoiding the loop over $results for every URL returned. Take advantage of PHP's array which is a hash table providing O(1) lookup.

First, make the URL the key for the results array.

foreach ($items as $item) {
    if ($item->img !== '') {
        $url = $item->img;
        $results[$url] = array(
            'id' => $item->id,
            'url' => $url,
            'size' => null
        );
        $rollingCurl->get($url);
    }
}

Next, use isset instead of array_search and looping.

// foreach ($results as $key => $value) { ... } becomes

$url = $request->getURL();
if (isset($results[$url]) {
    $results[$url]['size'] = $length;
    File::append($filePath, $results[$url]['id'] . ',' . $length . "\r\n");
}

Since you're placing each URL into the array before making the GET request, the if isn't even necessary.

Separately, you can delay writing to the file until the end of the inner loop so you write one big chunk rather than one thousand tiny chunks. It may be that I/O is more costly, and perhaps you're getting killed by seeking to the end of an ever-growing file? Seems unlikely but maybe after a million writes it adds up.

General Review

There are a few things that could be cleaned up here as well.

Consistent formatting: put your opening brace on the same line or the next, but do it consistently.
Blank lines before the closing brace seem misplaced to me. Use blank lines to logically group related code, though functions are preferred to whitespace.
Simplify testing if the image URL exists

if ($item->img !== '')

can be simplified to

if ($item->img)

to skip null values as well. Even if the field cannot be null, it's still easier to read.


Return different type of response based on Accept header

I don't know Akka-Http API well enough, but it looks like the if condition is misplaced. I think that it can be substituted with a matcher under case stories:

optionalHeaderValueByName("Accept") { contentType =>
  complete {
    NewsService.getNewsList().map {
      case stories: List[Story] => {
        contentType match {
          case Some(protoEncode) =>
            HttpResponse(entity = HttpEntity(ContentType(protoEncoding), StoryList(stories).toProto().build().toByteArray))
          case None => StoryList(stories)
        }
      }
    }
  }
}

It seems that it is a bit too deeply nested, but at least there is no repetition on NewsService.getNewsList().map.


I'd write the error handling this way:

def render(self, request):
    operations = {
        'POST': 'create',
        'GET': 'read',
        'PUT': 'update',
        'DELETE': 'delete',
    }
    if request.method not in operations:
        response = {
            'success': False,
            'error': 'InvalidRequestMethod',
            'error_message': ("Valid request methods: %s" % (', '.join(operations.keys()))),
        }
        request.setResponseCode(http.NOT_ALLOWED)
    else:
        response = {'success': True}
        ...
    return json.dumps(response)

Note the changes:

Since the error handler is simpler than the main processing code, put it first to get it out of the way.
if request.method not in operations reads better than if request.method not in operations.keys() and might be slightly more efficient.
Reuse operations.keys() for the error message.
Set HTTP status 405 ("Method Not Allowed").  (The constant is in twisted.web.http.)

In KeyValueStorage, I suggest raising the standard KeyError instead of making your own exception classes.


Favorite Game List utilizing vectors and iterators

Unused headers
As far as I can tell, nothing from the following headers is actively being used, so they shouldn't be included.

<ctime>
<cctype>
<cstdlib>

using namespace std
While it's probably not quite as bad using it inside a .cpp file instead of a header, it's generally seen as a code smell.
Variable usage
There are some variables that are declared at the begin of main, but only used further down (if at all, myIterator appears to not be used at all). This makes it harder to keep track of variables.
Magic numbers/literals
There are a lot of numbers/string literals, whose intention is not obvious in all cases. Examples include values 1 to 4 for input choices, or strings like "Your Games".
One way of dealing with these so called magic numbers is to put them into adequately named enums, constants or variables.
Container choice
There doesn't seem to be any dependency on actually keeping the order of the games intact. In addition, a small oversight (it is possible to add the same game twice) leads me to suggest that maybe a different container would be a better fit: std::unordered_set.
std::unordered_set allows us to insert and remove items with amortized \$\mathcal{O}(1)\$ runtime complexity, as well as to ignore duplicates.
Iterators or ranged for loops?
Generally, I prefer ranged for loops over "manual" iterator loops if the code isn't requiring some specific iterator behavior. Since this isn't the case here, I would suggest using ranged for loops for ease of reading.
Prefer smaller functions
Generally, it is easier to work with smaller functions: There is less mental overhead due to shorter code, fewer variables and narrower scope. Additionally, it allows for code reuse, which might reduce code duplication.
While the given code is small enough that these concerns might not matter right now, it will become a lot more obvious once additional logic like formatting, input handling or similar gets added.
Error checking
Neither user inputs nor results of calls to std::find are being checked for invalid values. This means I can easily cause errors inside the program (or crash it) by just entering weird stuff, or trying to remove non-existing entries.
Summary
Using all these suggestions, a cleaned up version could look like this:
#include <iostream>
#include <string>
#include <unordered_set>

enum class input_choices : int {
    add = 1,
    remove,
    list,
    exit
};

std::ostream& operator<<(std::ostream& output, input_choices choice) {
    output << static_cast<int>(choice);
    return output;
}

std::istream& operator>>(std::istream& input, input_choices& choice) {
    int temp = 0;
    input >> temp;
    choice = static_cast<input_choices>(temp);

    return input;
}

namespace messages {
    static const auto menu_header = "Menu";
    static const auto option_add = "Add a game to the list";
    static const auto option_remove = "Remove a game from the list";
    static const auto option_list = "Show all games on the list";
    static const auto option_exit = "Exit the program";
    static const auto enter_menu_choice = "Your choice: ";

    static const auto enter_game_to_add = "Enter the Game Name to add";
    static const auto enter_game_to_remove = "Here is the list of games enter the one to remove";
    static const auto list_header = "Your games";
    static const auto quitting = "Exiting program...";
    static const auto invalid_choice = "Unknown menu option";
}

class game_list_menu {
    std::unordered_set<std::string> games;

public:
    void add_game() {
        const auto game = enter_game(messages::enter_game_to_add);
        games.insert(game);
    }

    void remove_game() {
        print_games();

        const auto game = enter_game(messages::enter_game_to_remove);
        games.erase(game);
    }

    std::string enter_game(std::string_view prompt) const {
        std::cout << prompt << ": ";

        auto game = std::string{};
        std::cin >> game;

        return game;
    }

    void print_games() const {
        std::cout << "\n" << messages::list_header << ":\n\n";

        for(auto& game : games) {
            std::cout << "\t" << game << "\n";
        }
    }

    void print_menu() const {
        std::cout << "\n" << messages::menu_header << "\n\n";

        print_choice(input_choices::add, messages::option_add);
        print_choice(input_choices::remove, messages::option_remove);
        print_choice(input_choices::list, messages::option_list);
        print_choice(input_choices::exit, messages::option_exit);

        std::cout << "\n" << messages::enter_menu_choice;
    }

    void print_choice(input_choices choice, std::string_view description) const {
        std::cout << "\t" << choice << ": " << description << "\n";
    }

    void main_loop() {
        auto choice = input_choices::exit;

        do {
            print_menu();

            std::cin >> choice;

            switch(choice) {
            case input_choices::add:
                add_game();
                break;
            case input_choices::remove:
                remove_game();
                break;
            case input_choices::list:
                print_games();
                break;
            case input_choices::exit:
                std::cout << messages::quitting << "\n";
                break;
            default:
                std::cout << messages::invalid_choice << "\n";
                break;
            }
        } while(choice != input_choices::exit);
    }
};

int main() {
    auto menu = game_list_menu{};
    menu.main_loop();
}

Can you see how you can easily tell what each function does or what the meaning of each number/literal is?


You said to ignore getWeekStart(), but I'm afraid I can't do that.  It appears that the intention of getWeekStart() is to take a date string (in YYYY-MM-DD form) and find the Sunday that starts the week (in YYYY-MM-DD form).  However, depending on the time zone in which the code is executed, it may actually find the Monday, or possibly a Saturday instead.

The problem is that

new Date("YYYY-MM-DD") interprets the date as a UTC timestamp:

  Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

date.getDay() returns the day of the week for the specified date according to local time, where 0 represents Sunday.
date.toISOString() works in UTC:

  The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

For the code to be reliably correct, you must work consistently in UTC — in other words, call date.getUTCDay() instead.

Furthermore, I'd rename getWeekStart() to weekStart().  The "get" prefix implies that you are fetching something that already exists.  However, you are actually computing something, so the prefix is superfluous, perhaps even misleading.


I've researched for days and cannot grasp MINIMAX, or think of ways to make this AI better.

You can't really do MINIMAX without having an evaluation function. But even then, minimax is a bit complicated, but you could try something simpler:
Evaluation function
Make any function satisfying

f(state) = +A_LOT, if I win
f(state) = -A_LOT, if I lose
f(state) is bigger when the position looks better for me

Here, "looks better" simply means something like "me having 2 in a row is good", "me having 3 is even better". Just count things you believe are good.
Game tree search
You look at immediately wining turns, this is good. You also try to look at places where the other player can immediately win, this is also good. But you did it wrong (see below) and you don't do a real search.
A game tree search would mean, you do your hypothetical turn and then let the opponent try all moves (and so on). This can be as simple as two nested loops...
for all your turns {
  do your turn
  return if your won
  lost = false
  for all opponent's turn {
    do his turn
    lost = true if he won
    undo his turn
    break if lost
  }
  remember your turn as bad if lost
  undo your turn
}

Now you either returned with a winning move or remembered some bad moves or got no information at all. The further process should be obvious (winning move is clear, bad moves are to be avoided, that's all you know).
This can be generalized easily by using one more loop... you get one step smarter. And one more etc... however, a real depth search can go arbitrary deep, but try this for the start.
Combination
When going deeper, try using your evaluation function. This is still far from really smart, but it should be better than each idea alone.
Review
Player[][] hypothetical = state;

This looks like you'd have a state and an hypothetical state, which is not true, as it's the same array. So remove it to avoid confusion.
Player opponent = (player == Player.PLAYERX ? Player.PLAYERO : Player.PLAYERX);

Player should implement a method theOther() doing exactly this.
if (getWinner(hypothetical, r, c) == opponent)
        return c;

This alone is right, but it's in the same loop as finding your winning move. WRONG! If you can win at r=3 and the opponent can win at r=2, you'll play at r=2. You seem to be so scared of losing so that you give up a sure immediate win!
    if(player==opponent)
        return c;

WTF?
    }
}

    return (new Random()).getBestColumn(state, player);
}
}
}

WOW! So many closing braces and so nicely aligned...
The random move selection is fine if you don't know any better, but as I recently checked java.util.Random, it did not implement getBestColumn. This were a place for your evaluation function.


Collect all items containing a word to a Multimap

Well, if your items has no null elements, you can use ImmutableSetMultimap#flatteningToImmutableSetMultimap collector and it's own inverse method instead of calling utility methods.

return items.stream()
        .collect(flatteningToImmutableSetMultimap(
                i -> i,
                i -> i.wordSet().stream()
        ))
        .inverse();

It's a bit more terse (note the static import, which in my team we agreed is acceptable, although we normally don't use static imports) as it repeats looong class name in method name) and gives you immutable multimap right away.

If some "flattening" version of Multimaps#index existed, you could have also used it, but there's no such method right now unfortunately.


Implementing quicksort with pivot of first, median or random

quickSortCounter is reset too often
If the goal of the program is to count compares, the counter you are using is being reset in the wrong place.  Right now, you are going to end up with only the number of compares in the last call to partition(), which will likely be close to 0.  You need to move the quickSortCounter = 0 line to right before you call recursiveQuickSort().  That way you will add up all the compares in the entire sort.
You can also do it a different way without using a static variable.  You just need to have partition() be able to return the count to its caller.  One way of doing this would be to have partition() return an int [2] (one int for the partition index and the other int for the number of compares).  Another way is to pass an int [1] or Integer variable into partition() and write the compare count into that variable before returning.
Naming
One thing confused me about your variable names.  You used array as you array everywhere, but then you called it collectionArray in partition().  Why "collection"?


It might be better to treat the credit card number as a string. In the C programming language a string is a null terminated array of type char or character. This would remove all the division in the program to get each character. It would also allow the program to detect if any non-numeric characters were entered.

To get the actual numeric value of a character you would subtract '0' from the numeric character. For a single character this would always give you a value between zero and nine.

Variable Names
Having variables i1 through i16 is a very good indication that i should be an array, this is also true of t.

Having single character variable names is generally frowned upon except for loop control values. A single character really doesn't tell anyone reading or modifying the code what the variable really is or does. It isn't really clear in the program what i or t represents. While number is longer, it might be better if it was credit_card_number.

Basic Principles When Writing Code
One of the earliest principles all programmers learn is Don't Repeat Yourself, usually shortened to DRY code. Basically anytime you have code that repeats it would be better to put it into a loop or a function where the code is reused.

One example of repeating code from the question is :

    if (tN > 9)
    {
        tN = tN - 9;
    }

This code can be made into a function:

int adjust_t_value(int tN)
{
    if (tN > 9)
    {
        return tN - 9;
    }
    else
    {
        return tN;
    }
}

If the variable t was an array, then code in the program could be reduced to

    for (int t_count = 0; t_count < N; t_count++)
    {
        t[t_count] = adjust_t_value(t[t_count]);
    }

There is a second form of the if statement that could also make the code shorter, it is generally covered in the later part of any C programming course

    tN = (tN > 9)? tN - 9 : tN;

This single statement is equivalent to the function above.

A second example of repeating code is the division to reduce each digit in the credit card number to a single number, this could also be put into a loop. The divisor could be reduced in each iteration of the loop if the algorithm sticks with using numbers.

A second principle that should be taught early but is part of more complex programming is the Single Responsibility Principle which states that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated within the function, module or class. This reduces the size of functions which allows functions to be more readable, maintainable and easier to debug. This would mean breaking the main() function into two or three sub functions to reduce the complexity of main.

Use Vertical Spacing to Make the Code More Readable
The code in the question has the if (tN > 9) on only two lines, it might be more readable if it was 4 lines as shown above.


Goldbach's Conjecture using Sieve of Eratosthenes

Efficiency

Post-processing the results from the Sieve of Eratosthenes (isComposite) to produce primes is actually counterproductive.  If the findPairs() code just has a list of primes to work with, then it cannot quickly answer "is n a prime?" for any given n.  Hence, you need to try all pairs of primes, making findPairs() O(|P|2), where |P| is the size of the set of primes.  And that's in addition to the work needed to find those primes.

You would be better off using the raw isComposite array.  Then, for any given p, you can immediately find out whether input - p is also prime.

In your Sieve of Eratosthenes loop, you can use addition instead of multiplication.

Code organization

Mixing input/output code with computation code is poor practice.  I suggest using an Iterator<Integer> to iterate through the results.  Then you can use a nice simple loop in main() to print the results.

Instead of System.out.println(… + … + … + …), use System.out.printf(), which is more readable.  (Actually, System.err would be a better place to send diagnostic output.)

Suggested solution

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class GoldbachSums implements Iterable<Integer> {
    private final int sum;
    private final boolean[] ineligible;

    public GoldbachSums(int sum) {
        if (sum <= 2) {
            throw new IllegalArgumentException("Number must be greater than 2.");
        }
        if (sum % 2 > 0) {
            throw new IllegalArgumentException("Number must be even.");
        }
        this.sum = sum;
        this.ineligible = oddSieveOfEratosthenes(sum);
    }

    private static boolean[] oddSieveOfEratosthenes(int max) {
        boolean[] ineligible = new boolean[max];
        ineligible[1] = true;
        for (int i = 3; i * i < max; i += 2) {
            if (! ineligible[i]) {
                for (int j = i * i; j < max; j += i) {
                    ineligible[j] = true;
                }
            }
        }
        return ineligible;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            // 4 is the only sum whose decomposition involves an even prime
            private Integer n = (sum == 4) ? 2 : computeNext(sum - 1);
            private final int halfSum = sum / 2;

            private Integer computeNext(int n) {
                for (int i = n; i >= halfSum; i -= 2) {
                    if (!ineligible[i] && !ineligible[sum - i]) {
                        return sum - i;
                    }
                }
                return null;
            }

            @Override
            public boolean hasNext() {
                return n != null;
            }

            @Override
            public Integer next() {
                if (n == null) {
                    throw new NoSuchElementException();
                } else try {
                    return n;
                } finally {
                    n = computeNext(sum - n - 2);
                }
            }

            // For compatibility with Java < 8
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    public static void main(String[] args) {
        try (Scanner scan = new Scanner(System.in)) {
            System.out.print("Please input an integer to decompose as the sum of two primes: ");
            int input = scan.nextInt();

            long startTime = System.nanoTime();
            GoldbachSums goldbach = new GoldbachSums(input);
            long duration = System.nanoTime() - startTime;
            System.err.printf("\nSieve of Eratosthenes took: %d ns or %f seconds.\n",
                              duration, duration * 1e-9);
            duration = System.nanoTime() - startTime;
            for (int addend : goldbach) {
                System.out.printf("%d + %d = %d\n", input - addend, addend, input);
            };
            System.err.printf("\nThis program took: %d ns or %f seconds.\n",
                              duration, duration * 1e-9);
        } catch (IllegalArgumentException badInput) {
            System.out.println(badInput.getMessage());
        }
    }
}


Longest repeating and non-overlapping substring

Includes and namespaces

First of all, bits/stdc++.h isn't part of the C++ standard. Instead, only include the files you actually need:

#include <iostream>
#include <string>

Next, it's considered bad practice to use using namespace …, so let's get rid of it.

Your function f

There are several things we can improve here. First of all, it's name is ambiguous. What does f do? It calculates the length of the longest repeating and non-overlapping substring. Let's give it a better name and type:

size_t longest_repeating_substring_length(const std::string & str){
    …
}

'But wait', I here you say. 'That's not my function anymore'. It sure isn't. The problem with your function is that it's possible to use it wrong, e.g.

f("123", 100, 0, 0,mx_len);
//       ^^^ oh oh

It's a fine way to implement the dynamic approach, but it shouldn't be available to the user by default. Therefore, let's "hide" it:

namespace detail {
    void longest_repeating_substring_length(
        const std::string & str, size_t i, size_t j, size_t len, size_t & mx_len
    ){
        mx_len = std::max(mx_len,len);

        if(j >= str.length()) {
            return;
        }
        if(str[i] == str[j] && (j - i) > len) {
            longest_repeating_substring_length(str,i+1,j+1,len+1,mx_len);
        }
        longest_repeating_substring_length(str,i+1,j+1,0,mx_len);
        longest_repeating_substring_length(str,i,j+1,0,mx_len);
    }
}

Why is the const std::string& necessary? First of all, const will make sure that we don't accidentially change your string in our function. And & will get rid of additional copies that would happen throughout the execution.

Note that we can get rid of mx_len:

namespace detail {
    size_t longest_repeating_substring_length(
        const std::string & str, size_t i, size_t j, size_t len
    ){
        size_t mx_len = len;

        if(j >= str.length()) {
            return mx_len;
        }
        if(str[i] == str[j] && (j - i) > len) {
            mx_len = longest_repeating_substring_length(str,i+1,j+1,len+1);
        }
        mx_len = std::max(mx_len, longest_repeating_substring_length(str,i+1,j+1,0));
        mx_len = std::max(mx_len, longest_repeating_substring_length(str,i,j+1,0);
        return mx_len;
    }
}

Depending on which variant you'll use, you end up with the following code:

namespace detail {
    void longest_repeating_substring_length(
        const std::string & str, size_t i, size_t j, size_t len, size_t & mx_len
    ){
        mx_len = std::max(mx_len,len);

        if(j >= str.length()) {
            return;
        }
        if(str[i] == str[j] && (j - i) > len) {
            longest_repeating_substring_length(str,i+1,j+1,len+1,mx_len);
        }

        longest_repeating_substring_length(str,i+1,j+1,0,mx_len);
        longest_repeating_substring_length(str,i,j+1,0,mx_len);
    }
}

size_t longest_repeating_substring_length(const std::string & str){
    size_t max_length = 0;
    detail::longest_repeating_substring_length(str, 0, 1, 0, max_length);

    return max_length;
}

Easy-to-use function at global namespace, and function that can possibly get used in a wrong way hidden away in detail.

Which brings us to your new main:

int main(){
    std::string s;
    std::cin >> s;

    std::cout<< longest_repeating_substring_length(s) <<std::endl;

    return 0;
}

Less recursive calls

To get the number of recursive calls down, we have to ask ourselfs "how large can mx_len get in that particular call?"

Well, if we start at position I and J, the maximum we can get is limited by J-I (since we may not overlap both strings) and str.length() - J (since there are only so many characters starting from the second position.

So let's calculate the maximum length we could get for a string:

#include <cassert>
size_t max_length(size_t string_length, size_t first_pos, size_t second_pos) {
    assert(first_pos <= second_pos);
    assert(second_pos <= string_length);

    return std::min(second_pos - first_pos, string_length - second_pos);
}

size_t max_length(const std::string &s, size_t first_pos, size_t second_pos) {
    return max_length(s.size(), first_pos, second_pos);
}

Now we have a method to determine in \$\mathcal O(1)\$ whether we should continue a recursive call:

namespace detail {
    void longest_repeating_substring_length(
        const std::string & str, size_t i, size_t j, size_t len, size_t & mx_len
    ){
        // i is always less than j, otherwise we broke our algorithm
        assert(i <= j);

        // the current max
        mx_len = std::max(mx_len,len);

        if(j >= str.length()) {
            return;
        }

        if(str[i] == str[j] && (j - i) > len && max_length(str,i,j) <= mx_len) {
            longest_repeating_substring_length(str,i+1,j+1,len+1,mx_len);
        }

        if(max_length(str, i + 1, j + 1) > mx_len){
            longest_repeating_substring_length(str,i+1,j+1,0,mx_len);
        }
        if(max_length(str, i, j + 1) > mx_len){
            longest_repeating_substring_length(str,i,j+1,0,mx_len);
        }
    }
}

Further remarks

Your code could get a lot more readable if you used more whitespace. Also, for difficult functions, you really want to add comments and/or documentation.


AudioMetaTagger: recursively read files and gather metadata

welcome to code review! Here are some thoughts:

Casting

To get rid of the casting you can use generics (see also: https://docs.oracle.com/javase/tutorial/java/generics/types.html) like so:

public static Collection<File> checkData(File dir){
    Collection<File> files = FileUtils.listFiles(
        dir,
        new RegexFileFilter("^(.*mp3)"),
            DirectoryFileFilter.DIRECTORY
        );
    return files;
}

This way in your main function you can avoid the casting:

 Collection<File> files = checkData(dir);
 for(File file: files) {

This is to be preferred, as casting is to be avoided when possible (Interesting related discussion: https://stackoverflow.com/questions/4167304/why-should-casting-be-avoided).

Code

Why initialize a variable first and then assign the value? You can easily do it in one line, which is nicer to read:

AudioFile audioFile = AudioFileIO.read(file);

Formatting

On the nitpicky side, you should take a look at how code formatting is usually done in java: https://docs.oracle.com/javase/tutorial/essential/io/formatting.html

Using decent indentation and spacing allows for easier reading of the code. The best advice here is probably using the auto-formatter of your IDE (eclipse, intelliJ, etc.), as it is tedious to do it by hand.

Performance

Judging from your code, I don't see any specific place to make it a lot faster using the library. It looks like the library reads the entire file to get the metaData, which is of course very I/O intense, and therefor slow.
More advanced libraries like JAudioTagger (http://www.jthink.net/jaudiotagger/examples_read.jsp) might be able to do this in a more efficient way.

Hope this helps!


First we don't review:

ProductType
Vendor
IProductTypeService (just a little)
IVendorService
IRepository (just a little)
what is _memorxCahceService? I will use ObjectCache.

What we need to discuss?

A generic service implementation which will contain the common methods and implementation.

BaseService

We will need a class which can be the bridge to the repository and the cache so define it aas BaseService. T means we will use it in different repository+cache combose int a generic way. No black magic here, move on.

First we need to extract the common things from the two service implementation in you question:

get a cache key
try load from cache the data

public abstract class BaseService<T>
{
    private ObjectCache ObjectCache { get; set; }
    private IRepository<T> Repository { get; set; }

    protected BaseService(IRepository<T> repository)
        : this(MemoryCache.Default, repository)
    {
    }

    protected BaseService(ObjectCache objectCache, IRepository<T> repository)
    {
        ObjectCache = objectCache;
        Repository = repository;
    }

    protected virtual string GetCacheKey(string suffix, int sectionId = -1)
    {
        return GetType().Name + "_" + suffix + sectionId;
    }

    protected virtual async Task<ICollection<T>> GetAllAsyncValueFactory()
    {
        return await Repository.GetAllAsync();
    }

    public virtual async Task<ICollection<T>> GetAllAsync(int sectionId = -1)
    {
        var key = GetCacheKey("GetAllAsync", sectionId);

        var list = ObjectCache.Get(key) as ICollection<T>;

        if (list == null)
        {
            return ObjectCache.AddOrGetExisting(key, await GetAllAsyncValueFactory(), new CacheItemPolicy
            {
                //TODO: define cache policy
            }) as ICollection<T>;
        }

        return list;
    }
    }

What do we here is that we defining in the constructor what we will need: a repository and an ObjectCache but we could you a default MemoryCache instance if we don't get anything other.

The main thing is i have extracted all the logic you are using commonly in your code but with a generic implementation (hint: don't use IList is a dirty interface). Every method is virtual so they can be easily override in derived classes you you can define different cache keys or you can tell how you would want to get the data from the current repository.

Interface implementation

Because the generic base class we only need to define the constructors in our interface implementation classes as you can se:

public class ProductTypeService : BaseService<ProductType>, IProductTypeService
{
    public ProductTypeService(ObjectCache objectCache, IRepository<ProductType> repository)
        : base(objectCache, repository)
    {
    }

    public ProductTypeService(IRepository<ProductType> repository)
        : base(repository)
    {
    }
}

The constructor implementation will be different based on your unknown needs.


a condition to be met like if (someBoolean == true) can be simplified to if (someBoolean). For reverse check use the Not operator ! like if (!someBoolean).
Dipsose() should not only call Close() but also get rid of session, sessionOptions and transferOptions by calling Dispose() if they implement IDisposible or at least setting them to null.
SendFile()

you should declare the variable as near as possible to its usage and instead of catching .. rethrowing the exception, let it bubble up the tree. So it can be simplified to

public TransferOperationResult SendFile(string SourceFile, string DestFile)
{
    return session.PutFiles(SourceFile, DestFile, false, transferOptions);
}

if comments don't add any value, like explaining why something is done (what is done should be explained by the code itself), they should be removed like

//public properties


Pointless member variables

session could be a local variable in the constructor. You use it once to get store and you don't reference it again.

unreadMessageCount is pointless, because you could replace it with unreadMessages.size() instead.

In the constructor, you assign inbox, but you also close it. I'm not really familiar with how javax.mail works, but usually, after you close something it tends to become unusable. If that's the case, then the inbox member is pointless.

Pointless member variables make your class design confusing, hard to read, and potentially buggy. Try to be minimalistic, and eliminate anything from your class that it doesn't really need.

Extract logger

The logging in your code can be simplified if you extract the Logger to a constant:

private static final Logger LOGGER = Logger.getLogger(EmailSession.class.getName());

// ...
LOGGER.warning("More than 100 messages");
// ...
LOGGER.log(Level.SEVERE, null, ex);

Extract methods

The constructor is too long. It's hard to read large chunks of code. You could extract some of the functionality there to private methods to make it more readable:

private List<Message> getMessages(Folder inbox, int messageCount) throws MessagingException {
    if (messageCount > 100) {
        LOGGER.warning("More than 100 messages");
        return Arrays.asList(inbox.getMessages(1, 100));
    }
    return Arrays.asList(inbox.getMessages());
}

private List<Message> getUnreadMessages(List<Message> messages) throws MessagingException {
    List<Message> unreadMessages = new ArrayList<>();
    for (Message message : messages) {
        boolean isUnreadMessage = true;
        for (Flags.Flag flag : message.getFlags().getSystemFlags()) {
            if (flag == Flags.Flag.SEEN) {
                isUnreadMessage = false;
                break;
            }
        }
        if (isUnreadMessage) {
            unreadMessages.add(message);
        }
    }
    return unreadMessages;
}

With these helper methods and the other suggestions above, you could simplify the constructor:

public EmailSession() {
    Properties props = new Properties();
    props.setProperty("mail.store.protocol", MyProps.getProperty("mail.store.protocol"));
    Session session = Session.getInstance(props, null);
    try {
        store = session.getStore();
        store.connect(MyProps.getProperty("mail.host"), MyProps.getProperty("mail.user"), MyProps.getProperty("mail.password"));
        inbox = store.getFolder(MyProps.getProperty("mail.foldername"));
        inbox.open(Folder.READ_ONLY);
        messageCount = inbox.getMessageCount();
        List<Message> messages = getMessages(inbox, messageCount);
        inbox.close(true);
        unreadMessages = getUnreadMessages(messages);
    } catch (NoSuchProviderException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    } catch (MessagingException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

I also moved inbox.close higher to close it immediately when you don't need it anymore.

Avoid wildcard imports

Wildcard imports like import java.util.* are considered bad practice. Try to avoid it, it's better to clean up all of these:

import java.util.*;
import java.util.logging.*;
import javax.mail.*;


Generate xyz coordinates of a tube made of multiple rings

Thanks for sharing your code.

For the generation of your z-coordinate you can write something like:

def generate_z_coordinate(n, x0, x1):
    """Generate the z-coordinate for the n first ring.
       :param n: the number of ring
       :param x0: x0 coordinate
       :param x1: x1 coordinate
       :return: A list of the z-coordinate for the n rings
    """
    tmp = 0
    rings = []
    for i in range(0,n):
        if i % 2 == 0:
            x = x0
        else:
            x = x1
        rings.append(np.ones(x.shape) * tmp)
        tmp += 2
    return rings

I used tmp because I lack a better name, but there is probably a better way to name it.

And saving in the csv:

def save(filename, rings, x0, y0, x1, y1):
    """Save rings coordinate into filename
       :param filename: Name of the file to save data in
       :param rings: list of z-coordinate for the rings
       :param x0: x0 coordinate
       :param y0: y0 coordinate
       :param x1: x1 coordinate
       :param y1: y1 coordinate
    """
    for i, elt in enumerate(rings):
        name = filename + str(i) + '.csv'
        if i % 2 == 0:
            x = x0
            y = y0
            z = rings[i]
        else:
            x = x1
            y = y1
            z = rings[i]

        np.savetxt(name, np.c_[x, y, z], delimiter=' ', fmt='%10f')

I am not sure it is more readable than your version but it's more scalable. Depend on what you need.

Also try to be consistant in your code and follow Python style guide(see PEP8):

write bLength = 1.6 instead of bLength=1.6
theta = np.linspace(0, 2 * np.pi, numPoints, endpoint=False)

You can use flake8 or black or PyLint to lint your code


Algorithm generating a unique ID based on client name

First, I would expect from a function named GeneratePID to return the generated ID and not to set it. (Nobody likes side-effects)

private string GeneratePIDforNewPoint(string pointName)
{
    if(pointName == null)
        return "error";

    var storedPIDs = _ds.GetPIDs(pointName[0]);
    var newPID = 0;
    if(storedPIDs.Count > 0) {
        var maximumStoredPID = _ds.GetPIDs(pointName[0]).Max();
        newPID = Int32.Parse(maximumStoredPID.substring(1)) + 1;
    }
    return pointName[0] + String.Format("{0:000}", newPID);
}


What to you thing about:

<?=label ?>  OR:
<?=function(arg1, arg2, arg3) ?>

PHP is already a template engine

Just write a wrapper around a include call and your template system is ready to use and more flexible than anything you could write.

That said, why to you match single lines? Please have a look at preg_replace_callback.

/\<\%\s*(.+?)\s*\%\>/

If you want to put the whitespace trimming in the callback and as you don't need to escape <>%, you could even use

/<%(.+?)%>/