First of all, welcome to codereview! It's nice to see that you are attending Python courses at University / highschool.

Styling

As you're at the beginning of the road, you should know that Python has a style-guide which is called PEP8. You can read there things like:

Naming conventions: function / variable names should be lower_cased
Comments: you should add a space after # (a single one is enough, it's not necessary to abuse it) when you comment out the code, you should avoid obvious comments and also try to write docstrings to each function
Maximum line length: lines should have a maximum length of 79 characters (this is debatable as some editors - like PyCharm suggests a maximum of 120).
Spacing: you should have two new lines between methods, and one whitespace around operators

That being said, your code after some styling might look like this:

import random as r

RPS = ["ROCK", "PAPER", "SCISSORS"]

def main():
    """This is the main function"""
    comp = computer_move()
    player = player_move()
    winner, tie = calc_winner(comp, player)
    disp_winner(winner, tie)

def computer_move():
    """The move made by the computer."""
    comp = r.choice(RPS)
    return comp

def player_move():
    """The move made by the user."""
    player = ""
    while not player in RPS:
        player = input("Choose your weapon(rock, paper, or scissors: ").upper()
    return player

def calc_winner(comp, player):
    """Determining a winner."""
    print("The computer chooses {0}.".format(comp))
    winner = None
    tie = False

    if player == comp:
        print("No winner.... Restarting....\n")
        main()
        tie = True
    elif (((comp == "ROCK") and (player == "PAPER")) or
          ((comp == "PAPER") and (player == "SCISSORS")) or
          ((comp == "SCISSORS") and (player == "ROCK"))):
        winner = True
    else:
        winner = False

    return winner, tie

def disp_winner(winner, tie):
    """Display the winner of the game."""
    if tie == True:
        print("")
    elif winner == True:
        print("You beat the computer!")
    elif winner == False:
        print("The computer beat you!")

main()

More about styling

Keep in mind that your comments should be succinct and explicit and should emphasise what the method does.

I usually put the main() function after the others because it comes more naturally when you read the code.

Give descriptive names to your functions / variables. Doing this will make the code speak for itself (more readable) and will make you remove unnecessary comments.

You only use random once. Don't give it an alias.

Equality vs Identity Comparisons

is is identity testing, == is equality testing.

You should use:

if tie is True:
    ...

Instead of:

if tie == True:
    ...

Or shorted:

if tie:
    ...

! Remember that if you use is, the result will be true if and only if the object is the same object. However, == will be true any time the values of the object are the same.

Testing for membership

You should write:

while player not in RPS:
    ...

Instead of:

while not player in RPS:
    ...

Tuples vs Lists

Because your RPS is not changing, I'd recommend you use a tuple instead. A couple of advantages of doing the above:

  Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it,
  use a tuple instead of a list.
  It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an
  implied assert statement that this data is constant, and that special
  thought (and a specific function) is required to override that.

Fix the bug

If the computer chooses scissors and you choose paper there won't be any result because you only test for half of the cases.

Choose your weapon(rock, paper, or scissors: paper
The computer chooses SCISSORS.

Process finished with exit code 0

I'll let you fix this. HINT (think of a suitable data structure that can make the things easier)

Double hint: maybe a dictionary?


HttpURLConnection response code handling

Readability
Let's reformat your code quickly:

    HttpURLConnection connection = null;
    boolean connected = false;
    outer: for (int retry = 0; retry <= RETRIES && !connected; retry++) {
        if (retry > 0) {
            log.warning("retry " + retry + "/" + RETRIES);
            Thread.sleep(RETRY_DELAY_MS);
        }
        connection = (HttpURLConnection) entries.openConnection();
        connection.connect();
        switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                log.fine(entries + " **OK**");
                connected = true;
                break; // fine, go on
            case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
                log.warning(entries + " **gateway timeout**");
                break;// retry
            case HttpURLConnection.HTTP_UNAVAILABLE:
                System.out.println(entries + "**unavailable**");
                break;// retry, server is unstable
            default:
                log.severe(entries + " **unknown response code**.");
                break outer; // abort
        }
    }
    connection.disconnect();
    log.severe("Aborting download of dataset.");

Fixed:

1-liners are hard to read:
  case HttpURLConnection.HTTP_UNAVAILABLE: System.out.println(entries+ "**unavailable**");break;// retry, server is unstable

spacing inside for-loop conditions:
  for(int retry=0;retry<=RETRIES&&!connected;retry++)

indentation - 1-space indentation is 'just wrong'™.

Functionality
Right, how does this code work? There are a few problems I can (now) see in here:

On HTTP_OK, it breaks out of the switch, then it exits the loop (because && !connected), and then immediately disconnects and logs a severe error? This can't be right?
HTTP_GATEWAY_TIMEOUT logs a warning.... great, but HTTP_UNAVAILABLE does a System.out.println

The InterruptedException handling is not shown here. There are articles on how to do this properly. Google up on that.
Suggestion
I recommend a sub-function, with a do-while loop (the following is a quick hack-up - untested):
private static final HttpURLConnection getConnection(URL entries) throws InterruptedException{
    int retry = 0;
    boolean delay = false;
    do {
        if (delay) {
            Thread.sleep(RETRY_DELAY_MS);
        }
        HttpURLConnection connection = (HttpURLConnection)entries.openConnection();
        switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                log.fine(entries + " **OK**");
                return connection; // **EXIT POINT** fine, go on
            case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
                log.warning(entries + " **gateway timeout**");
                break;// retry
            case HttpURLConnection.HTTP_UNAVAILABLE:
                log.warning(entries + "**unavailable**");
                break;// retry, server is unstable
            default:
                log.severe(entries + " **unknown response code**.");
                break; // abort
        }
        // we did not succeed with connection (or we would have returned the connection).
        connection.disconnect();
        // retry
        retry++;
        log.warning("Failed retry " + retry + "/" + RETRIES);
        delay = true;

    } while (retry < RETRIES);

    log.severe("Aborting download of dataset.");

}


Task.Factory.StartNew(async () =>

I don't see any expensive non-async operations here, so I would consider directly running this code on the UI thread. It would also mean that you don't have to use Dispatcher.RunAsync in AddToLibrary.

Getting the properties will stay asynchronous, so it shouldn't block the UI.

List<LocalAudio> tempList = new List<LocalAudio>();

You can use var here, since the type of the variable is clear.

All async methods should be named ending with Async, in your case, that means AddToLibraryAsync.

I don't know if this is going to help, but you might consider getting the music properties in parallel. For example (using Batch from MoreLINQ or your own implementation):

var files = await StorageHelper.GetFiles(KnownFolders.MusicLibrary);

foreach (var batch in files.Batch(50))
{
    IEnumerable<Task<LocalAudio>> propertiesTasks = batch.Select(async file =>
    {
        MusicProperties properties = await file.Properties.GetMusicPropertiesAsync();

        var title = string.IsNullOrWhiteSpace(properties.Title) ? file.Name : properties.Title;
        var artist = string.IsNullOrWhiteSpace(properties.Artist) ? file.Path : properties.Artist;
        return new LocalAudio { Title = title, FilePath = file.Path, Artist = artist, Duration = properties.Duration };
    });

    LocalAudio[] properties = await Task.WhenAll(propertiesTasks);

    AddToLibrary(properties); // I'm assuming AddToLibrary is no longer async
}

You seem to be worried that adding the data to your UI will take too long. The solution to that is to not show the user so much data. Some solutions to that are only showing one "page" of data at a time or using virtualization to not create more UI elements than necessary (I have no idea if or how well does virtualization work on UPW).

Another possibility is to use paging, virtualization or just showing only a limited number of items, and combine it with some form of filtering. That way, when a user is looking for a song, they for example can type its name, instead of scrolling though a long list.


Customizing color for the navbar of my Android app

You could actually name (i.e. wrap in a proper resource) the color you used there, and thus reference it easier in the future. Not only that, but properly defining resources is recommended for Android development, and depending on the tools you use, you might see them complaining if you don't.

Inside

/res/values/colors.xml

you could define yours as

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="my_amazing_blue">#6a9abd</color>
</resources>

and then reference it as

@color/my_amazing_blue

in the XML, or

Resources res = getResources();
int myAmazingBlue = res.getColor(R.color.my_amazing_blue);

in your Java code.

Also note that for Android, resource names are usually cased_like_this.


Assigning an array of different (but convertible) type to concurrency::array in C++AMP

As with almost any performance related question, the correct answer is probably to do some profiling to get solid answers.

That said, it strikes me as unlikely that attempting to do the copy in parallel will usually make much difference. In a typical case, copying to the accelerator takes place over a PCIe bus. In that typical case, even a single CPU core will have substantially higher memory bandwidth than that bus, so the copy will be a "hurry up and wait" situation; using more than one CPU will basically means hurrying even faster so you can wait even longer.

In the case of something like an AMD APU, the parallel copy stands at least a little more chance of improving performance. Even here I'd have substantial doubts though. In particular, a single core can still normally (more than) saturate the processor's bandwidth to main memory, so doing the copy in parallel still won't gain anything.

That leads us to a much more general conclusion: if your processing is memory bound to start with, parallel execution is unlikely to improve performance unless you do it on hardware that has multiple sockets and each socket has a separate memory controller. In this case, the code will probably still be limited by bandwidth to memory, but you've doubled the bandwidth to memory which can roughly double the speed of the code.


replacing characters in string one by one to create target string

As Tyler Flynn pointed out in a comment, you should flip the conditional from "equals" to "not equals" to avoid the (current empty) if branch:

if(source != safe) {
  console.log(source);
  safe = source;
}

I'd avoid extending the String prototype. The method you're adding is pretty generic, and could be reusable, so it's not a terrible thing to add, but still. Extending prototypes is generally considered bad form - not because it'll instantly break anything, but rather because if everybody did it, they might defined replaceAt in some other way, and break your code. Or your extension would break their code. So extending prototypes, while often tempting, should be considered carefully.
In this case, it'd be just as simple to have a replaceAt(string, index, character) function that you call with the string, instead of calling it on the string.

Other than that, you code seems OK. There are a ton of other approaches you could take, of course, but without some external metric to judge by, yours is as good as any other.

However, there's one issue which irks me a little: source is mutated. With your current code, you can't print the original string after the loop has run, because you've "lost" it - source just becomes equal to target. I'd keep source and target unaltered, and generate a third "result" string for each step instead.

This also points to an alternative approach: Instead of replacing characters, create a new string by glueing parts of the two others together.

var source = "Turtle Ham";
var target = "Ham Maker!";

var lastResult = null;

for(var i = 0; i <= source.length ; i++) {
  var result = target.substr(0, i) + source.substr(i);

  if(result != lastResult) {
    console.log(result);
  }

  lastResult = result;
}

This code doesn't even need a separate function or prototype extension, and doesn't mutate the input (source and target) strings. It also doesn't need an extra console.log to show the original; everything happens in the loop, which runs from 0 characters replaced to source.length (inclusive) characters replaced.


Interpret YYYYMMDD as the nth day of the year

As you already use pandas, you are right that there is no overhead on using Timestamps (the kind of objects returned by pd.to_datetime). But, as said in the documentation (help(pd.Timestamp)):

  Help on class Timestamp in module pandas.tslib:

  class Timestamp(_Timestamp)
 |  TimeStamp is the pandas equivalent of python's Datetime
 |  and is interchangable with it in most cases. It's the type used
 |  for the entries that make up a DatetimeIndex, and other timeseries
 |  oriented data structures in pandas.

So you may choose pd.Timestamp or Python's datetime.datetime interchangeably.

The simplest way to count days from January 1st of the same year is to build both objects and then substract each other to get the count of days separating them. Take care of adding one day to actually count January 1st as well:

date = pd.to_datetime('20170201', format='%Y%m%d')
new_year_day = pd.Timestamp(year=date.year, month=1, day=1)
day_of_the_year = (date - new_year_day).days + 1

Now, having this piece of code hanging around is not really of any use, so you should wrap it into a function for better reusability:

import pandas as pd

def date_to_nth_day(date, format='%Y%m%d'):
    date = pd.to_datetime(date, format=format)
    new_year_day = pd.Timestamp(year=date.year, month=1, day=1)
    return (date - new_year_day).days + 1

if __name__ == '__main__':
    print(date_to_nth_day('20170201'))

Using Python's datetime module, the function would look like:

def date_to_nth_day(date, format='%Y%m%d'):
    date = datetime.datetime.strptime(date, format=format)
    new_year_day = datetime.datetime(year=date.year, month=1, day=1)
    return (date - new_year_day).days + 1


Given two Binary trees, find whether the second is a sub tree of the first

Firstly, what's will all the p's? I guess they mean pointer? They are silly, get rid of them.

Consider these trees:

     [A]                     [A]
    /   \                   /  \
  [B]   [C]               [D]   [C]
 /
[D]

Your code will claim that the second tree is a subtree of the first. The problem is that you cannot check the left/right matching using issubtree because they need to be exact matches not subtrees. You need to seperate the subtree search from the matching:

int matches(tree * tree1, tree * tree2)
{
    if(tree1 == tree2) return 1;
    if(tree1 == NULL || tree2 == NULL) return 0;
    if(tree1->data != tree2->data) return 0;
    return matches(tree1->left, tree2->left) && matches(tree1->right, tree2->right);
}

int issubtree(tree *haystack, tree * needle)
{
    if(tree1 == haystack) return 0;
    if( matches(haystack, needle) ) return 1;
    return issubtree(haystack->left, tree2) || issubtree(haystack->right, needle);
}

For increased efficiency, we can look at the problem in another way. We can express a tree by its pre-order traversal. So for the first tree above we have:

A,B,D,(NULL),(NULL),(NULL),C,(NULL), (NULL)

We can reconstruct the original tree from this sequence. Additionally, a subtree will show up as a substring of this sequence. This means that we can view the subtree problem as the same as the substring search problem. That's a well studied problem and you can view various algorithms for it here: http://en.wikipedia.org/wiki/String_searching_algorithm


C++ member function wrapper for interfacing with C APIs

After using the code for a while I noticed the following changes could be used:

I don't need instance_type_helper class. Result type will be taken out of the function type. Thus, instance_call_helper turns into following:

template<
    typename Function,
    Function F
>
struct instance_call_helper;

template<
    typename Result,
    typename Base,
    typename... Args,
    Result(Base::* Func)(Args...)
>
struct instance_call_helper<
    Result(Base::*)(Args...),
    Func
>

In order to use this code with GCC 6, one can check the value of __cpp_deduction_guides macro:

#if __cpp_deduction_guides >= 201606
template<
    auto F
>
#else
template<
    typename Function,
    Function F
>
#endif

For use with C code (it's not portable, as noticed in the comments), some more advanced typechecking can be used for arguments, like std::is_fundamental or std::is_pod


General Programming

Using built the built in exponent function from racket/base and referencing Euler's Number from math/base would probably reduce the likelihood of bugs; increase speed; and allow programming at a higher level of abstraction.

An alternative to read is the GUI function get-text-from-user in racket/gui/base.

Example Code
#lang racket

(require (only-in math/base
                  euler.0)
         (only-in racket/gui/base
                  get-text-from-user))

(define (get-power-of-e)
  (define x (string->number
             (get-text-from-user "Power of e"
                                 "provide exponent")))
  (expt euler.0 x))


Here are some comments on your revised code, many of which apply to your original code as well.

for (auto& T: U) transform(T).find(max_perim, proc);

You're using the names T and U to refer to things that are not template type parameters. In fact, U is a reference to a static data member of the enclosing class, whose only declaration appears many lines below this use. This is extremely surprising code. I might instead write

for (auto&& formula : this->child_formulas) {
    this->transform(formula).find(max_perim, proc);
}

Notice the use of braces around the loop body; the use of auto&&, Which Always Works; the use of this-> to clarify for the human reader what scope we're expecting to find these names in; and especially the descriptive name child_formulas for U. (child_formulas says what U is; this-> says whose it is. Both of those things were in question, in the old code.)

class triple : public std::array<long, 3> {

Don't inherit from standard types. It's legal C++, but it's bad practice.

  If you (or your project, or your company) didn’t write class Foo, then class Foo should not be granted control over the API of your own class. And that’s what you’re doing when you inherit from a base class: you’re granting that class control over your API.

I like your original x, y, z data members much better.

template <typename F>
void find(long max_perim, F&& proc) {

You're passing proc by perfect-forwarding, but then when you use it, you're using it as a plain old lvalue. This is fine (in the wild-west anything-goes world of templates), but it doesn't express the meaning of proc quite as well as I'd like. proc is supposed to be a callback that gets called for each triple, right? Calling a callback doesn't modify the callback. So, we can and should require that proc be const-callable, and then we just write

template<class F>
void find(int max_perim, const F& proc) {

(Drive-by irrelevant style adjustments to save typing. long varies in size and is the same size as int on many platforms, so let's just use int until we're ready to step all the way up to a well-defined int64_t or __int128_t.)

If you really want to support non-const and/or rvalue-callable Fs, you can perfect-forward proc all over the place, but trust me, it's not worth it. (The std::forward<F>(proc)s will clutter your code, and all you're doing is enabling your users to write confusing and unintuitive client code.)

Vice versa, re your question about concepts: You can constrain this template to SFINAE away in C++17 (or C++11) like this:

template<class F, class = std::enable_if_t<std::is_invocable_v<const F&, triple&>>>
void find(int max_perim, const F& proc) {

This is not much more boilerplate than the C++2a concepts version:

template<class F> requires std::is_invocable<const F&, triple&>
void find(int max_perim, const F& proc) {

Notice that in C++2a you will also be able to write "simply"

void find(int max_perim, const std::invocable<triple&> auto& proc) {

but (A) this doesn't express exactly the same SFINAE-constraint as the other two, and (B) IMHO it looks more confusing and scary.

But should you constrain this function to SFINAE away when it's given a "bad" lambda type? IMHO, no, you shouldn't. There's no reason to SFINAE here. SFINAE is for when you need this version of find to drop out of the overload set so that some other more general version can pick up the call. That's not the situation that you have, here.

Compare the error messages you get from (A) (or the C++2a Concepts version (A2))

template<class F, class = std::enable_if_t<std::is_invocable_v<const F&, triple&>>>
void find(int max_perim, const F& proc) {
    proc(*this);
}

this->find(42, 7);

versus (B)

template<class F>
void find(int max_perim, const F& proc) {
    static_assert(std::is_invocable_v<const F&, triple&>);
    proc(*this);
}

this->find(42, 7);

versus (C)

template<class F>
void find(int max_perim, const F& proc) {
    proc(*this);
}

this->find(42, 7);

and see which version feels most "user-friendly" for the client programmer. (Remember that someone using find correctly will never see any of these error messages, so you should optimize to help the guy who doesn't know how to use it.)

  cnt_next_depth += U.size(); // always 3
  if (--cnt_this_depth == 0) {
    if (++depth > max_depth) return;
    cnt_this_depth = cnt_next_depth;
    cnt_next_depth = 0;
  }
  for (auto& T: U) q.push(t.transform(T));

Code comments are usually a red flag, at least on CodeReview. ;) It seems that this += corresponds to the three calls to q.push below; i.e., your algorithm requires that cnt_next_depth exactly track q.size(). But you can't use q.size() because you are reusing q to store both the elements at the current level and the elements at the next level.

It would make more sense to use two different queues:

std::vector<triple> this_level = ...;
std::vector<triple> next_level;
for (int i=0; i < max_depth; ++i) {
    for (auto&& t : this_level) {
        proc(t);
        for (auto&& formula : child_formulas) {
            next_level.push_back(t.transform(formula));
        }
    }
    this_level = std::move(next_level);
    next_level.clear();
}

As a bonus, it turns out that we don't even need them to be queues anymore; they can be plain old vectors, and we save a bunch of heap traffic.

friend std::ostream& operator<<(std::ostream& stream, const triple& t) noexcept {
  // Frustrating boiler plate. Any terse alternatives, that do it quickly and correctly?
  char comma[] = {'\0', ' ', '\0'}; // NOLINT
  for (auto d: t) {
    stream << comma << d;
    comma[0] = ',';
  }
  return stream;
}

No good answer. The idiomatic way would be

friend std::ostream& operator<<(std::ostream& stream, const triple& t) {
    bool first = true;
    for (auto&& d : t) {
        if (!first) stream << ", ";
        stream << d;
        first = false;
    }
    return stream;
}

Notice that this function is not noexcept, because any of these stream operations might throw. (For example, if you're writing to a stringstream and it throws bad_alloc.)

Also, in real life I'd write for (int d : t) to indicate exactly what type of "elements" I expect to be getting out of a triple. I'm using auto&& here only because I saw your comment that you want to stick with "Almost Always Auto" style.

  triple transform(const trans& T) const noexcept {
    auto res = triple{};
    std::transform(T.begin(), T.end(), res.begin(), [this](vec3 V) {
      return std::inner_product(V.begin(), V.end(), this->begin(), 0L);
    });
    return res;
  }

This is interesting use of STL algorithms, but algorithms are really meant for operating on big anonymous ranges of data elements, not for constant-size situations like we have here. In order to use STL algorithms, you've been forced to anonymize your formulas into faceless data ranges:

  static constexpr auto U = std::array<trans, 3>{{
      // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships
      {{{{{1, -2, 2}},    // vec3 U[0][0]
         {{2, -1, 2}},    // vec3 U[0][1]
         {{2, -2, 3}}}}}, // vec3 U[0][1]

      {{{{{1, 2, 2}},    // vec3 U[1][0]
         {{2, 1, 2}},    // vec3 U[1][1]
         {{2, 2, 3}}}}}, // vec3 U[1][2]

      {{{{{-1, 2, 2}},    // vec3 U[2][0]
         {{-2, 1, 2}},    // vec3 U[2][1]
         {{-2, 2, 3}}}}}, // vec3 U[2][2]
  }};

Compare that code to a more "code-driven" version:

triple transform(const Formula& f) const noexcept {
    return f(x, y, z);
}

auto formulas[] = {
    +[](int x, int y, int z){ return triple{ x - 2*y + 2*z, 2*x - y + 2*z, 2*x - 2*y + 3*z}; },
    +[](int x, int y, int z){ return triple{ x + 2*y + 2*z, 2*x + y + 2*z, 2*x + 2*y + 3*z}; },
    +[](int x, int y, int z){ return triple{ -x + 2*y + 2*z, -2*x + y + 2*z, -2*x + 2*y + 3*z}; },
};

In this version, trans is gone already, and t.transform(f) is hardly pulling its weight.

if (perimeter() > max_perim) return;

Consider what you'd do if you wanted to find all triples up to some maximum side length, or up to some maximum hypotenuse length. Does this approach generalize to

triple.find(callback_on_each_triple, stopping_condition);

?


Immutable objects are awesome. They are robust, predictable, and inherently thread-safe.
Make the x, and y fields final,
and change the operations to return the resulting Vector,
for example:

class Vector {
    private final int x;
    private final int y;

    public Vector(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Vector add(Vector other) {
        return new Vector(x + other.x, y + other.y);
    }

    public Vector sub(Vector other) {
        return new Vector(x - other.x, y - other.y);
    }

    public Vector mul(Vector other) {
        return new Vector(x * other.x, y * other.y);
    }
}

As in the example above, I recommend changing the name of the Vector parameter from vector to something else, like other, to make it perfectly clear that the method is dealing with another vector.

This way you'll be able to chain operations like this:

new Vector(1, 2).add(new Vector(3, 4)).sub(new Vector(5, 6)).mul(new Vector(7, 8));

It will be also useful to implement a custom toString method to make it easy to print a String representation of the vector, for example:

@Override
public String toString() {
    return String.format("(%s, %s)", x, y);
}


Your code looks fine and is vectorized! You could've written a single line logistic cost function, but I believe your approach is more readable. Good job!

I don't think there is much more optimizations that you can do related to the basic form of logistic regression.

A possible addition however is to add regularization. This helps for the scenario of overfitting, where a high order polynomial function tries to fit perfectly according to the dataset in such a way that it doesn't make sense anymore.

An example:

regularization tries to prevent this by reducing the magnitude of the parameters θ (penalizing the parameters).  You will end up with a smoother curve which fits the data and gives a better hypothesis.

To accomplish this you will have to introduce another parameter, λ (regularization parameter).

I suggest you to look further into this yourself, perhaps here is a good starting point.

I hope this helps a bit.


A helper class for creating icons from a PNG image and colour in Swift

let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)

can be simplified to

let rect = CGRect(origin: .zero, size: size)

The explicit type annotation in

let backgroundImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

is not needed. In

UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)

one can pass 0.0 as the last argument, that is also interpreted
as the scale factor of the device’s main screen.

let cornerRadius = newImage.size.height/2
UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()

can be simplified to

UIBezierPath(ovalIn: bounds).addClip()

(and that would work even for a non-quadratic frame).

Instead of creating and drawing into a  bitmap-based graphics context
three times, with two intermediate images, it suffices to use a single graphics context, and

Add a round clipping path,
fill with the given background color,
draw the given image,

all with the same context.

Instead of the fully transparent default icon "iconEmpty.png" you
could make that parameter optional, and draw the icon only if an icon
was provided by the caller.

Finally, the method does not access any properties of the IconMaker
type. You can make it static, so that it can be called without
creating an IconMaker instance:

let newIcon = IconMaker.makeIcon(...)

Putting it all together, the method could look like this:

static func makeIcon(with color: UIColor, size: CGSize, icon: UIImage? = nil) -> UIImage {

    // Create graphics context:
    let rect = CGRect(origin: .zero, size: size)
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

    // Circular mask
    UIBezierPath(ovalIn: rect).addClip()

    // Make solid color background:
    color.setFill()
    UIRectFill(rect)

    if let icon = icon {
        // Add other image (which has transparency)
        icon.draw(in: rect, blendMode: .normal, alpha: 1.0)
    }

    // Create new image and release context:
    let newImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
}

Another option is to use the defer statement for releasing
the graphics context:

static func makeIcon(with color: UIColor, size: CGSize, icon: UIImage? = nil) -> UIImage {

    // Create graphics context:
    let rect = CGRect(origin: .zero, size: size)
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    defer { UIGraphicsEndImageContext() }

    // ...

    return UIGraphicsGetImageFromCurrentImageContext()!
}

The block passed to the defer statement is executed just before
the function returns. Here it allows to get rid of the newImage
variable. Generally it is a good approach to ensure that all
acquired resources are released properly, no matter how program
control leaves the function.


First and foremost, XML is not a regular language, and therefore parsing it using regular expressions is not appropriate, and is asking for trouble.

Secondly, invoking perl within perl is clearly an awful idea. Invoking it multiple times is even worse.

As all the s!!! operations are performed on the same file, you could perform all of them at once in the same process, by separating them with semicolons, that is:

perl -pi -e 's!pattern1!replacement1!sg; s!pattern2!replacement2!sg' file

But as I said earlier, you should not call perl from within a perl function in a backtick expansion, but implement properly the operations (open file, read buffer, perform replacements, overwrite the file).

And instead of doing this using regular expressions, consider using an XML parser.


helper function to determine if html text is wrapped with a certain tag

Your code looks good and concise.

Your test cases cover almost every branch of the code, which is also good.

You can improve the variable names:

The temp in tempDocument is not necessary. Therefore the variable name should better be document, or if that is too long, doc. Be careful though when abbreviating variable names, and don't make them ambiguous.
The no test case should rather be called parsererror. I had to run the code to see that it really tests this branch of the code. By improving the name of the variable, you make this more obvious.

There is a test case missing for a tag name other than p.

if (doc.children.length === 1 && doc.children[0].tagName.toLowerCase() === tag.toLowerCase()) {
  return true;
}
return false;

If you want, you can write this code a bit shorter:

return doc.children.length === 1
    && doc.children[0].tagName.toLowerCase() === tag.toLowerCase();

Your current code is a bit longer, but it allows you to set a breakpoint on the return true statement, which may be useful when debugging the code. But since you already have automated tests running, you will probably not need to set a breakpoint there. Your choice. Many programmers prefer the shorter form, but the longer form is not bad per se.

The expression doc.children.length === 1 is always true. This is because you are parsing the text using the text/xml type, and the XML standard requires exactly 1 root element. Everything else will end up in the parsererror branch. To verify this, you should add a test case for an empty string. And a test case for an XML comment, such as .

When I first read the function name textIsWrappedWithTag, I didn't know exactly what to expect from that function. My first thought was that textIsWrappedWithTag('

text

', 'p') would return true, since there is some text that is enclosed in a p tag. You could try to find a better name for that function, maybe topLevelElementIs.

By the way, the DOM API talks about elements, while the HTML standard calls them tags. If you want your function to feel like it belongs to the DOM API, you should call it textIsWrappedWithElement instead.


How to refactor this code to get a source from property files?

There are a couple of inefficient things you do, and there's some better-practice items too.

First, let's take one of the methods:

public static List<String> loadNodes2_00() {

    List<String> node = new ArrayList<>();

    try {

        InputStream inputStream = XmlUtil.class.getClassLoader().getResourceAsStream("nodes2.00.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        for (Object value : properties.keySet()) {
            node.add((String) value);
        }

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

    return node;
}

node is not a great name for something that is a list. It is typical in computer programs for node to point to just a particular element in a list, stack, or whatever, not the whole thing.

Something like result, or names would be better.

Then, you are not closing the InputStream. This is bad practice, and is a bad habit to be in. Java7 allows the try-with-resources statement, which is ideal for this code.

Now, there is the less-commonly-used method stringPropertyNames() available on Properties. It is useful here, instead of iterating on the keyValues().

Why are the loadNodes1_10() and loadNodes2_00() methods public? Do they need to be? They should be private to the class if they are not used.

Constant values embedded inside code are often called 'Magic values'. In this case, the values are Strings. You should declare a constant for your resource names....

Putting it all together, how about this method:

private static final String RESOURCE_NODES_2_00 = "nodes2.00.properties";
private static List<String> loadNodes2_00() {

    List<String> names = new ArrayList<>();
    try (InputStream inputStream = XMLUtil.class.getClassLoader()
                .getResourceAsStream(RESOURCE_NODES_2_00)) {

        Properties properties = new Properties();
        properties.load(inputStream);
        names.addAll(properties.stringPropertyNames());

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

    return names;
}

This is neater, and more efficient, and it closes all the streams correctly.... but... apart from the method name, and the file name, your two methods are identical. What you should do is generalize the method:

private static List<String> loadNodes(String resourcename) {

    List<String> names = new ArrayList<>();
    try (InputStream inputStream = XMLUtil.class.getClassLoader()
                .getResourceAsStream(resourcename)) {

        Properties properties = new Properties();
        properties.load(inputStream);
        names.addAll(properties.stringPropertyNames());

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

    return names;
}

Now, in your calling method, you can change your code to:

private Map<String, List<String>> loadXmlNodes() {

    Map<String, List<String>> mapNodes = new HashMap<>();
    mapNodes.put("1.10", loadNodes(RESOURCE_NODES_1_10);
    mapNodes.put("2.00", loadNodes(RESOURCE_NODES_2_00);

    return mapNodes;
}

This should simplify the code a whole lot.

If you need the two methods loadNodes1_10() and loadNodes2_00() to be public, I would make them simply:

public static List<String> loadNodes1_10() {
    return loadNodes(RESOURCE_NODES_1_10);
}

All the best, and enjoy.

EDIT:

If you want to return a Map<String,Map<String,String>> instead, it will look something like:

private static Map<String,String> loadNodes(String resourcename) {

    Map<String,String> names = new HashMap<>();
    try (InputStream inputStream = XMLUtil.class.getClassLoader()
                .getResourceAsStream(resourcename)) {

        Properties properties = new Properties();
        properties.load(inputStream);
        for (String key : properties.stringPropertyNames()) {
            names.put(key, properties.getProperty(key));
        }

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

    return names;
}

and then you would have to adjust the other methods that call this respectively.


Not much to review, but, if I read the Java documentation, you don't put the complete class in it.

Because you didn't put the full class I come to the next thing :

K outputElement = array[index++];
if (index == 0) {
    index++;
}

What the hell are you doing?

index is instantiated at 0, the line before is index++ so index is never 0.

Second point, you missed some errors.
When you are at the last element and you ask next() you will get an OutOfBoundsException.

Rather, it's better to check if your at the last element and if so, just return null.

The OutOfBoundsException is an unchecked exception, so nobody who will use your class will expect and handle this error, and then the problems are coming.

Also add JavaDoc what the Iterator returns when you are at the last element.

Then another point; the constructor has this line :

index = 0;

It's obsolete.  An int default value is always 0.
Because it's not a static variable, it's instantiated when you create the class; so it's 0.

Generics:

With the new description in your question, a few more things come up.
I don't know if you know how to use generics or it's just a fault but:

You expect Integer so I should rename the class name to UniqueIntegerIterator or something like that.
Because public class GenericIterator<K> implements Iterator<K> means that you can insert any type of Object it has a lot more usage then Integer only.
If you want to make it only for Integer, the declaration should change to public class GenericIterator implements Iterator<Integer>.
Of course the K[] should be changed to Integer[]

Expect bad usage of your class.

You state that you expect a sorted integer array in the constructor. You may ask:

  What if this isn't the case?

It's really important to ask yourself this question.
Normally, when you have some requirements, you check for that and throw an AssertionError when the requirements are not met.
In this case and in my own perception, I should sort the array in the constructor so I know the requirement is done.
Also, when I do this I rename the class again to UniqueSortedIntegerIterator so the people who are going to use this class understand they get unique values from a sorted collection, in this case an array.  The Object behind is Integer and it acts like an Iterator.


There are several issues that could be improved:

First of all, having concrete classes which are all tied to a specific database (in this case Oracle), is usually completely opposite of what a Data Layer's responsibility should be. Consider changing the classes' names as follows:

OracleConnection --> DbConnection
OracleCommand --> DbCommand
OracleParameter --> DbParameter.

To instantiate a new command, don't use a specific constructor, but rather use the DbConnection.CreateCommand() method (and, likewise, DbCommand.CreateParameter() to create its parameters). That means you only need to change the actual connection instance, if you decide to switch from Oracle to a different db provider one day.
Next, strategy pattern is usually used to abstract a functionality which several different algorithms can execute, while exposing a single (common) interface. Creating a different strategy for different table queries is not appropriate, because the calling code already knows which table it is querying (there are no additional strategical choices your code can do).
I am not sure if the NotImplementedExceptions are thrown deliberately, or you really haven't yet implemented those methods. If you are throwing to indicate that a certain implementation doesn't support that functionality, that is another alarm that these two implementations are not really different strategies for the same task.


Find all nodes in tree, without a sibling

Recursion
The null-check in your recursive method is redundant. The preliminary checks and the mid-recursion checks ensure that the method is never called with a null input.
I also really favour a simplified recursive approach, where the recursion checks it's own conditions, instead of pre-checking the recursive conditions before calling the recursion. In this case, it halves the number of recursive calls, halves the list.adds, and reduces by a third the number of if-conditions in your code:
    private void findNonSiblingNodes(TreeNode<T> node, boolean hasSibling List<T> list) {
        if (node == null) {
            return;
        }

        if (!hasSibling) {
            list.add(node);
        }

        findNonSiblingNodes(node.left, node.right != null, list);
        findNonSiblingNodes(node.right, node.left != null, list);
    }

You would call that code with:
    public List<T> nonSiblingNodes() {
        final List<T> list = new ArrayList<T>();
        findNonSiblingNodes(root, true, list);
        return list;
    }
}

It is safe to remove the null-check on the root node, because it can never be null at that point. That's because ....
Bugs
... your code does horrible things in the constructor, which will fail before it gets here:
    public PrintNodesWithoutSiblings(List<T> items) {
        create(items);
    }

    private void create (List<T> items) {
        root = new TreeNode<T>(items.get(0));
        ....

Your constructor will throw NPE if the items is null, and will throw NoSuchElementException if the List is empty. Thus, the root will never be null in the recursion.
Style

final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();

You should use the 'diamond operator' when using Java7 and later. The line above can be just:
final Queue<TreeNode<T>> queue = new LinkedList<>();

Similarly, the line:

final List<T> list = new ArrayList<T>();

can be:
final List<T> list = new ArrayList<>();


Exam score query for many types of exams

This kind of expression

 (Name_of_exam = 'First Term Weekly Test'
 OR Name_of_exam = 'Second Term Weekly Test'
 OR Name_of_exam = 'Third Term Weekly Test'
 OR Name_of_exam = 'Final Term Weekly Test')

can usually be shortened to an IN clause.

(Name_of_exam in ('First Term Weekly Test', 'Second Term Weekly Test', etc.))

But there's enough conditional logic in here that I'd have to ask myself, "Am I trying to write a report in SQL?" Reports are better implemented with a report writer.

This doesn't have to do with your question, but a GROUP BY statement that includes only one of 'n' unaggregated columns is almost always a syntax error in standard SQL. MySQL treats this like a feature, but it's a feature best avoided.

It's almost always a syntax error, because standard SQL allows you to group on one of 'n' unaggregated colums when the unaggregated columns are  functionally dependent on the grouped column.


Promise.all, but with enforced limit on concurrent promises

You can remove Object.assign as _.zip will eventually give you the required array.

Also _.range(0, limit) is equivalent to _.range(limit).


There is absolutely no need to put parentheses around the first statement (small improvement, but it improves readability). "parameter" is also misspelled (improving readability but in a different way).

String x = JOptionPane.showInputDialog(". Each parameter should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",";

There is no need to use Double[] when you can use double[]. The difference is, simply put, that a Double can be null while a double can not.
In the rest of your code it seems like you are reading all the doubles from the String (separated by commas), which can be done much easier like this:

String[] splitted = x.split(",");
double[] result = new double[splitted.length];
for (int i = 0; i < splitted.length; i++) {
    result[i] = Double.parseDouble(splitted[i]);
}

The key here is to use the split-method on the String, which does most of the work for you. For example, it splits the string "0.37,42,21.4" into a string array with the three elements "0.37", "42" and "21.4". The rest of the code loops through that array and converts from String to double.


You can streamline by dropping the use of append, and ignoring values in your for-loop that are automatically disqualified.  Benchmarking shows these steps reduce execution time by about 2x.

Original:

%%timeit

origin=[2,0,11,3,0]
left=1
right=10
query(origin,left,right)
# 3.6 µs ± 950 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

New version:

def query2(sliced,left,right):
    count = 0
    leng = len(sliced)
    for i in range(leng):
        if sliced[i] <= right:
            stack_ct = 0
            end_index = i
            found_max = False
            while(end_index < leng and sliced[end_index] <= right):
                if not found_max:
                    found_max = sliced[end_index] >= left
                end_index += 1
                stack_ct += 1
            if found_max:
                count += stack_ct
    return count

Benchmarking:

%%timeit

origin=[2,0,11,3,0]
left=1
right=10
query2(origin,left,right)
# 1.83 µs ± 41.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


Building the list takes a lot of time. Note that your  arr += [i] * arr[i] repeats the same value i over and over again. This can be much compressed by just storing repeat(i, arr[i]) instead. This succeeds in about 6 seconds, well under their 12 seconds limit:
from itertools import chain, repeat

def find(n):
    if n <= 3:
        return [0, 1, 2, 2][n]
    arr = [[2]]
    arr_sum = 5
    arr_len = 4
    for i, arr_i in enumerate(chain.from_iterable(arr), 3):
        arr_sum += i * arr_i
        if arr_sum >= n:
            x = (arr_sum - n) // i
            return arr_len + arr_i - (x+1)
        arr.append(repeat(i, arr_i))
        arr_len += arr_i

Note that in the n > 3 case, we start already with the number 3, appending it twice to the list. Thus of the sequence start [0, 1, 2, 2] we only need [2], so I start with arr = [[2]] (which is shorter than [repeat(2, 1)], and chain doesn't mind).

Alternatively... note that you're extending arr much faster than you're consuming it. For n=241, you grow it to over 51 million elements, but you're actually reading fewer than the first 70 thousand. So you could stop truly extending the list at that point. This succeeds in about 4.7 seconds:
def find(n):
    arr = [0, 1, 2, 2]
    if n <= 3:
        return arr[n]
    arr_sum = 5
    arr_len = 4
    for i in range(3, n+1):
        arr_sum += i * arr[i]
        if arr_sum >= n:
            x = (arr_sum - n) // i
            return arr_len + arr[i] - (x+1)
        arr_len += arr[i]
        if arr_len < 70_000:
            arr += [i] * arr[i]

And... you can combine the above two improvements, i.e., apply that if arr_len < 70_000: to the repeat-version. That then succeeds in about 4.5 seconds.
Benchmark results on my PC for n=241:
Your original:   1.795 seconds
My first one:    0.043 seconds (42 times faster)
My second one:   0.041 seconds (44 times faster)
The combination: 0.026 seconds (69 times faster)

Oh and a style comment: You twice do this:
if ...:
    return ...
else:
    ...

The else and the indentation of all the remaining code are unnecessary and I'd avoid it. I've done so in the above solutions.


NULL versus nullptr

You shouldn't be using NULL, as you did in various places, like here:

node->next = NULL;

NULL is deprecated, and you should be using nullptr, like this:

node->next = nullptr;

If this is legacy code, and you need to support users running old compilers that date to before C++11, you should keep using NULL.

std::endl versus "\n"

Rather than using std::endl, you should just suffix this onto the end of any std::cout statements:

<< "\n";

You should be doing this unless you're very sure that you want to flush the output buffer each time you run std::cout. If you do need to flush the output buffer, then you should keep using std::endl.

Nitpicks

There are a fair amount of things that I want to pick at here, so bear with me.

You should remove all the using statements at the top of your code. By removing the prefix of std:: on some of it's members, your code loses clarity. The only time it's really appropriate to use a namespace, or namespace members is when you have a really deep nested namespace, like foo::bar::baz::barbaz::blah.
Secondly, there are a lot of useless comments. For example, the comment by the function signature for Clr, is not really needed. If you give Clr a better name, like removeAll, the need for the comment vanishes. This applies to many other comments as well.
Finally, the Stack class should have a toString method, which should return a std::string-representation of the stack.


intToEnglish(-1) returns "undefined", which might not be what you want. Same goes for fractional values, although I guess that case could be waved... if you only support integers. Even so, you might want to add a check. At the very least, add a comment - problem descriptions are kept separate from your code right now, and that makes it non-obvious that it doesn't support such things!

Negative numbers could be supported via prepending "minus", then translator(Math.abs(n)).


I'm not sure why you're using your own built classes to access the database when .net has a very complete set of classes that can be used for data access.

Just looking at your syntax, I see the same functionality, so to me that is a waste of development time.

Also, it seems while I don't have access to your classes locally, I've changed them to use the included .net classes.

EDIT: Changed dr.GetString("") to dr.GetString(dr.GetOrdinal(""))

using System.Data.SqlClient;

public User Get(int userID)
{
    const string sql = "select * from users where userid = @id";
    const string connnectionString = "<your connection string>";

    // Using will dispose of the connection when the inner statements
    // have completed executing.  The dispose actually closes the connection.
    // The class has to implement the IDisposable interface.
    // var is a strongly typed variable, mostly used to keep the code easy to read.
    using(var connection = new SqlConnection(connnectionString))
    {
        connection.Open();

        // Make sure the SqlCommand object is disposed
        using (var cmd = new SqlCommand(sql, connection))
        {
            // No need to use a separate list to add parameters, just
            // add them directly to the command.
            cmd.Parameters.Add(new SqlParameter("@id", userID));

            var dr = cmd.ExecuteReader();
            var user = new User();

            // Read returns a boolean if it reads a record.
            if (dr.Read())
            {
                user.EmailAddress = dr.GetString(dr.GetOrdinal("email"));
                user.Password = dr.GetString(dr.GetOrdinal("passcode"));
            }
            return user;
        }
    }
}

public void Update(int userID)
{
    const string sql = "update users set email = @email, passcode = @pass where userid = @id";
    const string connnectionString = "<your connection string>";

    var user = Get(userID);

    using (var connection = new SqlConnection(connnectionString))
    {
        connection.Open();

        using (var cmd = new SqlCommand(sql, connection))
        {
            cmd.Parameters.Add(new SqlParameter("@email", user.EmailAddress));
            cmd.Parameters.Add(new SqlParameter("@pass", user.Password));
            cmd.Parameters.Add(new SqlParameter("@id", userID));

            cmd.ExecuteNonQuery();
        }
    }
}


This isn't a language I know, but there appears to be a problem with the logic.

Suppose I have a simple statement:

  In XML, ampersand can be represented using '&amp;' or '&#38;'

Is that an already-encoded string?  The logic here says that it is, but we see that's not the case - the HTML version of that would be

  In XML, ampersand can be represented using '&amp;amp;' or '&amp;#38;'

If it's hard to keep track in code, a better option might be a small class to hold a HTML-encoded string, so that we don't confuse these with content strings (or vice-versa, if HTML-encoded is the default in your target environment).

But TBH, I think that good variable naming should be enough to track which strings are which.


I'm not sure if you're gaining anything from this wrapper class or not, but there is an alternative for initializing an array to have all the same value at each position. You could use Enumerable.Repeat instead of the loop.

void GenerateDefaults()
{
    tileCosts = Enumerable.Repeat(1, System.Enum.GetNames(typeof(TileType)).Length).ToArray();
}

But perhaps the one liner is a bit too terse to be readable.

void GenerateDefaults()
{
    var length = System.Enum.GetNames(typeof(TileType)).Length;

    tileCosts = Enumerable.Repeat(1, length).ToArray();
}

Whether or not that's an improvement may be debatable and is mostly a matter of preference in my opinion.

Something else I don't care for is the fact that GenerateDefaults is a void. As such, it's not immediately clear that it modifies the tileCosts class variable. I would redefine it to return int[]. It's a few more keystrokes to call it, but it becomes obvious where tileCosts is being modified.

[System.Serializable]
public class UnitTileCosts
{
    int[] tileCosts;

    public UnitTileCosts()
    {
        //empty constructor uses default value of 1 for all fields
        tileCosts = GenerateDefaults();
    }

    public UnitTileCosts(Dictionary<TileType,int> costs)
    {
        tileCosts = GenerateDefaults();
        foreach(var pair in costs)
        {
            tileCosts[(int) pair.Key] = pair.Value;
        }
    }

Which begs the question, why set a default value at all if you're just going to overwrite the value a split second later?? It doesn't make sense to me and I would remove that code. At the least, I would make the overloaded constructor call the default constructor to dry things up.

    public UnitTileCosts(Dictionary<TileType,int> costs) : this()
    {
        foreach(var pair in costs)
        {
            tileCosts[(int) pair.Key] = pair.Value;
        }
    }


Replace 24 with (sizeof(int) - 1) * CHAR_BIT. Otherwise the code would fail on a non-32-bit integer machines. Also, using -1 as a probe makes you independent of the bitness of a system:

return ((-1) >> 1) == (-1);

PS: you don't want to print anything from such a specialized routine.


Using namespace std

Please review this post on why you should not use using namespace std: Why is “using namespace std” considered bad practice?

Enums

//0 = empty
//1 = has guessed
//2 = sub

You should use an enum to represent those values:

enum SquareType {
    Empty = 0,
    Guessed = 1,
    Sub = 2
};

Now, instead of doing the confusing:

if (board[x][y] == 0)
{
    ...
}
else if (board[x][y] == 1)
{
    ...
}
if (board[x][y] == 2)
{
    ...
}

You can do:

if (board[x][y] == SquareType.Empty)
{
    ...
}
else if (board[x][y] == SquareType.Guessed)
{
    ...
}
if (board[x][y] == SquareType.Sub)
{
    ...
}

Style

You have way too much vertical space in your program.  You should really only use 1 empty line at a time.

Your bracing is inconsistent.  Either always use them (preferred), or use them as little as possible.

Input

You never use the do-while loop in playerGuess.  If you carefully check the runtime, you break directly out of the loop every time you have bad input.  That gives the loop a chance to continue if, and only if, you get two good inputs, but getting two good inputs automatically invalidates the continuation condition.

Notice how similar the two sections in the following code is.  Duplication everywhere.

//get X pick
cout << "X: ";
cin >> guessX;
if (guessX < 0 || guessX>2)
{
    goodInput = false;
    cin.clear();
    cin.ignore(256, '\n');
    cout << "Out of Range!" << endl;
    //display grid again with X's on board where guessed
    break;
}
else
{
    goodInput = true;
}

//get Y pick
cout << "Y: ";
cin >> guessY;
if (guessY < 0 || guessY>2)
{
    goodInput = false;
    cin.clear();
    cin.ignore(256, '\n');
    cout << "Out of Range!" << endl;
    //display grid again with X's on board where guessed
    break;
}
else
{
    goodInput = true;
}

You should join these into a single input function:

int input(string prompt)
{
    int guess = -1;

    do {
        cout << prompt;
        cin >> guess;
        if (guess < 0 || guess > 2)
        {
            guess = -1;
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Out of Range!" << endl;
        }
    } while (guess == -1)

    return guess;
}

Then call it like:

//get X pick
guessX = input("X: ")

//get Y pick
guessY = input("Y: ")

This will also ensure the function gets good input back the first time input() returns.

main()

Your main() function should only be the entrance to your program.  You typically should not use main() to do work--create a function who's sole responsibility is doing that work.  Right now, you gave main() two responsibilities--starting the program and running it.

Exceptions

Only use exceptions for exceptional behavior, not for control flow.  Getting bad input is never exceptional--it is to be expected.  Simple programs like this should almost never throw exceptions deliberately.


Creating JavaScript API for first time; request review

From what I understand, you are building an abstraction layer and making your own functions for your API. Here's what you need:

A Namespace

Sounds very C++-ish but yes, you do need namespaces in JS. This prevents you from polluting the global namespace and have a central go-to object for your functions. For example, jQuery uses jQuery and the $ namespaces for a central collection of their functions. Notice $ in $.each(), $ is actually the namespace (a function actually).
Module that code

Another way to prevent code pollution and collision is to wrap your code in a scope, usually called a "closure". This is just a geeky way of calling a function scope that persists because of something returned that still has reference to that scope. Normally, it's called a module (as in a modular piece of code). A simple way of building a module is to use an "immediate function" or a function that immediately executes. A more detailed explanation how it works is explained here
Extensibility

With modular, namespaced code, usually developers forget to open their modules to extensibility. Because module pattern is like putting a cage around their code, developers forget to actually provide a way to make their module extendable.

You should provide a way (like provide a function) that allows (limited) access to your module and allow it to attach custom functions from the outside. An example is how jQuery allows plugins to be made.

Here's a short way to make a module, and have your custom functions

(function(namespace){

    namespace.get = function(params){
        ...
    }

}(window.myNamespace = window.myNamespace || {}));

myNamespace.get(params);


On the offhand chance that your object is already a DateTime, you're performing unnecessary conversions to and from strings.

 if (o is DateTime)
     return (DateTime)o;

This also strikes me as something you might be doing for a database item, for example. In which case, I'd encourage you to know and trust your data types and then use existing methods of retrieval.

For example, if you have a DataTable with a column CreatedDate, you should know it's a date, what you might not know is if it has a value if the column is nullable at the database. That's fine, you can handle that in code.

 var createdDate = row.Field<DateTime?>("CreatedDate");

There we go, a DateTime?, no coding of a conversion necessary. You can even specify a default and type if to DateTime

 var createdDate = row.Field<DateTime?>("CreatedDate").GetValueOrDefault(DateTime.Now);
 var createdDate = row.Field<DateTime?>("CreatedDate") ?? DateTime.Now;


Calculating n-ary Cartesian Product too slow

The implementation contains one small but important bug (or feature?), it yields the same array instance from each loop.
Consider this example.
int[][] numbers = new[] { new[] { 1 }, new[] { 2, 3 }, new[] { 4, 5 } };

foreach (int[] arr in Product(numbers))
{
    Console.WriteLine(string.Join(", ", arr));
}

The output is perfect
1, 2, 4
1, 2, 5
1, 3, 4
1, 3, 5

But if you want to store the result as jagged array and process it later:
foreach (int[] arr in Product(numbers).ToArray())
{
    Console.WriteLine(string.Join(", ", arr));
}

You'll get this output
1, 3, 5
1, 3, 5
1, 3, 5
1, 3, 5

That's because it's an array of four references to the same array.
Next small thing is one redundant line of code
yield break;

You don't need it because previous line is the last statement in the method. The method exits after it.
Fix is simple
public static IEnumerable<T[]> Product<T>(T[][] items)
{
    T[] currentItem = new T[items.Length];
    static IEnumerable<T[]> Go(T[][] items, T[] currentItem, int index)
    {
        if (index == items.Length)
        {
            yield return (T[])currentItem.Clone();
        }
        else
        {
            foreach (T item in items[index])
            {
                currentItem[index] = item;
                foreach (T[] j in Go(items, currentItem, index + 1))
                {
                    yield return (T[])j.Clone();
                }
            }
        }
    }
    return Go(items, currentItem, 0);
}

That's it.
Performance while keeping it as returning arrays will be slow because e.g. for 10 arrays of 10 items it will yield 10*10*10*10*10*10*10*10*10*10 = 10000000000 arrays of 10 items each. But you want up to 15. It won't be fast at all.
But let's try to eliminate the recursion.
Consider an alternative implementation of the same
public static IEnumerable<T[]> MyProduct<T>(T[][] items)
{
    int length = items.Length;
    int[] indexes = new int[length];

    while (true)
    {
        T[] arr = new T[length];
        for (int i = 0; i < length; i++)
        {
            arr[i] = items[i][indexes[i]];
        }
        yield return arr;

        int row = length - 1;
        indexes[row]++;
        while (indexes[row] == items[row].Length)
        {
            if (row == 0)
                yield break;
            indexes[row] = 0;
            row--;
            indexes[row]++;
        }
    }
}

To understand this implementation imagine a digital clock. What if you make 3 arrays 24,60,60 items and fill it with numbers from 0 to 23/59. The Product will yield time to display for each second of the day - 86400 arrays of 3 items each. Then imagine how clock counts time on display and you'll catch the idea of this implementation.
Looks like it works
1, 2, 4
1, 2, 5
1, 3, 4
1, 3, 5

And finally let's make a benchmark for both implementations. Using Benchmark.NET of course. For example with 6 arrays of 6 items each.
[MemoryDiagnoser]
public class MyBenckmark
{
    private int[][] numbers;

    [GlobalSetup]
    public void Setup()
    {
        numbers = new int[6][];
        for (int i = 0; i < 6; i++)
        {
            numbers[i] = Enumerable.Range(i * 6, 6).ToArray();
        }
    }

    [Benchmark]
    public void RunProduct()
    {
        foreach(var _ in Product(numbers)) ;
    }

    [Benchmark]
    public void RunMyProduct()
    {
        foreach (var _ in MyProduct(numbers)) ;
    }

    public static IEnumerable<T[]> Product<T>(T[][] items)
    {
        T[] currentItem = new T[items.Length];
        static IEnumerable<T[]> Go(T[][] items, T[] currentItem, int index)
        {
            if (index == items.Length)
            {
                yield return (T[])currentItem.Clone();
            }
            else
            {
                foreach (T item in items[index])
                {
                    currentItem[index] = item;
                    foreach (T[] j in Go(items, currentItem, index + 1))
                    {
                        yield return (T[])j.Clone();
                    }
                }
            }
        }
        return Go(items, currentItem, 0);
    }

    public static IEnumerable<T[]> MyProduct<T>(T[][] items)
    {
        int length = items.Length;
        int[] indexes = new int[length];

        while (true)
        {
            T[] arr = new T[length];
            for (int i = 0; i < length; i++)
            {
                arr[i] = items[i][indexes[i]];
            }
            yield return arr;

            int row = length - 1;
            indexes[row]++;
            while (indexes[row] == items[row].Length)
            {
                if (row == 0)
                    yield break;
                indexes[row] = 0;
                row--;
                indexes[row]++;
            }
        }
    }
}

Go!
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042
Intel Core i7-4700HQ CPU 2.40GHz (Haswell), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=5.0.102
  [Host]     : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT
  DefaultJob : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT

|       Method |      Mean |     Error |    StdDev |     Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------- |----------:|----------:|----------:|----------:|------:|------:|----------:|
|   RunProduct | 28.509 ms | 0.2488 ms | 0.2077 ms | 6750.0000 |     - |     - |  20.08 MB |
| RunMyProduct |  1.274 ms | 0.0103 ms | 0.0086 ms |  712.8906 |     - |     - |   2.14 MB |

You vote.


Do you really need this:

typedef unsigned long long ull;

Will a long or an int not just work (1 .. 100) fit nicely in these types.

One variable declaration per line.
You are not helping the compiler by making less lines of code (it will work just as well with more). But humans who have to read this will work better with cleaner more readable code.

ull start=1, stop=100,cnt;

A register declaration. Wow. I have not seen one of those in a while (20 years). The optimizer is much better than you at deciding what fits in a register let it do its job. I would even bet this keyword is ignored nowadays.

register int t,len;

Do you realy need to cast the result here?

int a_len=(int)strlen(Alpha);

That could would look a lot clearer without the cast. I would only keep it if the compiler is generating a warning. (but then I may change the type of a_len to be the correct type (but I am a C++ programmer and correct types is important to me).

This seems like a complicated way

 while ( t-- ) str--;

of saying:

 // Or
 str -= t;
 t    = 0;

WTF!!!!

        *p1 ^= *p2;
        *p2 ^= *p1;
        *p1 ^= *p2;

Why O Why do you use this. Its a obfuscated way of swapping two values. Just swap the two values using a temporary. The compiler will use any tricks it has internally to do this as fast as possible (probably using a register and two memory accesses rather than 3 memory accesses (which will be slower)).

Seems to me like you are trying to manually do peephole optimizations that the compiler is already doing for you. The compiler is better than you at these optimizations so the only thing you are doing is screwing with the compilers ability to perform these optimizations probably resulting in slower code.

Humans are bad at this, compilers are very very very good. Humans are good at algorithmic optimizations compilers are bad at this. Do what humans do best and let the compiler to what it is good at.


Here's the list of things I would change:

Indentation (make it 2 or 4 tabs)
Field naming is inconsistent. For example, courseid should be changed to courseId. Secondly, you should append the prefix course to all fields, or omit it at all. (Don't forget to change your methods as well).
Assuming that this is a POJO (Plain Old Java Object) class, then I would recommend removing the display() method from this class. It's simply not its responsibility to display itself(S from SOLID principles). Instead, you can modify your toString() method to look something like this:

`

public String toString() {
   return "Course ID:" + id + '\n' +
            "Course name:" + name + '\n' +
            "Course description:" + description + '\n' +
            "Credit hours:" + creditHours + '\n';
}

`
And then use it in a different object/function whose responsibility is to present information to the user.

From my personal experience, I can say that the id field should be a String. If you are getting data from a server, and then convert that data to a POJO, the id field may cause an overflow in some situations if it's an integer. Even longdata type may cause an overflow if the id value is very long.
I don't think it's a professional way to declare and initialize an instance of a class the way it was written. You can do both in a single line.

This is how I would have written it:

public class Course {

  private String id;
  private String name;
  private String description;
  private float creditHours;

  public void setId(String id) {
     this.id = id;
  }

  public String getId() {
     return id;
  }

  public String getName() {
     return name;
  }

  public void setCreditHours(float creditHours) {
     this.creditHours = creditHours;
  }

  public void setName(String name) {
     this.name = name;
  }

  public void setDescription(String description) {
     this.description = description;
  }

  public String getDescription() {
     return description;
  }

  public String toString() {
     return "Course ID:" + id + '\n' +
            "Course name:" + name + '\n' +
            "Course description:" + description + '\n' +
            "Credit hours:" + creditHours + '\n';
  }

  public static void main(String args[]) {
    final Course course = new Course();
    course.setCreditHours(15.6f);
    course.setDescription("BlaBla");
    course.setId("12345567878665345453123");
    course.setName("Just a boring class");

    System.out.print(course.getDescription());
  }
}

It contains some other corrections as well.

Hope this helps!

As a side note, though it seems absolutely superfluous, I would like you to know that's it's not my intention to criticize your code, I'm simply expressing my opinion based on the experience I have.


How do I make the search in the typeahead widget more efficient

The way the regular expression engine works is, it iterates along every character in the input string, checking if a match to the pattern starts there. For example, searching for "jose" in "san jose" will result in the match being attempted at index 0, which immediately fails, and the bumpalong increments to index 1, which also immediately fails. This continues until index 4, at which point the j is matched successfully, so the pattern continues, matching o, s, e. When the pattern is just composed of ordinary characters, the length of the pattern doesn't have much of an effect, because on the vast majority of indicies, it'll immediately fail. Rarely, it'll have to iterate a few characters in the pattern before an index fails, eg searching for san jo against San Francisco at index 0, but this is uncommon and still only goes through part of the pattern. So, pattern length doesn't affect computational power required much; it isn't something to worry about.

When turning user input into a regular expression, make sure to escape the input text first, otherwise the constructed pattern's syntax could be invalid or not match what it should. (You could also make a whitelist of characters, and remove any character not on the whitelist from the input)

But for the expensive operation you want to optimize, since it looks like you're just trying to find whether a substring exists in a larger string, a regular expression is overkill - use String.prototype.includes instead. Turn the input and data strings to lower case first, to preserve case-insensitive search - for the data, do this once, on pageload, not inside findMatches. Store the lower-cased results in another property of course, lowerCity and lowerState. There may occasionally have unusual characters like San José, so call String.prototype.normalize on both the input and data, to get a string without accents and diacritics. (You need to use the regex later to construct the HTML, of course, but you don't need to use it when performing the expensive search to find the matching places)

To further cut down on computations required, a possible approach is create an object indexed by characters a to z. Have each property value be an array containing the places that contain that character. Then, when searching for a place, find the least common character in the search string, then look up and search through that array on the object. For example, when searching for "Jose", the least common character is J, so you'd look up the j property. Taking the cities listed on this page as an example, this results in having to search through only 40 cities instead of 2000. (This approach requires a bit more memory, though)

Here's a quick example of the algorithm, taking a few of the places from your gist, and displaying matches as you type:

const places=[{city:"New York",growth_from_2000_to_2013:"4.8%",latitude:40.7127837,longitude:-74.0059413,population:"8405837",rank:"1",state:"New York"},{city:"Los Angeles",growth_from_2000_to_2013:"4.8%",latitude:34.0522342,longitude:-118.2436849,population:"3884307",rank:"2",state:"California"},{city:"Chicago",growth_from_2000_to_2013:"-6.1%",latitude:41.8781136,longitude:-87.6297982,population:"2718782",rank:"3",state:"Illinois"},{city:"Houston",growth_from_2000_to_2013:"11.0%",latitude:29.7604267,longitude:-95.3698028,population:"2195914",rank:"4",state:"Texas"},{city:"Philadelphia",growth_from_2000_to_2013:"2.6%",latitude:39.9525839,longitude:-75.1652215,population:"1553165",rank:"5",state:"Pennsylvania"},{city:"Phoenix",growth_from_2000_to_2013:"14.0%",latitude:33.4483771,longitude:-112.0740373,population:"1513367",rank:"6",state:"Arizona"},{city:"San Antonio",growth_from_2000_to_2013:"21.0%",latitude:29.4241219,longitude:-98.49362819999999,population:"1409019",rank:"7",state:"Texas"}];

const placesByChar = {};
for (const place of places) {
  for (const char of new Set(place.city.toLowerCase() + place.state.toLowerCase())) {
    if (!placesByChar[char]) placesByChar[char] = [];
    placesByChar[char].push(place);
    place.cityLower = place.city.toLowerCase();
    place.stateLower = place.state.toLowerCase();
  }
}
const charFrequencies = [['z',128],['j',188],['q',205],['x',315],['k',1257],['v',2019],['b',2715],['p',3316],['g',3693],['w',3819],['y',3853],['f',4200],['m',4761],['c',4943],['u',5246],['l',7253],['d',7874],['h',10795],['r',10977],['s',11450],['n',12666],['i',13318],['o',14003],['a',14810],['t',16587],['e',21912]]
  .map(([char]) => char);
const input = document.querySelector('input');
const results = document.querySelector('div');
input.addEventListener('input', () => {
  // validate, debounce, and:
  const lowerValue = input.value.toLowerCase();
  const char = charFrequencies.find(([char]) => lowerValue.includes(char));
  if (!char) return;
  results.textContent = '';
  placesByChar[char]
    .filter(place => place.cityLower.includes(lowerValue) || place.stateLower.includes(lowerValue))
    .forEach((place) => {
      results.textContent += place.city + ',';
    });
});
<input>

Your listener has a bug: if it runs when a displayMatches is currently being debounced, but the input length is 1 or 0, the outer if will not be entered, but the timeout won't be cleared. If you enter text, then clear it, the still-running displayMatches(e.target.value); will display all places. You should clear the timeout regardless - and since you have a reference to the input element already, you can use that instead of e.target.value:

let timeId;
searchInput.addEventListener("input", e => {
  clearTimeout(timeId);
  const { value } = searchInput;
  if (value.length < 3) {
    return;
  }
  timeId = setTimeout(() => {
    displayMatches(value);
  }, 500);
});

Your fetch has no catch. If there are errors (gist deleted, site down, network offline), it would be more user-friendly to display them to the user, rather than having the app silently fail.

You should usually be quite wary of concatenating data into a string that gets inserted as HTML, eg:

${text}

It might be safe with this dataset, but for others, it would allow for arbitrary code execution (and, for example, send the user's login information in their cookies to a malicious actor).

const text = `<img src onerror="alert('evil')">`;
const html = `<span class='type-ahead__result-city--hl'>${text}</span>`;
document.body.innerHTML = html;

Either escape special characters first, or set the text by assigning to the textContent of the element after it's been created.


Create all possible character combinations of any size

Improvements

Use either argparse or sys.argv because this feels just wierd,
and kind of surprised it worked at all. I'd recommend sticking with argparse
Secondly, be sure to check out the itertools module from python, because what you are looking for are basicly permutations of a word.

New code

import argparse
from itertools import permutations

def main(string):
    for idx in range(1, len(string)+1):
        print(list(''.join(p) for p in permutations(string, idx)))

def parse_args():
    """parsing argument"""
    parser = argparse.ArgumentParser()
    parser.add_argument('-input', dest='input', type = str,
                         required = True,
                         help = "please provide string")
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    main(args.input)


React has a small amount of boilerplate you need to repeat in order to keep your components well documented, thus the usage of propTypes which is one of great things to validate data.

There is nothing wrong with how your components are structured, as react "ways" were followed.

Only thing I can observe and which can be improved is to use strict comparisons, eg: === instead of == and so on. Why?

  The identity operator returns true if the operands are strictly equal (see above) with no type conversion.

More information at MDN

As a bonus if your project uses Babel then you can use const and let for defining variables.

Also you could transform:

var {label, id} = this.props;
var other = _.omit(this.props, 'label');

To:

const {label, id, ...other} = this.props;

You can notice that we have eliminated the use of lodash/underscore.

You can find more about Babel at their homepage.


You could use a ternary operator to inline the condition into a single return statement:

private String checkTrailingSlash(String website) {
    return website.endsWith("/") ? website : website + "/";
}


VersionString (eg "1.0.2") IComparer algorithm

I adjusted the compare method slightly, making it more readable (IMO) through the use of an Anonymous type with named properties and by extracting two helper methods.

I'm not checking the result of TryParse anymore since the result is 0 for failed conversions.
Regarding performance: on my machine, your version runs ten thousand iterations in ~400ms, while mine seems to shave off around one fourth, running the same amount of iterations at ~300ms.

This should be because I moved the parsing of the versions out of the loop.
I measured this using a System.Diagnostics.Stopwatch.

EDIT: A note on performance... micro-optimizations such as the ones I've done are meaningless unless you have actually identified a real bottleneck in your code. I only ran these simplified benchmarks to make sure I wasn't making your implementation slower while getting it into a more expressive form.

public int Compare(string x, string y)
{
    if (x == y) return 0;
    var version = new { First = GetVersion(x), Second = GetVersion(y) };
    int limit = Math.Max(version.First.Length, version.Second.Length);
    for (int i = 0; i < limit; i++)
    {
        int first = version.First.ElementAtOrDefault(i);
        int second = version.Second.ElementAtOrDefault(i);
        if (first > second) return 1;
        if (second > first) return -1;
    }
    return 0;
}

private int[] GetVersion(string version)
{
    return (from part in version.Split('.')
            select Parse(part)).ToArray();
}

private int Parse(string version)
{
    int result;
    int.TryParse(version, out result);
    return result;
}

This adapted converter returns the same test results as your original one - though I haven't tried to test it more thoroughly - maybe someone can spot an edge case? ;-)


Some generic comments about your code, not related to your problem.

using namespace std;

There are some developers which consider importing a whole namespace (overwriting some standard functions with imported ones) as very bad practice. I'm not qualified enough to make comments on that, but it's something you should keep in mind.

You're inconsistent about your usage of letter casing.

int sift_down( ...
void Extract_Max( ...

That's one of the things you should fix first, there is no standard for C/C++ when it comes to casing, but at least be consistent within your source code. And even better, have a look at what everyone else in your environment does and copy that.

int sift_down(long long int *a, int i, int n){
    int l = 2 * i;
    int r = 2 * i + 1;

To abuse a very popular movie quote:

  I find your lack of properly named variables disturbing.

There is absolutely no valid reason to use single letter variable names in production code, with the only exception of dimensions (x, y, z) and loop variables (i, j, k).

You might also notice that, normally, an integer with the name i is only used inside loops. Seeing it as a parameter to a function is...disturbing.

The lack of comments is also problematic, especially when it comes to rather complex implementations.


Counting the number of click on the entire page

From my experience, this is a good first cut solution for a less experienced candidate as opposed to some experienced candidate. Also, a lot of other info is missing in question such as was there any further discussion on how to improve the solution or about adapting some good practices or how to make this code bug free etc.

I will try to list down possible issues which can to addressed:

The counter variable is a global variable here which is not recommended
The function is not reusable. Suppose, I want to track clicks in 2 different sections in same document now, the approach will fail
Any user can easily modify counter value. Anytime in window, user can do counter = 0 and the value will reset to 0 losing data
What if user refreshes the pages? In that case, do we need to store the data or losing it would be fine
If some additional functionality needs to be added (send total counter to backend server etc), so how easily it can be added without modifying the existing code

A lot of things depends on how the discussion goes after you present the solution. You can use closures, class based approach etc. I will try to list them below.

1. Use closure

(Not the best approach but better than OP's)

const clickCounter = clicker()
document.addEventListener('click', clickCounter);

function clicker() {
  let counter = 0
  return function() {
    ++counter
    console.log(counter)
    return counter
  }
}

2. Use class like approach

This is the one people generally expect and works best; covering most of the cases
You can also do the same by using ES6 classes
Adding new functionality is lot more easier here

function Counter() {
  let clicks = 0
  this.registerClick = function() {
    ++clicks
    console.log(clicks)
    return clicks
  }
}

const clicker = new Counter()

document.addEventListener("click", function() {
  clicker.registerClick()
})

Hope it helps. Revert for any doubts.


Complexity

Your answer is \$O(n^3)\$ and not \$O(n^2)\$. You have three levels of nested loops... two inside the longestPalindrome() method and another inside the isPalindrome().

Can this problem be solved with less complexity? I believe it is possible to do an \$O(n^2)\$ solution ... I'll have to think it through though.

Test-Cases

Your code may have passed the test cases, but I don't believe your code works every time... consider this:

                if(s.substring(i, j+1).length()>longestPalindrome.length()){
                    longestPalindrome = s.substring(i, j+1);
                    return longestPalindrome;
                }

You return the first palindrome you find.... longestPalindrome starts off as the empty String (length 0), and you return the first value that is longer. Your code could simply be equally broken as:

   if(s.substring(i, j+1).length() > 0){
       return s.substring(i, j+1);
   }

I don't know what the test cases are, but they need work.

Nit-picks

giving a variable the same name as a method is 'wrong'... : longestPalindrome
you calculate s.substring(i, j+1) three times in the following block:

       if(isPalindrome(s.substring(i,j+1))){
           if(s.substring(i, j+1).length() > longestPalindrome.length()){
               longestPalindrome = s.substring(i, j+1);
               return longestPalindrome;
           }
       }

Performance

Your loops could be trimmed down (a lot). These optimizations do not affect the complexity, but they do reduce the computational overhead:

for(int j = s.length()-1; j >= 0 && j != i; j--){

has redundant j-conditions. The j >= 0 can be dropped since the j != 1 will be encountered first.

Also, j is only ever used in a +1 context. You may as well change the loop conditions to be:

       for(int j = s.length(); j > i; j--){

and then replace all the j + 1 references inside the loop with plain j.

Conclusion

I am not satisfied that this solution reliably finds the longest palindrome....


Don't rely on IDs when your cases are general.  Rely on classes.
Use the DOM hierarchy to reference elements

page1 (added a container div, "toggle-image" class name):

      &nbsp;&nbsp;&nbsp;&nbsp;Page1

page2 (same changes):

      &nbsp;&nbsp;&nbsp;&nbsp;Page2

JavaScript (generalized with class selectors, sibling selectors, improved class logic):

 $(document).ready(function(){
      $('.toggle-image').attr("class", "toggle-image-expand");
      //Hide (Collapse) the toggle containers on load
      $(".toggle-container").hide();

      $("h3.trigger").click(function(){
          $(this).toggleClass("active").next().slideToggle("slow");

          $(this).children('.toggle-image')
              .toggleClass('toggle-image-collapse')
              .toggleClass('toggle-image-expand');

          return false;
      });
 });


Java 8 use streams for a "group by" feature

Thank you for a nicely formulated and formatted first question! :)

Indeed, the same result can be achieved with much less code using Java 8.

I suggest the following:

Group all the items into a Map<String, List<Item>>, equivalent of the first original for loop:

Map<String, List<Item>> itemsGroupedByCode =
  items.stream().collect(Collectors.groupingBy(Item::getCode));

Collect all the messages citing duplicate entries, equivalent of the second original for loop, but without the prefix:

String duplicatesMessage =
  itemsGroupedByCode.entrySet().stream()
      .filter(entry -> entry.getValue().size() > 1)
      .map(entry -> {
        final String duplicateValues = entry.getValue().stream()
                                                       .map(Item::getDescription)
                                                       .collect(Collectors.joining(", ", "{", "}"));
        return String.format("'%1$s' used by %2$s", entry.getKey(), duplicateValues);
  }).collect(Collectors.joining(", "));

Return the result, empty if there were no duplicates or prefixed if there were some entries:

if (!duplicatesMessage.isEmpty()) {
  return "Some of the items are sharing the same code: " + duplicatesMessage;
}
return "";

I'd also suggest to change the return type of the method to Optional<String> and return Optional.empty() instead of the empty string. But this is up to you to decide if it fits the context of your app.


Building a parent/child tree relationship

Some quick comments:

Your code style is all over the place. You have three different styles for function names: initialize_tree, PushChildren and getTopParent, pick one and stick to it. I would recommend the last one.
Your code looks more like C and not C++ with what I presume to be free functions.
item is an inappropriate name, a more typical name is Node.
You really should push the functionality to modify the nodes, or tree in general onto the item type and turn it into a class using member functions (methods).
You are allocating memory with new but never freeing it with delete thus you are leaking memory like it's 1995.
You are handling raw pointers, this is not recommended. Prefer to use the std containers or smart pointers for managing memory.
If you feel that you need to explain something to the reader, that's usually a hint that your code needs better structure. hint
std::list is slow, prefer to use std::vector on modern CPUs. Vector is \$\mathcal{O}(n)\$ insertion and removal at the front while list is \$\mathcal{O}(1)\$. However the cost of poor locality of reference on the list means that the cross-over point when the list becomes faster than the vector for just about anything at all is when you have about 100-1000 elements (depending on size) and are hitting the worst case for vector. Which I doubt you won't reach in your program. So unless you have a very specific reason to use std::list prefer a std::vector.


Welcome to CodeReview. Regarding your issue, a quick solution is:
else if (dice1 == dice2 || dice1 == dice3 || dice2 == dice3) {
    int doubleNum = dice1 == dice2 ? dice1 : dice1 == dice3 ? dice1 : dice3;
    System.out.println("Congratulations : You threw TWO - " + doubleNum + "s");
    System.out.println("You win $5");
}

The ternary operator makes the code more compact, but in this case I think it's a bit less readable than a chain of if-else.
Few other suggestions:

The while-loop can be replaced by a more convenient for-loop. From:
int round = 1;
while(round<=3){
    //...
    round++;
}

To:
for(int round = 1; round <= 3; round++) {
    //...
}

Declaring multiple variables in one line int dice1, dice2, dice3; is not considered good practice in Java.
Instead of generating a random float and then casting it to an int, generate directly an int with ThreadLocalRandom.current().nextInt(6). Docs.
You can print the first line with System.out.format. From:
System.out.println();
System.out.println("Dice 1 : " + dice1 + "    Dice 2 : " + dice2 + "    Dice 3 : " + dice3);

To:
System.out.format("%nDice 1 :  %d    Dice 2 : %d    Dice 3 : %n", dice1, dice2, dice3)

Class names should be PascalCase. Instead of Lab6_part3 you can name it Lab6Part3.
Declare a constant for the number of rounds, to make it easier to change. For example:
public class Lab6Part3 {

    private static final int ROUNDS = 3;

    public static void main(String[] args) {
        for(int round = 1; round <= ROUNDS; round++) {
            //...
        }
}

Another approach is to generate three numbers with Random#ints and calculate the frequencies:
Random r = new Random();
// Generate three random numbers from 1 to 6
IntStream diceRolls = r.ints(3, 1, 7);

// Generate map of frequencies
Map<Integer, Long> freq = diceRolls.boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

boolean winner = false;
for (Entry<Integer, Long> entry : freq.entrySet()) {
    int number = entry.getKey();
    long times = entry.getValue();
    if (times == 3) {
        // Three of a kind ...
        winner = true;
    } else if (times == 2) {
        // Two of a kind...
        System.out.println("Congratulations : You threw TWO - " + number + "s");
        System.out.println("You win $5");
        winner = true;
    }
}
if(!winner) {
    // Did not throw anything of value
}


Date and time of an article in a humanized and localized way

Adding time zone support

Add a new argument to your function: now. This should be the localized datetime of the client. Compare now to the current server datetime and adjust the formatted time by the difference between them. Boom, timezone support added.

That said you cannot get the client timezone server-side. Look into client-side solutions with JavaScript (either full client-side date formatting, or phoning home). This should start you off on the right track.

On with the code review.

Tidying up the code

Variable and function naming

info and value are excessively vague.
datetimeformat_jinja() is a bit eccentric  as a function name, as its not in imperative form (eg format_datetime).

String formatting

Concatenating strings with addition is considered bad practice is Python. You should format individual elements of your message together, rather than starting with info='' and adding new parts as you go along. Use str.format() (or %s-formatting with Python 2.5 and below) to achieve this.

The If-elif-else chain

In lines 9 through 33 you copy-pasted the same logic twelve times over; that's a sure-fire sign you need to express things more generically.

Style

Take this suggestion for the petty nothing it is, but—please, please, please—unless you're following the style guidelines of your team or employer, read and obey PEP 8.

Result

MONTHS = ('Jan', 'Feb', 'Mar', 'April', 'May', 'June',
          'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
FORMAT = '%H:%M / %d-%m-%Y'

def format_datetime(to_format, format=FORMAT, locale='en'):
    now = datetime.now()
    if datetime.date(to_format) == datetime.date(now):
        date_str = _('Today')
    elif (now - to_format).days < 2:
        date_str = _('Yesterday')
    else:
        month = MONTHS[to_format.month - 1]
        date_str = '{0} {1}'.format(to_format.day, _(month))
    time_str = format_time(to_format, 'H:mm', locale=locale)
    return "{0}<br>{1}".format(date_str, time_str)


Function that generates steps time series from user given values

Your type checks are distracting, they are probably better extracted to a separate function.

def check_type_or_raise(obj, expected_type, obj_name):
    if not isinstance(obj, expected_type):
        raise TypeError(
            "'{}' must be {}, not {}".format(
                obj_name,
                expected_type.__name,
                obj.__class__.__name__)

Note that this has slightly different behaviour than your code: you would e.g. accept a step_width of 2.5 and convert it to a 2. This is typically not what you want, so I think it is better to raise for such cases.

If you don't mind the conversion, then you probably don't need to wrap your calls to int() in a try and re-raise, as you will already get a nice error, e.g.:

>>> int('abc')
ValueError: invalid literal for int() with base 10: 'abc'

I would also refactor your code to have the output creation happen in a single, common place, after some manipulation of the arguments:

def steps(step_width, values, repeat=1, size=None):
    check_type_or_raise(step_width, int, 'step_width')
    check_type_or_raise(repeat, int, 'repeat')
    values = np.asarray(values)
    if size is not None:
        check_type_or_raise(size, int, 'size')
        # This does rounded up integer division without floating point
        repeat = (size - 1) // (len(values) * step_width) + 1
    return np.tile(np.repeat(values, step_width), repeat)[:size]