Function to use projections in legacy algorithms

Design review
I don’t think you gave a lot of thought to what this library would be actually useful for.
Let me start by just considering the idea of proj() in complete isolation, ignoring any real-use context, and just considering it as a clever trick. From that perspective, I’d have to say that proj() is not a bad idea… but perhaps not the best way to go about it.
Here’s what a ranges call to sort() might look like:
std::ranges::sort(b, e, {}, &Pair::Key);

Here’s what proj() promises, at best:
std::sort(b, e, proj(std::less{}, &Pair::Key));

Here’s what else is possible in C++17, and possibly even before if you’re willing to put in the work of re-implementing std::invoke, etc. (of course it’s also possible in C++20, but… we’ll get to that issue shortly):
myns::sort(b, e, {}, &Pair::Key);

That is, you could implement a wrapper around std::sort() that handles the projection transparently.
For the user, that’s shorter, simpler, and doesn’t require manually specifying the comparator.
Not to mention that when I can advance to C++20 and use the full power of std::ranges, all I need to do (very basically) is a find-replace for myns to std::ranges. If I had these little proj() sub-calls everywhere, the code transform becomes MUCH more complex, and possibly tedious and/or dangerous.
And while you’re at it, why not implement myns::sort() as a neibloid, to get all the sweet, sweet benefits that go along with that?
So if you really want the benefits of projections, why wouldn’t you do that?
Yes, I realize I’m basically saying “re-implement std::ranges”. As a halfway solution proj() only halfway satisfies. What’s the point of that? If you’re going to implement a library tool to make coders’ lives easier, why half-ass it? Who benefits from a mediocre solution? I guess the person writing the library gets to save on some work… but the whole point of library writing is that the library writer is taking on extra work so library users don’t have to. Making things easier for the library writer is silly. You should be concentrating on making things easier for the users.
And by the way, there are a bunch more complications to making something like proj() generally usable that I haven’t mentioned. Like, you’ve created a variant that works with most of the standard algorithms… but it won’t work with std::find() (no predicate, so no Fn). Won’t work with std::merge() (has a predicate, but has two projections). By the time you sort all that out, and test it all rigorously enough to show that it’s trustworthy in production code, you might as well have just used range-v3.
Except… and this is the biggest issue with this whole idea…
This code won’t even compile in C++17. It needs C++20. C++20… where… std::ranges already exists.
So who exactly is this library for?

It can’t be for C++17 (or before) users. (Won’t compile.)
It makes no sense for C++20 (and later) users. (Because if they want a projection in a legacy algorithm, they can just use the std::ranges version. In your example, std::ranges::sort().)

Are you targeting the hypothetical subset of users who are targeting C++20 with their project, but are using a C++20 compiler/library that has lambda templates, std::identity, and constexpr std::invoke… but not the ranges algorithms? That’s a bizarre target group, to say the least. I mean, who targets a C++ version—or uses a specific feature, like projections—without a compiler/library that actually supports it? Not to mention it’s a rather ephemeral group, because presumably if they’re targeting C++20, they could just use std::ranges as soon as the features they need become available in their chose compiler/library, making proj() just a weird stop-gap they would use for a while, then have to weed out of their code base later.
The bottom line is: proj() makes no sense. The only people who could use it… don’t really need it.
(Or, AT BEST, they could maybe use it NOW, for the brief period when their chosen platform supports everything needed to make proj() work, but doesn’t include std::ranges. But, frankly, I’d rather write the lambda than use a mysterious 3rd-party library that’s only going to be useful for a few months then become a legacy maintenance burden.)
From where I’m sitting, this looks like a case of nerd sniping. A neat little theoretical problem became so distracting by its intellectual challenge, that you completely ignored the surrounding real-world problems that are, in point of fact, much more important.
Code review
There’s not much code to review, of course, but….
auto
constexpr proj(//...

It’s pretty bizarre to write the constexpr after the auto. I’ve never seen that done before. I can’t see any sensible reason to adopt this style; it’s only likely to cause confusion.
constexpr proj(TFn &&Fn, TProj &&Proj = {})

Putting the type modifiers next to the variable name, rather than with the type, is a C convention, not a C++ convention. In C++, types matter more, so it makes more sense to say TFn&& Fn.
Also, it is a little peculiar to name variables with UpperCamelCase. UpperCamelCase is usually reserved for template argument names. In other words, TFn&& fn is more conventional.
template<typename TFn, typename TProj = std::identity>
auto
constexpr proj(TFn &&Fn, TProj &&Proj = {})
{
  return [&Fn, &Proj]<typename... TArgs>(TArgs &&...Args)
  {
    return std::invoke(std::forward<TFn>(Fn),
                       std::invoke(std::forward<TProj>(Proj), std::forward<TArgs>(Args))...);
  };
}

The thing that bothers me most about this function is that you:

take the two function arguments as forwarding references
place them into the closures as lvalue references; then
forward them within the closure.

Now, I will admit here that I haven’t sat down and reasoned this through as hard as it really deserves (because it’s late, and because I don’t see the point of the function in any case), but even from a cursory inspection it smells wrong. The smelly part is that you “forget” you’re dealing with forwarding references on that second step.
If the two parameters are lvalues, then no harm, no foul. All the forwarding references will collapse to lvalue references, and the forward()s will degenerate to… well, nothing, effectively; just lvalue references. So you have lvalue references all the way through. All cool.
But if a parameter is an rvalue, then the forward()s will degrade to rvalue references, and may end up moving the argument. So imagine you have a call to, say, sort(), where proj() has been given an rvalue function object (for either parameter, doesn’t matter). On the first execution of the comparator—that is, the first time that lambda proj() returns is called—it will move the function object… leaving it in a moved-from state… so the second time the comparator/lambda is executed, it’s using an “empty” function object. Exactly what damage this will cause depends on what using a “moved-from” function object means, which will depend on the function object type. But in any case, it’s not good.
Okay, put simply:

You have correctly taken the function arguments as forwarding references…
… and you have correctly perfect-forwarded them in the invoke() expressions…
… but you have NOT perfect-forwarded them in the lambda capture.

You need perfectly-forwarded lambda captures. That is NOT trivial… but not too hard (tip: use std::tuple and a mother-ton of decltype(TFn), etc.; don’t forget to mark the lambda mutable).
Summary
As an experiment to explore stuff like projections and perfect-forwarding, this is actually a really neat idea.
As a practical library… I’m not seeing it. Just about the only people who could use it won’t need it. And the tiny demographic who could use it, but who can’t use the superior std::ranges solution, would be unwise to use it (better to wait until their platform supports std::ranges).
The implementation is sound but for that one tricky hiccup: You have perfectly-forwarded everything except the lambda captures. Fix that, and I think it should be a sound implementation. For full practical usability (such as it is), you’d need a couple of overloads for cases not covered by a single predicate and a single projection (for example, an overload without a predicate, for things like std::find(), std::count(), std::remove(), etc.; plus a few other overloads for the more esoteric cases), but once you’ve got the one working, that should be no problem.


Toward optimization and better functionality

consider using short array syntax [] instead of old-fashioned array()
do not designate redundant captured groups such as ([0-9]{2})...([0-9]{2}) if you only need the 1st captured group ([^`]*?)
regex [0-9] has a concise equivalent for designating digits - \d

All those preg_replace calls in the initial approach can be combined into a single call using regex alternation group /-us|(\d{4}|\s)$/ for combining the needed patterns. The \s$ patten could also be excluded from combined pattern in favor of rtrim function call.As /-/ is the only pattern that is too simple and requires different replacement string ' ' (space) - it deserves to be a simple string replacement with str_replace function.

The final optimized approach:

$input = ['http://example.com/blue-bloods-s10e13-more-text/','http://example.com/charmed-2018-s02e11-more-text/',
          'http://example.com/dynasty-2017-s03e11-more-text/','http://example.com/magnum-p-i-2018-s02e14-more-text/',
          'http://example.com/fresh-off-the-boat-s06e13-more-text/','http://example.com/hawaii-five-0-2010-s10e14-more-text/',
          'http://example.com/american-housewife-s04e13-more-text/','http://example.com/love-us-s01e13-more-text/'];

foreach ($input as $value){
    preg_match('/http:\/\/example.com\/([^`]*?)-s\d{2}e\d{2}/', $value, $matches);
    $name = str_replace('-', ' ', preg_replace('/-us|(\d{4}|\s)$/', '', $matches[1]));
    echo $name . "<br>";
}

The output:

blue bloods
charmed
dynasty
magnum p i
fresh off the boat
hawaii five 0
american housewife
love


The orthodox (and functional) approach in Ruby is:

def find_type(types, str)
  types.detect do |type|
    type[:criteria].any? do |criterion|
      str =~ /#{criterion}/i # or Regexp.new(criterion, "i")
    end
  end
end


Implementation of database access class [PHP]

The reason for singletons

First, you've got some misunderstandings about what singletons accomplish.  PHP automatically keeps all variables separate from request to request, so the fact that you have simultaneous requests makes no difference for the singleton pattern.  Rather, the singleton pattern makes sure that you only have one instance of a particular class inside a single request.  Your constructor is protected, and so the only way to get a DB connection object is through the static getInstance method, which makes sure there is only ever one instance.  The relevancy of this to a DB connection class is that if the system can create more than one instance of your DB connection class per request, and if your DB connection class opens a new connection to the database everytime it is created, then you can potentially get many open connections to MySQL from a single HTTP request.  That's a quick way to overload your database's open connection pool and end up with failed requests.  It doesn't have anything to do with having multiple requests at the same time.

The reason to not use singletons

That being said, while this is a good stepping stone to a better application, it shouldn't be your final stepping point.  Singletons are, in essence, a design pattern that should be considered deprecated.  The reason is because they break dependency injection.  If you're new to this concept (we all were at some point) then it is absolutely worth a lot of googling and reading.  Dependency injection, other than making your code more flexible and easier to maintain, also makes it possible for you to mock and test your code thoroughly (via unit and integration tests).  It is a completely different way of building an application, so I wouldn't expect you to just throw everything away and start over.  However, it is never to soon to start learning, so you can do yourself a favor and start reading about these things now.

Oftentimes with dependency injection you will have a dependency injection container that handles the details for you, and these containers usually have a way of flagging classes as "singleton" classes, which means that the dependency injection container will never initialize more than one.  At that point in time though, the classes don't implement the singleton pattern: they act like normal classes with a normal constructor, and rely on the DI container to make sure there is only one.

Passwords in config files

This is fairly common, and is normally fine.  Just make sure that the file with your DB credentials isn't committed to your code repository.

Public functions

The other problem you have is that you are trying to stick your data access method directly into your DB connection class.  You don't want to actually do that.  For an application of almost any size, you are going to quickly end up with far too many methods, and this class will become impossible to read/update/maintain.  It's all about the separation of concerns.  Ideally, your DB connection class would just be a simple wrapper around the PDO object, and your models classes (depending on how you organize your application), would then be responsible for using the DB connection class to execute their own queries, as is relevant to them.


Sum the exponents of the prime factors of a number

In addition to the other answer:

There is no need to generate all primes up to n. You can generate them up to sqrt(n). If something remains after the division by these primes, it is a prime.
There is no need to generate any prime numbers at all. This code does exactly what you need:

public int primeExponentsCount(int n) {
    if (n <= 1)
        return 0;
    int sqrt = (int) Math.sqrt(n);
    int remainingNumber = n;
    int result = 0;
    for (int i = 2; i <= sqrt; i++) {
        while (remainingNumber % i == 0) {
            result++;
            remainingNumber /= i;
        }
    }
    if (remainingNumber > 1) {
        result++;
    }
    return result;
}

The time complexity of this algorithm is O(sqrt(n)). The space complexity is O(1). As you can see, there is much room for improvement for your initial solution in terms of efficiency.

Now about the code itself:

Writing self-evident comments is a bad practice. For instance, this comment doesn't serve any purpose.

// initialize the sum
int result = 0;

I would delete it.
Error handling. It looks like your primeExponentsCount does not expect to receive a negative number. Instead of returning a wrong result, I'd throw an exception:

public int primeExponentsCount(int n) {
    if (n < 0)
        throw new IllegalArgumentException("The number must be non-negative");
    ...
}

There are too many blank lines inside methods, in my opinion(it is conventional to separate methods from each other with an empty line, but it is not common to insert random blank lines inside a method's body).


A few fairly minor things:

Constants for the characters

Instead of using the constants, you can just use a character inline:

if(input[index] >= 'a' && input[index] <= 'm')

It's worth noting though that a literal character will be a char rather than an int like your constants are (won't affect anything in this program though).

using namespace std;

It's fine in short programs like this, but as you hinted that you're fairly new to C++, I wanted to mention that this can be a bad habit to get into.  In particular, in large applications with many different segments of code, this can cause naming clashes.

This question on SO addresses the problems it can cause.

Naming

I would probably call rot, rot13 since there are other kinds of rotations.  This is mainly me just being overly picky though :).

Strange Character For Space

  The space character is showing up as a crazy character in my terminal screen, I'm assuming it's because of character encoding, although I could be wrong.

rot13 traditionally only operates on alpha characters (a-z and A-Z), so your space characters should not be changing.

I believe your program has a bug in it:

else if(input[index] <= UPPER_N && input[index] <= UPPER_Z)

If this is not a bug, you should know that  this will be always be true if input[index] <= UPPER_N, so really there's no point in the second conditional.

Anyway, I think what's happening is that the space character (and anything under 'N') is falling into this block when it shouldn't be.

Space is ASCII 32, so it's getting changed to 19, which is not a printable character.

while vs for

Your loop seems to fit the construct of a for loop very well, so I might consider using that:

for (int inputSize = input.size(), index = 0; index != inputSize; ++index) {

}

This comes down to personal preference though.

You should usually try to match the return type of a method

std::string::size() doesn't return an int; it returns a std::string::size_type which is always (in every implementation I've ever seen anyway), a size_t (which is in turn an unsigned 32 or 64 bit integer depending on the platform and compiler).

Anyway, when working with standard containers (or really APIs in general), unless you have a reason to use a different type, I would try to stick with the return type specified.  For example:

for (std::string::size_type len = input.size(), idx = 0; idx != len; ++idx) {
    //input[idx] = ...;
}

A potential implementation

I suspect that the if-else tree can be simplified a bit using isalpha and family, but this is what I might implement your algorithm like;

std::string rot13(std::string input) {

    for (std::string::size_type len = input.length(), idx = 0; idx != len; ++idx) {
        if (input[idx] >= 'a' && input[idx] <= 'm') {
            input[idx] = input[index] + 13;
        } else if (input[idx] >= 'n' && input[idx] <= 'z') {
            input[idx] = input[idx] - 13;
        } else if(input[idx] >= 'A' && input[idx] <= 'M') {
            input[index] = input[index] + 13;
        } else if(input[idx] >= 'N' && input[idx] <= 'Z') {
            input[index] = input[index] - 13;
        }
    }

    return input;

}

To get a little carried away for a moment, you could also implement it using iterators.  Using iterators would allow you to apply it to any container that implements iterators (all of the standard containers and plain pointers).

template <typename Iter>
void rot13(Iter begin, const Iter& end) {

    while (begin != end) {

        //Doesn't need to be here, but I'm lazy and don't like
        //typing *begin over and over again.
        char& c = *begin;

        if (c >= 'a' && c <= 'm') {
            c += 13;
        } else if (c >= 'n' && c <= 'z') {
            c -= 13;
        } else if (c >= 'A' && c <= 'M') {
            c += 13;
        } else if (c >= 'N' && c <= 'Z') {
            c -= 13;
        }

        ++begin;

    }

}

Note that this modifies a container in place rather than creating a copy:

char str[] = "Hello World";
rot13(str, str + strlen(str));
std::cout << str << std::endl;
rot13(str, str + strlen(str));
std::cout << str << std::endl;

Would output:

Uryyb Jbeyq
Hello World

You could of course modify it to operate on a copy instead though.


What do you think of this improvement of Linq's GroupBy method?

I think the reason it's done this way is to make GroupBy() consistent with the rest of LINQ: everything is as lazy as possible, so that following queries can be efficient.

And there already is a method that does almost the same thing as your GroupToDictionary(), it's called ToLookup().


You have:

if (db.BadgeAssignments.Any(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId))

And later:

.Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)

The two lambdas:

bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId
bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId

Identical. .Any is \$O(n)\$, meaning worst-case, it will have to iterate all elements of the source to find one that matches the predicate; Where is also \$O(n)\$, meaning it will traverse all elements of the source to find all that match the predicate.

currUserScore = db.BadgeAssignments
                  .Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)
                  .Sum(bba => bba.BadgeAssociated.Points);

This does it once, and will return 0 if no match is made while iterating BadgeAssignments... and that leaves you with a single linq statement =)

The predicate could be simplified further if you encapsulated it into a separate method:

currUserScore = db.BadgeAssignments
                  .Where(bba => IsMatch(bba, userId, courseId))
                  .Sum(bba => bba.BadgeAssociated.Points);

The IsMatch function (//todo: find a better name) is the lambda's body:

return bba.UserIdReceiver == userId
    && bba.BadgeAssociated.CourseId == courseId;


Scale-able API development with macro definitions

What you've currently got expands to something like this:

PYBIND11_PLUGIN(SPerson)
{
    typedef SPerson Type;
    py::module Module("Person", "A person descriptor")
    py::class_<SPerson> Binding(Module, "\"Person\"");
    Binding.def_readwrite("Age", &Type::Age);
    Binding.def_property("Name", &Type::getName, &Type::setName);
    return Module.ptr();
}

I think you've got a stray # in front of NAME in one place.

Anyway, is there a technical reason you need SPerson and Person to be different identifiers? That seems like it would increase confusion (two names for the same entity, depending on what language you were writing) rather than decreasing it.

And the string "A person descriptor" is just internal documentation, right? It's not important to the code's semantics, i.e., it's just a comment? If so, it would almost certainly be better to omit it. Remember, you're aiming this code at people who will cut-and-paste it and change just what they need in order to make it work; I foresee a lot of

PLUGIN_BEGIN(SPerson, "Person", "A person descriptor")
PLUGIN_BEGIN(SDog, "Dog", "A dog descriptor")
PLUGIN_BEGIN(SVehicle, "Vehicle", "A vehicledescriptor")
PLUGIN_BEGIN(SWeapon, "Weapan", "A person descriptor")
PLUGIN_BEGIN(SEnemy, "Enemy", "A person descriptor")

in your future, unless you take steps now to eliminate those redundant fields. Remember Murphy's Law: Whatever can go wrong, will go wrong. So if you don't want anything to go wrong, you should try really hard to eliminate any element of the system that can go wrong.

PLUGIN_BEGIN(Person)
    PLUGIN_MAP_FIELD(Age)
    PLUGIN_MAP_PROPERTY(Name)
PLUGIN_END

If your users are likely to show any personal initiative whatsoever — if they're likely to want to understand the tool you give them, instead of just using it passively and/or asking you personally if they have questions — then I would also advise not monkeying with pybind11's names for things. Don't say FIELD if what you mean is READWRITE.  This will help the user-programmer when something inevitably breaks and he has to go google the name of the thing; it'll help because there will be one name (readwrite) instead of two (readwrite and field), which means his googling can be twice as effective in the same amount of time.

This will also help you, the library writer, when it comes time to extend the library. Under your current system, how would a user expose a const data member to pybind11? He can't. You need a new macro to deal with const fields. pybind11 has an existing name for such things (readonly), but you haven't made up your own name for them yet. Do you go with FIELD_READONLY, or CONST_FIELD, or suck it up and go with READONLY even though you didn't originally use READWRITE...? It's a bit of a mess. Whereas, if you make a design decision to stick with pybind11's names for things from the get-go, you'll never have to waste your own time on such questions again; the answer is always "go with what pybind11 called it."

Your macro system limits you to one Python class per Python module. That's okay, right?

Syntactical nitpick: Those trailing backslashes are going to bite you one day. (I don't even know if putting a backslash as the last character of a source file is well-defined!) Instead of

#define FOO \
        bar \
        baz \
/* warning: this blank line is semantically significant */

I'd strongly recommend

#define FOO \
        bar \
        baz


Scaling decimal numbers up within bounds of limit

double smallest = Double.MAX_VALUE;

This is even larger:

double smallest = Double.POSITIVE_INFINITY;

    if (exp < smallest) {
        smallest = exp;
    }

Unless you need to do something else in the body, like remembering an index, this can better be replaced with:

    smallest = Math.min(smallest, exp);

Anti-pattern: The -1 you describe is a 'magic value', which in this case, after a bit of reverse engineering, just divides scaling by 10, like so:

double scaling = Math.pow(10, Math.abs(smallest)) / 10;

This is clearer to casual readers of your code, but still a magic number unless rationalized in the comments.

Pitfall: There is no check if entry.raw is actually not larger than one. If it is, your approach breaks.

Performance / Precision / Confusing: don't calculate base-e log for every number and then base-10 exp (that combination alone is already confusing enough). Just find the very smallest number (not the smallest exponent) and set double scaling = 1.0 / smallest;. To get a number-correct result to your current implementation, because of the base confusion, it would be:

double scaling = 40.287487705590465 / smallest;

Note that this just moves the 'magic number' problem. You need to rationally explain the value here, and not just state that it 'packs things better'.


Does iterating through a large data set in a Map each time i click impact the performance?

Technical improvements

use albumMap.values() to get a Collection<Album> directly instantiated as list, which supports positional access get(index). So no need for array and filling loop. See Listing 1.
use some of Android's ListView interfaces which usually provide a convenient method on their underlying data model like getItemAtPosition(position). See Listing 2.

Listing 1: Q: How to convert map to list

List<Album> albums = new ArrayList<Album>(albumMap.values());

Listing 2: Vogella's Tutorial on Android's ListView

ListView albumsView = (ListView) findViewById(R.id.listview);

// fill albums data to model (adapter implementation)
albumsView.setAdapter(adapter)

albumsView.setOnItemClickListener(new OnItemClickListener() {

  @Override
  public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
    final Album album = (Album) parent.getItemAtPosition(position);
    // your implementation
  }
}

Design improvements

album.getAlbum() gets the title of an album, so rename property|getter to title|getTitle()
keep the event-handler short and extract all action/intend creation into separate method

References

Answer on using RecycleView with OnItemClickListener
Tutorial: Android working with RecyclerView
Android Official Guide on AdapterView


If I understand your problem well, the problem is that you don't want an if clause to become too long and that you have a problem with empty parameters. Your way of checking seems right to me, for the other part I asked myself if you can't just add something like this to the functions namecheck() emailcheck() and messagecheck():

 if (strlen($fname) == 0 || strlen($lname) == 0) return false;

Furthermore in your code line with the checks you have two times the emailcheck instead of the messagecheck once:

  if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($emailcheck ===TRUE)) {

Good luck, hope it helped.

Jef


Project Euler #7: What is the 10,001st prime number?

More efficient... look at Sieve of Eratosthenes for a huge speed up. I'm ignoring it for now, as it comes again and again.

for (int num = 2; num < 10000000; num++) {

The condition num < 10000000 is plain wrong. It works, but makes no sense. If the requirements change, the limit may be too small. Just drop it. Or better, replace it by counter < 10001 (nobody says, that you have to test num, any condition is allowed).

You surely know that 4, 6, 8, ... are no primes, so you can skip them. Iterate over odd numbers only and set the initial value of counter equal to one (accounting for the skipped prime 2). So you get something like

for (int num = 3; counter < 10001; num += 2) {

This hardly helped the speed, but doing the same thing in

for (int factor = 2; factor < num; factor++) {

surely helps. You only have to deal with odd num, so you test only odd factors.

Observe that for each factor, also num / factor is a factor and the smaller of the two is no bigger than the square root of num. So you can use

int limit = (int) Math.sqrt(num);
for (int factor = 3; factor <= limit; factor += 2) {

        if (isPrime) {
            primeNum = num;
            counter++;
        }

This looks a bit strange. It works, but you assign primeNum just in case it'll be needed. A rather useless variable as num would do, too.

Even for such a rather trivial tasks you should use methods. Write small methods and let each of them do just one thing. Especially, never mix user input or output with computation as this makes the code perfectly non-reusable. Try to write methods like

boolean isPrime(int num);
int nextPrimeAbove(int num);
int nthPrime(int n);


Composing QGIS expression based on a QGIS layer tree

You do quite a lot or repetition. Using str.format you should be able to make your code smaller by using a comprehensions or map.
Doing these inside a ''.join can allow you to reduce a lot of your code.
And if you make a list to iterate over you can do this all in two comprehensions.
I also think you should make a comprehension to get the layer name from your group.children().
Finally you will want to build formula1 from this which can be done with another string with format.

As all the strings used to format the data are constant, you can use UPPER_SNAKE_CASE variable names to say it's a constant.
And should result in something like:

SCORE_FORMATS = [
    '"{}_Score" = 1 OR ',
    '"{}_Score" = 2 OR ',
    '"{}_Score" = 3 OR ',
    '"{}_Score" = 4 OR ',
    'coalesce({} = 2, 0.00)*2 OR ',
    'coalesce({} = 3, 0.00)*3 OR ']
FORMULA1 = "CASE WHEN {3}{5}>=9 THEN 4 WHEN {2}{4}>=6 THEN 3 WHEN {1}THEN 2 WHEN {0}THEN 1 ELSE 1 END"

Finally to make the main part of your code, formula1 to final_formula, you can use the following as I explained above:

for group in policy_group.children():
    group_children = [layer.layerName() for layer in group.children()]
    formulas = [
        ''.join(map(formula_format.format, group_children))
        for formula_format in SCORE_FORMATS
    ]
    formula1 = FORMULA1.format(*formulas)
    formula2 = formula1.replace("OR >=9 THEN 4 ", ">=9 THEN 4 ")
    formula3 = formula2.replace("OR >=6 THEN 3 ", ">=6 THEN 3 ")
    formula4 = formula3.replace("OR THEN 2 ", "THEN 2 ")
    final_formula = formula4.replace("OR THEN 1 ELSE 1 END", "THEN 1 ELSE 1 END")

The output of this function only uses final_formula where I was originally unsure if you were using all the formulas.
You also used the wrong delimiter for the coalesce.

To improve on the above I'd change SCORE_FORMATS to be tuples of (delimiter, format).
This will allow you to easily change both for all your different functions.
This will also change the ''.join(map(...)) to use your delimiter and will remove the need for all the replace calls.

This unfortunately makes the FORMULA a bit longer,
but give us an excuse to use implicit string concatenation which can make it much easier to read.

SCORE_FORMATS = [
    (' OR ', '"{}_Score" = 1'),
    (' OR ', '"{}_Score" = 2'),
    (' OR ', '"{}_Score" = 3'),
    (' OR ', '"{}_Score" = 4'),
    (' + ', 'coalesce({} = 2, 0.00)*2'),
    (' + ', 'coalesce({} = 3, 0.00)*3')]
FORMULA = ('CASE WHEN {3} OR {5} >= 9 THEN 4 '
            'WHEN {2} OR {4} >= 6 THEN 3 '
            'WHEN {1} THEN 2 '
            'WHEN {0} THEN 1 '
            'ELSE 1 END')

for group in policy_group.children():
    group_children = [layer.layerName() for layer in group.children()]
    formula = FORMULA.format(*[
        delimiter.join(map(formula_format.format, group_children))
        for delimiter, formula_format in SCORE_FORMATS
    ])


Don't do from something import *.

Either import what you need:

from datetime import datetime

Or import the entire module and use qualified names:

import datetime
...
    start = datetime.datetime.now()

Importing everything is dangerous because it can shadow already existing names. One such example:

import datetime
from datetime import *
# `datetime` as a class shadows `datetime` as a module

You might want to do a little reading on the subject.

This whole thing makes no sense:

RET_NO = 0
RET_YES = 1
RET_MAYBE = 0.5 # haha :)

Instead of RET_YES / RET_NO you sould use True and False.

You don't have to call super(...).__init__  if the class only inherits from object.

Why do you print something to stdout and then raise an empty exception?

Instead of

print 'WARN: Contains() called before elements were inserted!!'
raise Exception()

you should do

raise Exception('contains() called on empty tree')

In the method Tree.contains, you already checked if self.root is None, so this

return self.root.contains(element) if self.root else RET_NO

can be simplified to this

return self.root.contains(element)

Instead of contains you can define the __contains__ method. Then you can use the in keyword:

return element in self.root

Although in this particular case it's less readable, so it's probably better to just stick with contains.

Method Tree.bulk_insert is just wrong. There's no point in having an empty list for a default argument. In the for loop you modify the list while iterating over it, and on each iteration you call the len function. Why? Even the C-style

for i in range(len(elements)):
    self.insert(elements[i])

would have been better.

This is the way to do it in Python:

def bulk_insert(self, elements):
    for element in elements:
        self.insert(element)

That way elements doesn't have to be a list, it can be any iterable.

Does your tree have a special requirement that it cannot contain the same element twice? If not, then in Node.insert there should be no

if self.element == element:
    return

Remove unreachable statements. There's no point in having

raise Exception('Should never reach this line!')

in Node.contains, while having it in Node.insert effectively makes the method raise an exception in almost all cases. Actually if you fix the error mentioned in the previous point, it would be in completely all cases.

The comment

"""
Return size
"""

is pointless. The method itself is called size, so it's obvious that it returns size. Also, the name size is quite ambiguous to begin with. Either don't restate code in comments, or actually explain what the method does (eg. how do you compute the size). A more suitable name would be number_of_elements, or maybe something shorter but descriptive like nelems.

The docstring of Node states:

"""
Node class to be used in Tree instances.
"""

I'd say it can possibly be used in other classes than Tree, so don't create a tight coupling between the two, even if it's just in comments.

size can be a property:

@property
def size(self):
    ...

That way you won't have to call it:

left_size = self.left.size if self.left else 0

Even tests should be documented. Add docstrings explaining what do the test_* methods test. Your non-test code also lacks documentation.

The docstring of Tree says "O(N) access on elements". This is not quite true, for two reasons:

your Tree and Node classes don't even allow you to access elements, they only allow you to check whether an element is present in the tree,
\$O(n)\$ is the worst case; average asymptotic complexity is \$O(log(n))\$.

Have you by chance forgotten to implement a remove method? Or you just wanted an insert-only tree?

$$⸻$$


Using an AsyncTask instead would be much better. You've got many callbacks to the UI thread, all of this you could do in the post execute method instead:

private class LoginTask extends AsyncTask<Void, Void, String>{

    private String username;
    private String password;
    private Exception exception;
    private boolean isSaveSuccess;

    public LoginTask(String username, String password){
        this.username = username;
        this.password = password;
    }

    @Override
    protected String doInBackground(Void... voids) {
        try{
            String result = NetUtil.loginByGet(username, password);
            //Grab the token
            isSaveSuccess = InfoUtil.saveUserInfo(LoginActivity.this,token);
        }catch(Exception ex){
            //Catch any given exception to use it in the post execution (e.g. show a toast)
            this.exception = ex;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        //Here it goes your UI logic
    }

}

To call it, just launch an execution when login button is clicked:

public void doLogin(){
    mButton.setClickable(false);
    mButton.setText("Loading...");
    String username = mUserName.getText().toString().trim();
    String password = mPassWord.getText().toString().trim();
    new LoginTask(username, password).execute();
}


namespace Revolution;
class engine

I do not understand these names.  I would have expected to see something database related.  Neither Revolution nor engine says database to me.

final public function __construct()
{
    $this->Initiate();
}

final public function Initiate()
{
    global $_CONFIG;
    if(!$this->initiated)
    {
        $this->setMySQL('connect', mysql_connect);
        $this->setMySQL('pconnect', mysql_pconnect);
        $this->setMysql('select_db', mysql_select_db);
        $this->setMySQL('query', mysql_query);
        $this->setMySQL('num_rows', mysql_num_rows);
        $this->setMySQL('fetch_assoc', mysql_fetch_assoc);
        $this->setMySQL('fetch_array',mysql_fetch_array);
        $this->setMySQL('result', mysql_result);
        $this->setMySQL('free_result', mysql_free_result);
        $this->setMySQL('escape_string', mysql_real_escape_string);

        $this->initiated = true;

        $this->connect($_CONFIG['mysql']['connection_type']);
    }
}

As a general rule, you don't want to do your database connection in your constructor.  You should be able to create an instance without having it connected to a database.  What you might consider doing is creating a fetchConnectedInstance that runs the constructor and initializes it, returning the result.  You should pass $_CONFIG into this function and Instance.  That way you can connect to more than one database at once.  Your version is almost a Singleton but not quite.

I don't see the point in things like

        $this->setMysql('select_db', mysql_select_db);
        $mydatabase = $this->mysql['select_db']($_CONFIG['mysql']['database'], $this->connection);

Note that $this->mysql['select_db'] is longer than mysql_select_db, so it's clear that this is not a convenience abbreviation.  What is the benefit?  It almost seems like you are trying to make a base class that you can reuse for other database types.  Unfortunately, I don't know that you can rely on each database offering the same abilities.  For example, a key/value database is not going to offer some of the capabilities that a relational database will.

If you are going to alias something, then there should be a reason.  If there's a reason, you should comment on it so that the reader knows it.  As a general rule, if you are clever, explain to the reader how it's clever.  That way, the reader doesn't need to be clever just to read the code.

I don't like the use of $this->initiated.  It doesn't seem necessary.  Either don't care about that situation, or check something more direct like the existence of $this->mysql.

/*-------------------------------Secure MySQL variables-------------------------------------*/

final public function secure($var)
{
    return $this->mysql['escape_string'](stripslashes(htmlspecialchars($var)));
}

This is not the right way to handle this.  The htmlspecialchars function should not be called before putting something in the database.  It should be called after fetching something from the database and before outputting it in HTML.  It should be the last thing called before outputting.  Doing it this way risks someone finding a special input that will evade htmlspecialchars and then be enabled by the stripslashes/mysql_real_escape_string.  Also, htmlspecialchars can change the data if used at this point.  What if you want to store HTML in the database?  E.g. user entered content.

You also aren't using bind parameters at all.  In general, bind parameters are considered a safer way of handling things than using mysql_real_escape_string.

    if($this->mysql['close'])

What this does is check if $this->mysql['close'] has a true or false evaluation.  You may have meant to do at least

    if ($this->mysql['close']())

However, that's still incorrect.  That closes the last database connection that was open.  That may or may not be the right connection.  It really should be

    if ($this->mysql['close']($this->connection))

In the following two function signatures, you use $sql to represent two different things:

final public function query($sql)
final public function num_rows($sql)

In the first, $sql is a string representing a MySQL query (i.e. a SQL string).  In the second, it is a query result handle.  I find that $sql makes a lot of sense in the first signature and no sense in the second.  I would suggest changing the second to something like

final public function num_rows($query)

You also have a function that doesn't quite do what one would expect:

final public function fetch_assoc($sql)
{
    return $this->mysql['fetch_assoc']($this->mysql['query']($sql, $this->connection));
}

What you do here is run a query based on the $sql string and then return the first row of the result.  However, you now have no way to get subsequent rows, as you throw away the query result handle.  You take care of this situation with a while in

final public function fetch_array($sql)
{
    $query = $this->mysql['query']($sql, $this->connection);

    $data = array();

    while($row = $this->mysql['fetch_array']($query))
    {
        $data[] = $row;
    }

    return $data;
}

This will usually work but can cause problems if the number of rows is large.  You are essentially reading the entire result into memory and then processing it later.  If there's a relatively small amount of data, this is fine.  However, if there is a large amount of data, then you can overload the server if you have this happen in too many results at once.  For this reason, it is more common to allow the caller to take care of the while loop portion.  The caller can either save the data or use and discard the results immediately.

I don't want to say a lot about this, since you already noted it.  It's worth repeating though.  You would generally be better off using either mysqli or PDO to do this.  You might even find that they offer enough that you don't need an intervening class to manage the connection.


Let's start with an attempt at a short summary of the situation with inheritance.

As long as you just create/use/destroy an object of your type, the fact that it inherits publicly from a standard container doesn't lead to a problem.

The problem arises if you have pointer (or reference) to the base class that refers to an object of the derived class, and you destroy the object via that pointer to base.

std::vector<int> *t = new custom_growth_vector<int, growth::geometric<ratio<3, 2>>>;

// ...

delete t; // This causes undefined behavior

Unfortunately, there's nothing you can do in your class to prevent this--part of the definition of public inheritance is that it allows implicit conversion to the base class.

Aside from that:

Linear growth

Using your growth::linear class means that any vector you create this way no longer meets the requirement for push_back to have amortized-constant complexity. In the other direction, this does mean the amount of space that's "wasted" by growing the vector is limited to a constant.

push_back

push_back normally has overloads for both const lvalue reference, and rvalue reference, though this may just be another member function you haven't provided (yet).

Growth Factor

I guess the biggest problem I see in the end is the fairly simple question what the real point of this is supposed to be. Most systems use virtual memory, which typically means that even if you think you're expanding an allocation following a geometric series, chances good that the system will allocate actual storage for your data following an arithmetic series, almost regardless of what you try to do.


Implementation of merge sort algorithm in C++

merge calls back() on empty vector

The logic in your merge function has a bug.

if (firstHalf.back() > secondHalf.back() && !firstHalf.empty()) { … }

The first problem is that you access firstHalf.back() before the check that !firstHalf.empty(). The checks should be in reversed order.

The second problem is that you're also accessing secondHalf.back() without checking whether !secondHalf.empty().

While the code could be fixed with less changes, I suggest that you look at the problem again: Merging only really makes sense if neither of the halves is empty. So let's break the problem into two parts:

Merge two non-empty containers.
Append the remaining elements to the already merged container.

std::vector<float> combined{};
// Merge two non-empty containers.
while (!firstHalf.empty() && !secondHalf.empty()) {
    if (firstHalf.back() > secondHalf.back()) {
        combined.push_back(firstHalf.back());
        firstHalf.pop_back();
    } else {
        combined.push_back(secondHalf.back());
        secondHalf.pop_back();
    }
}
// Append the remaining elements to the already merged container.
while (!firstHalf.empty()) {
    combined.push_back(firstHalf.back());
    firstHalf.pop_back();
}
while (!secondHalf.empty()) {
    combined.push_back(secondHalf.back());
    secondHalf.pop_back();
}

This version is not only correct but also simpler to understand.

Input does not handle excess spaces correctly

If you feed your program with input that puts more than one space between two numbers, your program will crash.

While it is a legitimate choice to require exactly one space between subsequent numbers, it turns out that you can make the behavior more user-friendly and simplify the code at the same time.

std::vector<float> floatVectorInput()
{
    std::vector<float> numbers{};
    std::string line{};
    std::getline(std::cin, line);
    std::istringstream iss{line};
    float x;
    while (iss >> x) {
        numbers.push_back(x);
    }
    if (!iss.eof()) {
        throw std::runtime_error{"Garbage input"};
    }
    return numbers;
}

Instead of first splitting into a vector of strings, I'm reading the floats from the std::istringstream directly. This will skip over any amount of white-space as desired.

The !iss.eof() check is there because I want to make sure that we stop because the input is exhausted, not because there was something that is not a floating-point number.

Avoid using namespace std

I know that many C++ tutorials want you to put

using namespace std;

into every file. I don't think that this is good advice and recommend against doing it. Importing namespaces is a complex operation and you probably don't understand all its implications. For example, what will the following code print with and without the using namespace std;?

#include <iostream>
#include <utility>

//using namespace std;

void swap(double x, double y)
{
  std::clog << "swap(" << x << ", " << y << ")\n";
}

int main()
{
  int a = 1;
  int b = 2;
  swap(a, b);
  swap(3, 4);
}

   With the offending line commented out, the code will print swap(1, 2) and swap(3, 4) as you'd probably expect. However, with using namespace std, it will only print the second line.

What happened?

   By using namespace std, we've made std::swap (defined in <utility>) visible. Since our own swap takes doubles as parameters, calling it with an argument of type int is not a perfect match. What the C++ compiler does is adding an implicit conversion from int to double. However, if there is also a function that doesn't require this conversion to happen, the compiler will prefer it. It just so happens that std::swap is a template that will be a better match in this case. So why is only the first call resolved to std::swap then? This is because std::swap takes its arguments as mutable references. A temporary object (like an integer literal in this case) doesn't bind to a mutable reference.

I understand that this is complicated stuff for a beginner and you probably shouldn't have to worry about it at this point. But if you're using namespace std, you'll have to know it or you won't understand your code.

That said, using namespace std is also frowned upon in production-quality code (written by people who ought to understand the aforementioned language rules) so you're teaching yourself a bad habit by using it. Just be explicit and prefix symbols from the standard library with std::. It will tell the reader at a  glance where the symbol comes from which makes understanding the code easier for readers of any level of experience.

Be const correct

Your mergeSort function doesn't modify its argument (sorts the vector in-place) but actually returns a new, sorted vector. Therefore, make its argument const.

std::vector<float> mergeSort(const std::vector<float>& inputArray);
//                           ^^^^^

You should do this with any variable that you don't intend to modify.

Use the correct integer types

This comment is actually wrong.

  auto round the input array because size() returns int

std::vector::size is of type std::vector::size_type which is probably an alias for std::size_t. In any case, it is an unsigned integer type. Compiling your code with warnings enabled will warn you about this mixing of signed and unsigned types.

Unfortunately, std::size_t is an unsigned integer for historic reasons. This meas that you cannot let inidces go below zero which makes the loop conditions a bit more complicated in some places.

Make double your go-to floating-point type

Unless you have a good reason to use float, prefer double for its greater range and precision. On modern hardware, you'll hardly notice a performance difference.

That's not to say there are no valid use-cases for float. But unless you have such a case, your default-choice should be for double.

Prefer '\n' over std::endl by default

std::endl does more than outputting a new line. It also flushes the output stream. Which is an expensive operation.

Sometimes, this is just what you want. For example, in this line,

cout << "Array to sort (separate by spaces): " << endl;

you've used it correctly. The text must be visible before the instruction on the subsequent line gets executed or the program might start blocking for user input before the unlucky user was asked to provide some.

However, in all other places in your program, there is no need to flush. And output flushing is slow. It probably doesn't make any measurable difference for your small program but I've seen code where replacing std::endl with '\n' literally made the code ten times faster! And as a bonus: it's also less typing.

Consider using auto type deduction (C++11)

C++11 introduced a great feature: auto type deduction. This means that if you're declaring a variable and immediately initialize it with some value, you don't have to spell out its type. The compiler will deduce it for you.

So, for example, you could replace

vector<float> sorted = mergeSort(inputArray);

by

auto sorted = mergeSort(inputArray);

and the compiler will figure out for you that sorted is of type vector<float>.

Using auto systematically can help you avoid repeating the same information over and over again and also avoid doing some silly mistakes that happen when you think you know the type.

(Applying the earlier advice, we should use const auto here, of course.)

Avoid index-based for loops (C++11)

You're using C-style for loops throughout your code. While they are not wrong, they're less readable than ideal and allow you to make some avoidable bugs with the index bookkeeping. In some cases, they might also perform worse than ideal.

Since C++11, you can iterate over any standard library container using the following idiom, known as range-based for loop.

Before:

for (int i = 0; i < stringArray.size(); i++) {
    array.push_back(stof(stringArray[i]));
}

After:

for (auto&& s : stringArray) {
    array.push_back(stof(s));
}

Notice how I am using auto type deduction here. The type of s will be deduced to std::string& here but you don't necessarily have to worry about it. You can always use auto&& if you don't care about the actual type. Prefer const auto& if you don't intend to modify the object, though. Don't use plain auto as it will make an unnecessary copy.

Prefer standard library algorithms over raw loops (intermediate level)

The previous item notwithstanding, you should try to avoid raw loops in your code at all, if possible. (Search for Sean Parent's great “Better Code” talks and in particular for his “no raw loops” advice.)

For example, the loop from above could become this.

std::transform(
      std::begin(stringArray),
      std::end(stringArray),
      std::back_inserter(array),
      [](const std::string& s){ return std::stof(s); }
);

I understand that this might not be very easy to understand for a beginner and it is perfectly acceptable to write your own loops at this point. But once you become more familiar with C++, standard algorithms are definitely something to look into.

(Taking this further, production code would of course use the standard library's std::stable_sort algorithm instead of rolling its own merge sort implementation. But implementing algorithms yourself for learning is a good exercise.)

Make the code generic (intermediate level)

Your sorting logic can currently only be used for sorting std::vector<float>. You could generalize it to work with any container of any type that defines a comparison function.

This is not a defect in your code. If you only have to sort std::vector<float>, that's fine. In fact, it is better to write specific code that is correct than to write generic code that is flawed. Once you've learned about templates and move semantics, you can attempt to make your code generic.

Avoid unnecessary copies

I liked this comment in your code.

  Reverse merged vectors. Vectors don't have pop_front and I didn't want to use lists.

Indeed, using lists would be a bad idea here (and almost everywhere else, too). However, there is no need to create another vector. For one, you can reverse the elements of a vector in-place. In this case, however, an even better solution would be to use a std::deque (which has pop_front) instead of a std:vector.

Of course, you could also re-work your code such that you don't actually pop the items off the front of your vector but merely iterate over it.

There are some other places where your code makes copies that could be avoided. For example, the splitting into the firstHalf and secondHalf vectors isn't necessary. You could instead always pass a reference to the original vector and a pair of indices. Alternatively (and preferably) use iterators.

An expert would probably also try to avoid the allocations for the merged intermediary results and instead use a single working array. But that is probably too complicated for now.

The naming could be improved slightly

Your code is generally very readable but at some places, I'd suggest looking carefully at the chosen names. For example, internal doesn't really tell me anything useful. More as a matter of taste, I'd avoid names like stringArray in favor of strings. Especially since it is a std::vector and not a std::array.

Use tools to detect easy bugs

Some of the issues pointed out in this review could easily have been found by tools.

The most important tool is your compiler. Always compile with a high level of warnings enabled and treat them as errors. For GCC and Clang, I recommend you use the -Wall, -Wextra, -Werror and-pedantic options. There are even more warnings available but these should cover a good part.

If your C++ implementation supports it, build debug builds with a “checked STL”. That is, a modified standard library that performs more checking than required (or even allowed) by the standard. When using GCC, this is really simple. All you have to do is compile with the -D_GLIBCXX_DEBUG option.

This cannot find all issues, however. So in addition, I recommend that you compile your code with a sanitizer. GCC and Clang both support the -fsanitize=TOOL flag where TOOL is the name of the sanitizer to use. I recommend that you use address and undefined routinely. Using these switches will instrument your binaries with some run-time checks.

Alternatively – or, preferably, in addition – you can use Valgrind which is a tool to instrument your binaries on the fly.

Instrumentation of your code is only useful, however, if you have appropriate tests that execute the instrumented code. In your case, testing would be easy. Just write a function that calls mergeSort with a number of interesting inputs. “Interesting” in this case might be: an empty vector, a vector of a single element, a sorted vector, a vector sorted in reverse, a vector with duplicate elements, a random vector, etc. Of course, the test should also verify that the output is sorted correctly. Re-run these tests whenever you make modifications to your code to be alerted of newly introduced bugs immediately.


Button click handlers for a JavaScript text-based adventure game

You are falling into a conceptual trap of trying to define javascript behaviors for each element on the page by numbering each and every one with a different id or class name (i.e. choice_*).  Any time you see this pattern in your coding, this should be a red flag that there is probably a better approach to your problem (which is why I think you are asking for this review).

With jQuery (or really javascript in general), you should be thinking in terms of what the behavior of an element is supposed to be using classes to identify elements which need to exhibit similar behavior, much in the same way you use classes to define elements that have common CSS stylings.  For example, all of your choice buttons fundamentally have the same behavior.  That is, they hide other options and expose a new situation.  Because this basic behavior is common, there is no reason that you need to duplicate code for each of these buttons.

So the question then becomes how do you generalize your code to have a single onclick handler for all of the choice buttons?

To do this, you have to have an understanding of which buttons expose which situations - something you are now implementing via choice_* class naming.

In jQuery/javascript, there are probably two main strategies to do this. One is to tie the elements together via their hierarchy in the DOM and to traverse the DOM hierarchy to hide/show related elements based on their location relative to each other on the DOM.  For example, when hiding/showing elements, you might hide all the siblings in same level of DOM as the one you are trying to show.

The other main approach is to use data attributes to describe how elements should interact with one another.

I will focus on the data attribute approach here as I think this makes the most sense for your use case.  You have a potentially complex set of interactions in a "Choose Your Own Adventure" style of game where you ultimately may have multiple story branches each which could lead to different situations via different paths.  This would likely be hard to model via HTML hierarchy alone once you move beyond just a trivial proof of concept.  Data attributes are also a powerful tool for a budding javascript developer to learn.

I would propose some changes to your HTML to make each "situation" its own self-contained set of HTML elements, like the concept of a page.  You could then hide/show each situation (including choices) as a single entity.  I also think in this case it makes your HTML much easier to read and maintain.

            You are lost in the woods.

        <input type="button" class="situation_choice"
            value="Continue on..."
            data-situation-target="found_cave">

            You find a cave. Do you go inside or go look for food?

        <input type="button" class="situation_choice"
            value="Go inside"
            data-situation-target="enter_cave">
        <input type="button" class="situation_choice"
            value="Look for food"
            data-situation-target="food_search">

            You walk into the cave.

            You walk away from the cave, to search for food. You find berries. Do you eat them or not?

        <input type="button" class="situation_choice"
            value="Eat the berries"
            data-situation-target="eat_berries">
        <input type="button" class="situation_choice"
            value="Don't eat the berries"
            data-situation-target="ignore_berries">

            You eat the berries.

            You ignore the berries. You are still hungry.

Note that we apply a data attribute called situation on the container of each situation "page" to uniquely identify it amongst all situations.  We also have data attributes on each option specifying the situation-target that option relates to (i.e. which situation will be shown when the button is clicked).

I have added another class situation_default to show which situation(s) are visible for display on initial page load.

Finally, I have also introduced a class for situation_text here that is not used in the javascript at all, but could perhaps give you a handle for applying CSS styling.

You use these data attributes within your javascipt to implement the logic as to what situation is shown when an option is clicked.

$(document).ready(function() {
    // Create jQuery handle to all situations.
    // Having this outside click handler allows you to access it while
    // preventing you from having to query the DOM every time you want to
    // act on this selection of elements as a whole.
    var $allSituations = $('.situation');

    // Get selector for default situation(s) which will show on page load
    var $defaultSituation = $('.default_situation');

    // Show default situation(s)
    $allSituations.hide();
    $defaultSituation.fadeIn(2000);

    $('.situation_choice').on('click', function() {
        // Find target situation element for this choice.
        // We use the 'situation-target' data attribute for the
        // clicked element, this, within the handler to determine
        // the target.
        var targetName = $(this).data('situation-target');
        var $target = $('.situation[data-situation="' + targetName + '"]')

        // if we find a single target element, we can now show it
        if($target.length === 1) {
            // hide all situations
            $allSituations.hide();
            // show target element
            $target.fadeIn(4000);
        }
    });
});


Vector addition and Pythagorean Theorem code

This is actually a good place for a class. It allows you to define methods on the vector object itself and it also allows you to document your data format (it took me a bit to figure out that you initialize your vector as [magnitude, angle_from_x_axis_in_degrees]. It also means that you don't need to repeat yourself quite so often. Internally I would store the vector as its x and y components, since that is usually more useful (especially when adding two vectors):

from math import sqrt, cos, sin, radians

class Vector2D:
    """A 2D vector that supports addition, calculation of magnitude
       and initialization from (magnitude, angle)."""

    def __init__(self, x, y):
        """Standard constructor with x and y components."""
        self.x = x
        self.y = y

    @classmethod
    def from_mag_and_angle(cls, magnitude, angle):
        """Alternative constructor from magnitude and angle from x-axis in degrees."""
        x = magnitude * cos(radians(angle))
        y = magnitude * sin(radians(angle))
        return cls(x, y)

    def __add__(self, other):
        """v1 + v2 if both are 2D vectors"""
        if not isinstance(other, self.__class__):
            return NotImplemented
        return self.__class__(self.x + other.x, self.y + other.y)

    @property
    def magnitude(self):
        """Magnitude/length of vector"""
        return sqrt(self.x**2 + self.y**2)

    def __str__(self):
        """Readable representation of vector as list"""
        return f"[{self.x}, {self.y}]"

This uses two differently decorated methods. @classmethod is basically a way to define alternative constructors (here instead of giving the components we give the magnitude and angle). @property allows a method to be accessed like an attribute, so we can write v.magnitude, instead of v.magnitude(). This way we do not need to update the magnitude if we change the x or y components, it is calculated whenever we access the attribute.

Finally, getting the x and y components does not need all your special cases. The formula is valid in all four quadrants. Only when doing the opposite (getting the angle) do you need to special case (actually you don't because it is done for you in math.atan2).

The __add__ and __str__ methods are magic (or dunder) methods. They allow you to give custom classes built-in behaviour. The former allows you to write v1 + v2 and the latter defines str(v). __str__ is also called by str.format, so printing the coordinates of the vector is a lot easier.

You might want to define, e.g. __mul__ for multiplication with another vector or a scalar.

This can be used similarly to your code:

if __name__ == "__main__":
    vector_A = Vector2D.from_mag_and_angle(2, 45)
    vector_B = Vector2D.from_mag_and_angle(*[6, 73.5])
    vector_C = vector_A + vector_B

    print(f'Coordinates of the endpoint of your vector are {vector_C} and its magnitude is {vector_C.magnitude}.')

The execution of this code is protected by a if __name__ == "__main__": guard to allow importing from this script from another script.

You can use tuple unpacking to unpack your list into the two arguments of the classmethod (as done for the second vector) or just specify the parameters directly (as done for the first).


Basic Database Class with PDO functionality

Interestingly, my review is going to be all about control.

Not Enough - Public Property

Just like in the real world, public property can be used by anyone.  If your car was public property anyone could walk into your driveway and do whatever they liked with it.  When you woke up you could not expect to $this->car->drive() (What if someone had already taken it and replaced it with null?).  If they wanted to they could place a house brick in your driveway pretending that it is your car (good luck driving that).

Public properties remove the encapsulation of state from an object.  I see virtually no place for them in OO.  Protected and Private properties on the other hand are set through using the public interface (the public methods) of an object.  Importantly the public interface is testable, so you can ensure that you will not end up with a brick in your driveway unless you really want that.

Too Much - Inversion of Control

Your code will benefit from an Inversion of Conrtol (IoC).  You can read about IoC on the web.  There is a good answer on stackoverflow with code here.

With IoC and the protected properties your code becomes:

class Page {

    protected $title;
    protected $db;

    public function __construct($db, $title) {
        $this->db    = $db;
        $this->title = $title;
    }
}

Your code is no longer dependent on the specific database setup to function correctly.  Your page will use any database connection that it is given.  This has big benefits when it comes to unit testing.  See Miško Hevery - How to Think About the “new” Operator with Respect to Unit Testing.

I have another answer that covers similar things with an extra part on injecting interfaces here.


First things first, I'll highlight areas I felt you should change.

Make a function.
Don't litter the program with blackbox debugging 'comments'.
Don't use enumerate if you don't need both index and letter.
It's easier to read one slice rather than two.
You could change your while loop to a for loop, this reduces the amount of statements in the if.

Most of these are pretty simple, and are mostly due to your debugging.
I'll elaborate on 5 as it's the only one that I should need to explain.

If we rearrange both \$\text{index} - \text{stretch} >= 0\$ and \$\text{index} + \text{stretch} < \text{length}\$ to get stretch.
This gets \$\text{index} >= \text{stretch}\$ and \$\text{length} - \text{index} > \text{stretch}\$.
As we know the input are integers we can get both to use the same sign, >.
With \$\text{index} + 1 > \text{stretch}\$.
If we merge them both together we get: \$\text{min}(\text{index} + 1, \text{length} - \text{index}) > \text{stretch}\$.

This basically means you can use the following range:

for stretch in range(1, min(index + 1, length - index)):

You should note, it won't go above the largest possible stretch and so you should only do stretch -= 1 if you break from the loop.

All of this together should get you:

def get_longest_palendrome(string):
    string = string.replace('', '^')
    longest = 0
    position = 0
    length = len(string)
    for index in range(length):
        stretch = 0
        for stretch in range(1, min(index + 1, length - index)):
            text = string[index - stretch:index + stretch + 1]
            if text != text[::-1]:
                stretch -= 1
                break
        if stretch > longest:
            longest = stretch
            position = index
    position -= longest
    return string[position:position + (2*longest + 1)].replace('^', '')

The second I looked at string = string.replace('', '^') I thought this can't be an \$O(n^3)\$ algorithm.
I don't know the actual complexity, but you instantly change the length of string to \$2n + 1\$.
This means your function is more \$O((2n)^3)\$ or \$O(8n^3)\$

I know you normally ignore the coefficient but I think it's quite important to highlight the pitfall on doubling the size of the input.


Drawing a hollow rectangle of rows and column provided by the console application

static void DrawLine(int w, char ends, char mids)
    {
        Console.Write(ends);
        for (int i = 1 ; i < w-1 ; ++i)
            Console.Write(mids);
        Console.WriteLine(ends);
    }

    static void DrawBox(int w, int h)
    {
        DrawLine(w, '*', '*');
        for (int i = 1; i < h-1; ++i)
            DrawLine(w, '*', ' ');
        DrawLine(w, '*', '*');
    }

    static void Main()
    {
        DrawBox(10, 10);
    }


Checking 160,000 records in a database for changes

There is multiple things that can be optimized in this code.

It is pretty obvious that most time is spent in HTTP requests to remote API and in database queries, so these points should be first in list of optimizations.

Your code doesn't tells much about what is coming from remote API and you didn't tell if you really need to run all requests for this API each day. If amount of requests for remote API can be somehow reduced - you should do it. If not - you need to think about how "fresh" information from this API you need to have, maybe part of information can be cached and re-used.

Besides this, if you need information from remote API on daily basis - you may think about refactoring API requests loop into separate service that  will run during whole day and store received information in some local data storage (e.g. database or some cache). Then your primary script will not need to spend time waiting for remote API responses and will run much faster.

If you know that significant amount of information that came from remote API updates less often than daily and you need to process only information that really changed - you should think about hashing. For example you can query API (even in this loop), clean it up from any information that may change at every request (e.g. request date) and, calculate hash from it (e.g. sha1) and store pair (url=>hash) somewhere. Then on the next iteration of script run you will be able to compare hash from new API response with already available hash and if they're same - completely skip data comparison with database.

About database queries - you should check that your query uses database indexes, it may significantly improve query performance.

And less intensive, but still useful optimizations is to avoid repetitive creation of things that you need to create once. For example:

Do you need to call generate_proxy() at each request?
You should use prepared SQL queries if your library supports them
You may collect information that should be updated into database into local array and then send it into database as a single transaction at the end of data processing - it may be faster.


How to replace plain URLs with links, in javascript?

I think that it's nutty to replace all characters 'a' and 'b' with junk, then un-replace them later, just so that you can use 'a' and 'b' as landmarks to indicate which points your two regular expressions have in common.  If you're going to do that, then why not just use "--ucsps--" and "--uspds--" as your landmarks in the first place?  Of course, using any special strings as landmarks is a bad idea.

The fundamental problem is that you want to exclude the same number of closing parentheses as there are open parentheses.  You can't use a regular expression to match left and right parentheses, because such an expression would not be regular.  Well, some flavours of "regular" expressions support backreferences within the expression itself, which could do the job.  RegExps in JavaScript don't.

What JavaScript can do, though, is let you specify your own code to generate the replacement text.  Here's what I came up with:

function replaceURLWithHTMLLinks(text) {
    var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])/ig;
    return text.replace(re, function(match, lParens, url) {
        var rParens = '';
        lParens = lParens || '';

        // Try to strip the same number of right parens from url
        // as there are left parens.  Here, lParenCounter must be
        // a RegExp object.  You cannot use a literal
        //     while (/\(/g.exec(lParens)) { ... }
        // because an object is needed to store the lastIndex state.
        var lParenCounter = /\(/g;
        while (lParenCounter.exec(lParens)) {
            var m;
            // We want m[1] to be greedy, unless a period precedes the
            // right parenthesis.  These tests cannot be simplified as
            //     /(.*)(\.?\).*)/.exec(url)
            // because if (.*) is greedy then \.? never gets a chance.
            if (m = /(.*)(\.\).*)/.exec(url) ||
                    /(.*)(\).*)/.exec(url)) {
                url = m[1];
                rParens = m[2] + rParens;
            }
        }
        return lParens + "" + url + "" + rParens;
    });
}


Ruby function to find numbers whose sum of squares of divisors is a perfect square

You don't need to call to_a.  Ranges are directly Enumerable.

Divisors always occur in pairs.  You don't need to test (1..i/2); you only need to go up to \$\sqrt{i}\$.

For fast performance, though, you would need a solution based on number theory rather than brute-force enumeration.


Adapter class to display songs in an Android ListView

ListView has been deprecated, a better practice would be to use RecyclerView and RecyclerView.Adapter, for more information: Android RecyclerView


Download a file and update the current downloaded percentage

From a once over and reading some docs:

You need a resp.on('error', function () {} to deal with http errors
You need a tmpFile.on('error', function () {} to deal with fs/stream errors
tmpFile is an unfortunate name, i would call it maybe tmpStream or tmpFileStream
You use both single and double quotes for strings, stick to one, preferably single quotes
resp should be res ( standard in Node ), or response, it bugs me every time I read the code ;)


A few things immediately jump out:

Use std::string instead of char*.
Your string is not null terminated (use of std::string fixes this)
Don't create two globals when they're only used in one place.
Don't create globals with an "uppercase" name. By common practice this is reserved for macros.
srand() and rand() are superseded by any RNG from the <random> header.
Don't use a do...while when a for-loop does the same job more succinctly.
Your createPassword function does two things:

It communicates with the user.
It creates a new password.

Split the logic into 2 functions.


Here are a few tips:
1) Use standard naming convention.
tE and tF sound like booleans and not a refence to an element.
Try names like el, $this or that instead.
2) Separate complex logic into smaller functions.
There's too much going on here.
 inputResize = ->
   $('form').each ->
    tF = $(this)
    formWidth = tF.width()
    tF.find('input').each ->
     tE = $(this)
     inputBorder = (tE.outerWidth() - tE.innerWidth())
     inputPadding = parseInt(tE.css('padding-left')) + parseInt(tE.css('padding-right'))
     tE.css 'width', ->
      (formWidth - inputBorder - inputPadding)

Since tF is only used then you can get rid of it and use $(this) directly.
Next, extract the input width size calculation to one function and you get something like this.
  getNewInputSize = (el, formWidth) ->
    inputBorder = el.outerWidth() - el.innerWidth()
    inputPadding = parseInt( el.css("padding-left"), 10) + parseInt(el.css("padding-right"), 10)
    formWidth - inputBorder - inputPadding

  resizeFormInputs = ->
    $("form").each ->
      formWidth = $(this).width()
      $(this).find("input").each ->
        $(this).css "width", getNewInputSize($(this), formWidth)

Final Code:
$ ->
  getNewInputSize = (el, formWidth) ->
    inputBorder = el.outerWidth() - el.innerWidth()
    inputPadding = parseInt( el.css("padding-left"), 10) + parseInt(el.css("padding-right"), 10)
    formWidth - inputBorder - inputPadding

  resizeFormInputs = ->
    $("form").each ->
      formWidth = $(this).width()
      $(this).find("input").each ->
        $(this).css "width", getNewInputSize($(this), formWidth)

  $(window).resize(resizeFormInputs).triggerHandler "resize"


This looks really nice to me, I have just a few minor remarks.

Imports buried in the code

Many imports are buried in some functions,
for example in putc and getc,
and I don't see a good reason for that.
It would be better to import the required modules at the top.

Complicated command line argument parsing

The command line argument parsing in the main function looks a bit complicated. I think it should be possible to refactor that to make it easier to read, and using a context manager for the input file handling.

Mutually exclusive if statements

The second if here should be an elif:

if c == '[':
    stack.append(i)
    count += 1
if c == ']':
    jump_table[i] = stack[-1]
    jump_table[stack[-1]] = i

Don't repeat yourself

The assignment of s and i are almost identical in these two functions:

def __getitem__(self, index):
    s = self.pstack if index >= 0 else self.nstack
    i = index if index >= 0 else -index + 1
    # ...

def __setitem__(self, index, value):
    s = self.pstack if index >= 0 else self.nstack
    i = index if index >= 0 else -index - 1
    # ...

I would add some helper functions to reduce the duplication.

Too dense formatting

It would be easier to read the code with a blank line between functions.


The docstrings and doctests are nice.  I would prefer a more explicit description of the behaviour: "Return a copy of the array, sorted using the bubble sort algorithm."  Typically, if you're implementing these sorting algorithms as an exercise, you would perform the sorting in place.

In bubble_sort(), the while last_index > 0 loop would be written more idiomatically as:

for last_index in range(len(array) - 1, 0, -1):
    …

In insertion_sort(), the reversed(list(enumerate(sorted_array))) would be making temporary copies of sorted_array.  I would therefore consider it an improper implementation of the algorithm.


Array inside array (comment system with 2 levels)

Depends on how your data is modeled. I dont know that, but I can assume that you use three relational tables. Something along these lines:

Post [parent]
+-------------+---------+
|    Field    |  Type   |
+-------------+---------+
| id          | int     |
| value       | varchar |
+-------------+---------+

Comment [parent-child]
+-------------+---------+
|    Field    |  Type   |
+-------------+---------+
| id          | int     |
| foreign_key | int     |
| value       | varchar |
+-------------+---------+

Comment->Comment [child]
+-------------+---------+
|    Field    |  Type   |
+-------------+---------+
| id          | int     |
| foreign_key | int     |
| value       | varchar |
+-------------+---------+

You are looking to potentially run three queries. An easy fix would be to add a has_children field to each parent table. With that you would save a potential checkup and easily release some complexity in the PHP loop.

    [parent-child]
    +--------------+---------+
    |    Field     |  Type   |
    +--------------+---------+
    | id           | int     |
    | foreign_key  | int     |
    | has_children | bool    | <===
    | value        | varchar |
    +--------------+---------+

I can provide the PHP code if you like, but I'm assuming that you get the general idea.


Calculate the sum at a level of a binary tree represented in a String

Recursion:

  Considering this is a binary tree, a recursive function seems
  appropriate.

Recursion would be a natural choice if your input were a root tree node with tree nodes as children - a recursive data structure. However, your input is a 'flat' string representation of a tree. A simple iteration might actually be much easier to implement, read and execute.

Passing inputs:

  How should I properly be passing the altered string throughout the
  recursive function?

I think the recursive passing down of substrings representing nodes or node lists (children) is already pretty well done.

However, I would like to suggest a few improvements regarding the parsing functions and their return values:

Style:

Consider the getCurrentVal(input) function:

function getCurrentVal(input){
  var val = "";
  while(input[0] !== "(" && input[0] !== ")" && input.length){
    val += input[0];
    input = input.substr(1);
  }
  return {
    val,
    input
  }
}

The code is not very descriptive: It is not immediately obvious what this function does.

The function name getCurrentVal is misleading, as you don't just return the node value, but also the children.
The argument name input is meaningless, as all arguments are inputs.
The variable names are misleading, as you reuse input to store part of your output.

How about this alternative:

// Split node 'a(b)(c)' into value 'a' and children '(b)(c)':
function parseNode(node) {
  let split = Math.min(node.indexOf('('), node.indexOf(')'));
  if (split < 0) split = node.length;
  return {
    value: node.slice(0, split),
    children: node.slice(split)
  };
}

'Parse' hints at the input being text or some other raw content.
'Node' carries more semantics than 'input'
Math.min and String.indexOf are more descriptive than a while loop.

Destructuring the resulting object improves readability:

var {value, children} = parseNode(node);

Also, when parsing integers, you shouldn't use JSON.parse(string) but the more specialized Number.parseInt(string) or the idiomatic type conversion via +string.

Further naming suggestions:

getValueForLevel -> getSumForLevel or sumTreeLevel
Consistency: Choose either val or value when naming currentValue.val, getCurrentVal, getValueForLevel

Complexity:

  Considering the parens and values are removed as they are parsed, that
  lends itself to O(n), but I feel it's O(n^2) because of the duplicate
  parsing in order to create the child nodes. Is that correct? Can it be
  improved?

First of all, let's define n as the length of the input string.
Then, let's look at the complexity of the helper functions:

stripFirstLastParen: O(n) because of input = input.substr(1)
getCurrentVal: O(n²) for worst-case input "1(2)(3)", "11(22)(33)", "111(222)(333)" and so on because of input = input.substr(1) within while (input.length). Yes, we break the loop as soon as we encounter the first parenthesis, but this doesn't happen before parsing roughly 1/3 * n characters for above input. The best-case complexity is however O(n) when the value has constant length.
getChildren has worst and best-case time complexity of O(n²) due to input = input.substr(1) within a while loop over input.

Now, we can tackle the complexity of getValueForLevel:

The first four lines are dominated by getChildren(currentValue.input). If the length of currentValue.input - the length of the children - is proportional to n, then it has a runtime complexity of O(n ²).
Then it calls getValueForLevel(children.left, k-1). It is easy to construct inputs which maximize the length of children.left such as "4(3(2(1))))" without right children. For this input, in each iteration, the length of children.left is reduced by 3.
The final call to JSON.parse is in O(n).

Adding the complexities together gives us:

n² + (n-3)² + (n-6)² + ... + (n-3k)²

Thus, for k = 0 the runtime complexity is in O(n²) and for maximum k we have a runtime complexity of O(n³):

In general, the runtime complexity is bounded by O(kn²).

Alternative approach:

Following my introductory remarks about a possibly simpler iterative solution, here a possible implementation with linear runtime complexity:

// Sum integer tree nodes at given level:
function sumTreeLevel(tree, level) {
  let tokens = tree.match(/(\(|[0-9]+|\))/g);
  let sum = 0;
  for (let token of tokens) {
    if (token === '(') {
      level--;
    } else if (token === ')') {
      level++;
    } else if (level === -1)  {
      sum += +token;
    }
  }
  return sum;
}

// Example:
console.log(sumTreeLevel("(10(5(3)(12))(14(11)(17)))", 2)); // 43


Is there a better way to handle multiple join statements in a linq query?

I'm not sure what you mean by a 'cleaner way'. The syntax you're using is known as query syntax and is by far the best for readability when you have multiple joins.

If you use method syntax to express the same query you'll quickly see what I mean.

However, if you use method syntax you'll be able to break those joins up using different methods.

For example:

IGrouping<Results> AddJoin(IQueryable<Stuff> query) {

    if (business_rule) {
        return query.Join(inner => inner.Key, outer => inner.Key == outer.Key);
    }

    return query;
}

In this way you can reuse parts of your join and construct them dynamically.

Hope this helps.


You can make this shorter by modifying your html to have the id in a data attribute and using classes, but this is what I have based on the info you've given.

$(function() {

    function initializeMenu(id) {
       $('#show-menu-' + id).on('click touch', function() { toggleMenu(id, true); });
       $('#close-menu-' + id).on('click touch', function() { toggleMenu(id, false); });

       $(document).on('click touch', function(event) {
            if (!$(event.target).closest('#menu-' + id).length) {
                toggleMenu(id, false);
            }
       });
    }

    function toggleMenu(id, open) {
        $('#menu-' + id + ' > .main-menu__submenu').toggleClass('main-menu__submenu--active', open);
        $('#menu-' + id).toggleClass('main-menu__item--active', open);
    }

    for(var i = 1; i <= 2; i++) {
        initializeMenu(i);
    }
});


What you have is very good and it certainly functions as expected. I have just a few ideas to consider implementing (more in relation to the game than the code):

Print the number ranges for each difficulty at the start, so that the user knows what range to guess in.
Check if the guess is outside the range.
Count the number of guesses and report back to the user at the end.
Edit the prompts slightly so user knows when input is expected.

I have shown my code below, implementing these features. I reduced it to a single function (to avoid having to use global variables). I have used a dictionary to store the top end of the range of each difficulty (difficulty_ranges) so this can be checked easily later, using fewer if else checks.

I also corrected a few PEP8 style warnings (spacing, use snake case instead of camel case for function name etc).

import random

def number_guess_game():
    # Set up main variables
    guesses = 0
    difficulty_ranges = {'e': 20, 'm': 50, 'h': 100}

    while True:
        difficulty = input(
            "Type E, M or H for easy (0-20), medium (0-50), or hard (0-100) number range:\n").lower()
        try:
            number = random.randint(0, difficulty_ranges[difficulty])
            break  # Need to break the while loop here
        except KeyError:
            print("Incorrect input! Choose again...")  # Encourage user input

    while True:
        try:
            guess = int(input("Your guess: "))
            guesses += 1
            if number == guess:
                print("Correct guess! You used {} guesses.".format(guesses))
                return number_guess_game() if input(
                    "Play again? Press Y to play again or any key to exit.").lower() == 'y' else 0
            elif guess < 0 or guess > difficulty_ranges[difficulty]:
                print("Your guess was out of range!")
            else:
                print("Too High. Guess again..." if number < guess else "Too Low. Guess again...")
        except ValueError:
            print("Must be an integer value.\n")

def main():
    number_guess_game()

if __name__ == '__main__':
    main()

I should add that I am not a Python expert, so other users will likely provide more useful information on the code. I think your layout is good and the logic is easy to follow. I wanted to suggest a few of these extra features as it is a game and these may improve the experience.


class IText - Validates text from Ajax POST | Add consistent return type, defensive coding, functional focus

I've tried to cover as many things I could.  A few of my explanations are rather brief, so if you want me to explain or defend anything, let me know.  And hopefully it doesn't read too ramble-y :).

IText

IName typically denotes an interface.  It's not a naming scheme often used in PHP, but it's used often enough that you should avoid prefixing an I onto a class that isn't an interface.  This is confusing.  In fact, when I first saw the name, I was expecting an interface.

As a developer consuming the class, it really is not all that important if it's "independent" since most IDEs will show the constructor signature.  Interface vs abstract vs concrete tends to matter, but I do not feel that independent necessitates its own naming scheme.

mixed concerns

I'm not sure if I understand what your class is doing.  Based on the name, it looks like you're trying to model a string. BUt what it's actually doing is sort-of processing POST.

Instead of doing this, I would create validators that are separate from the model of a string (or the model of any data type really).  Also, why hold an array of values inside of the object?  Is the object meant to be some kind of repository or something?

Once you get a lot of validations, or once you get a few very complicated ones, this class will grow to be unmanagable.

Personally, I like the model of Zend_Validate.  It completely separates the concept of data and the validation of data.  In your class, storage, validation and manipulation have all been (needlessly) coupled.  (Obviously storage and validation go together when storing things long term, but in this context, I mean storing as in storing in PHP-land.)

A perfect example of your validation and storage coupling is your checkPattern method.  What if you want to validate something as a URL, but it's not stored in $_POST['url']?  What if you want to check $_POST['website']?  Or what if you have an arbitrary $url that you want to check?  Your code now does not facilitate that.  It is directly tied to the expectation that the validation and the data will be stored with the same keys.

htmlentities

Your values are not being used in the context of HTML, so they should not be treated as HTML.  Only treat HTML as HTML.  In other words, don't escape data until it actually needs to be escaped.  Your validations are going to be confused when they see a &#38; b instead of a & b (or any other substitutions htmlentities may make).

$_POST

A lot of the comments in the "mixed concerns" section, you're probably thinking "but it's only meant to manipulate post?"

Well, what if at some point in the future, you have an arbitrary array you want to handle?  There's no need to couple your code to $_POST.  Instead, pass the array in to the constructor.  (Well, in all honesty, I think your design is flawed, but if you do stick with it, pass the array in.)  What if at some point in the future you have a JSON based API and you want to validate that?  How would you do that with your current code?

technicalities

If nothing is posted (count($_POST) === 0), then text_array is going to be NULL.  This will mean that every array access will issue a notice.  You should initialize the member to an array either in the declaration or in the constructor.  I would do it in the declaration:

private $text_array = array();

Also, you're assuming $_POST is one dimensional.  If someone posts a form like:

<input type="text" name="test[]" value="array">

Then $_POST will look like:

array('test' => array('array'))

This means that you'll end up passing an array to htmlentities.  In other words, don't assume that POST values are strings.  (Though they are always either a string or an array.)

in addPrefix, you've used textArray instead of text_array

Constants

Instead of using names of the validations, use class constants instead.  This will mean that calling code doens't need to know the array keys, and that they can be changed if needed/wanted.  It will also tend towards cleaner looking and more maintainable code since typos will be errors instead of falling through the cracks.

For example:

const DOMAIN = "domain";

Then:

$text->checkPattern(IText::DOMAIN);

Be paranoid

Never assume anything in code.  In particular, don't assume that a variable will be the type that you expect or that an array key will exist.

Note that these both basically only apply to user data since if you create the data, you can know with certainty what it is.

Consider your checkPattern method:

public function checkPattern( $pattern )  // pattern checker returns bool
    {
        return ( preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) );
    }

What if an invalid pattern name is provided?  Then suddenly you have at least 3 notices (two that the array key does not exist, and one that preg_match received an empty pattern).

You should be safe guarding things like this:

public function checkPattern($pattern)
{
    if (!array_key_exists($pattern, $this->patterns)) {
        //Pattern doesn't exist
        throw new Exception("Invalid pattern provided: " . $pattern);
    }
    if (!array_key_exists($pattern, $this->text_array[$pattern])) {
        //data doesn't exist
        return false;
    } else if (!is_scalar($this->text_array[$pattern])) {
        //If this were checked on construction, this would not be necessary
        throw new Exception("The data stored for {$pattern} is not a scalar, but it's being treated as such");
    }
    return (bool) ( preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) );
}

Also, while I'm at it, your comment is a lie.  preg_match returns an int, not a bool.  A wrong comment is significantly worse than no comment.

Final suggestions

I would consider decoupling your data and validations.  What you could do is create a "Form" that encapsulates all of this.  Basically your form would have elements and each element would have validations.  The form would then be capable of taking in an arbitrary array and telling you if it's valid per the specification of the form.

If you want a few ideas on this, you could look at Zend_Form.  It has a lot of limitations, and the rendering side of it can be a bit hard to get along with, but overall, it's a fairly decent modeling of a form.  Zend_Form is likely not the best, just Zend Framework happens to be what I'm familiar with.

Edit: URL handling

Just noticed that you've used a regex to extract out the domain from a url.  Instead of doing that, you might want to use parse_url.


Concatenating multiple strings from a JSON response

I would suggest using then whenever possible. done and fail are specific to jQuery while then is a "standard" pseudo-interface for promises.

And if my jQuery isn't mistaken, the success handler will fire for 2xx and 3xx responses, while the fail handler will fire on 4xx and 5xx responses. You should take advantage of those instead of returning and checking statuses manually. The only time I remember APIs require using 2xx for errors is for Flash, for some reason.

Assuming response always has a data field and you want everything in the data field to be concatenated, you can use Object.keys, array.map and array.join.

Your code should end up looking like this. Two-space indent is a personal preference, but I go with it because it looks more compact.

$.post('/API',null,'json').then(function(response){
  location = Object.keys(response.data).map(function(key){
    return response.data[key];
  }).join(', ');
}, function(){
  location = previousLocation;
}).always(function(){
  $("#location").text(location);
});