I can't post a full answer about the "advanced JavaScript" part of your question, but here's what I would change in the actual code:

Use jQuery.fn.find method

You could optimize this $('#scroller ul li') with this $('#scroller').find('ul li'). When using a selector like #someidname, jQuery can use directly the native method document.getElementById. When using  #someidname something, then jQuery has to parse the selector, and only after this it can say "oh there's an id string in there !".
Don't recreate jQuery objects

When doing var scrollerContainer = $('#scroller ul');,  scrollerContainer becomes a jQuery object. Then, you don't need to do $(scrollerContainer).someMethodName() but you could directly write scrollerContainer.someMethodName().
Always use triple equals sign

You should (almost) always prefer === over ==. The double equal sign may have some unexpected behavior such as "\t \n" == 0 which evaluate to true.
Don't use jQuery when it's not needed

$(this).attr('id') could be simplified in this.id. This way, you don't construct a new jQuery object (this can be costly when done in loops for example), and the id property is supported in a cross-browser way so you don't have to worry about it.
Cache your DOM selections

$('#leftControl') and $('#rightControl') should be cached in variables in the same way as $('#scroller ul') is. We should avoid doing the same DOM query wherever it's possible.
Prefer jQuery.fn.on or jQuery.fn.bind methods over traditional ones

Because:

they are faster: internally $('whatever').click(fn) calls $('whatever').on('click', fn), so you can use it directly and avoid a function call,
they are more flexible: you can bind the same function to different events ($('whatever').on('click mouseenter mouseleave', fn)), you can namespace your events ($('whatever').on('click.myPlugin', fn)) which IMO would be useful in your case (your doing some sort of namespacing)

Simplify (Math) expressions

IMO, the code slideWidth*(-(currentPosition*3)) is not really readable. Why using such parenthesis ? And what about this inner - sign ?

What about writing it this way -slideWidth*currentPosition*3 ?

Also, the part (position*3)==numberOfSlides-1 || (position*3)==numberOfSlides-3 || (position*3)==numberOfSlides-2 can be simplified. Have a look (shorter variable names for the example):

(p*3)==n-1 || (p*3)==n-3 || (p*3)==n-2
// which is equivalent to
1==n-p*3 || 3==n-p*3 || 2==n-p*3
// which is equivalent to
1 <= n-p*3 && n-p*3 <= 3
// and also equivalent to
(n-p*3-1) in [0,0,0]

so you end up with this:

if( (numberOfSlides-position*3-1) in [0,0,0] ) {
    ...
}

That (n-p*3-1) in [0,0,0] part is quite interesting. When doing a in b you'll search if the array b has the index a. This only happens in our case because b is an array. So we use a array b = [0,0,0] which has 3 elements. 3 comes from the expression n-p*3, this is the maximum X of the three n-p*X forms seen above. Then, since [0,0,0] has 3 elements, its index are 0, 1, and 2. So the test if the expression n-p*3 equals to one of 1, 2, or 3, we have to subtract -1.

To explain it on another way, we can say that 0 in [0,0,0], 1 in [0,0,0], and 2 in [0,0,0] will both be true (because we're using the array indexes and not its values), and all others numerical values will evaluate the expression to false. Since what you want you is to check if n-p*3 is of one 1, 2 or 3, if we remove 1 to this expression, we retrieve our values 0, 1, and 2 from above which will evaluate the expression to true.

If you think this one is too tricky (and to be honest, it is !), you can do the following, which avoid code repetition and where the intent is explicit and readable (I would recommend this technique over the index i [0,0,0] one which is implicit and less readable IMO)

var temp = numberOfSlides - position * 3;
if( 1 <= temp && temp <= 3 ) {
    ...
}

Hope that helps :)


Display data from two MySQL database tables

foreach
Don't have an empty foreach loop... ever. Similarly, just because php lets $row escape from the context it is in does not mean you should use it after the foreach-loop is over.
PDO::query
I recommend against using PDO::query, especially because you lack a thorough understanding of what you are doing. You can use it when executing complete static queries (those that do not have variables), but you already have a where-clause in that sql statement and it is only a matter of time until you want to change that to something dynamic. Use PDO::prepare instead.
PDO::prepare
You are using $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);. Good. Except that you do not use prepared statements at all. Keep in mind that your mysql driver must be able to use native prepared statements too.
PDO::ERRMODE_EXCEPTION
You are setting the error mode to PDO::ERRMODE_EXCEPTION. Good. Except that you do not catch any of them and instead let the page return blank.


Login system using bcrypt and MySQL, to be used for any future projects

Let's start with the SQL and your loginDbMySQL stuff first.
You should probably reconsider the naming of your SQL table columns.
Bare minimum reproducible example with a table that has automatic incrementation, a UID as the primary key, and the username field 'username' and 'passwd_hash'.  You should name colums to be descriptive of the value per record, not as plurals unless you are storing multiple items for each field in the record.
So, let's make the table accordingly, and also have a unique constraint on usernames - you don't want duplicate usernames.  The username also becomes the primary key since we want unique usernames:
create or replace table login_tests.login_table
(
    uname varchar(50) not null,
    passwd_hash varchar(1000) not null
);

alter table login_tests.login_table
    add primary key (uname);

Note we're using uname as the primary key, so you can only have unique usernames.  This is entirely permitted in SQL.
SQL query mechanisms being used are NOT SQL-Injection-Safe!
Next, let's look at one of the glaring problems in your code:  your queries and routines are not injection-safe!  I can easily pass a value in that can escape the 'argument' being called and simply cause chaos with SQL injections.  The way around this is to build predetermined procedures in the DB and call that, and then pass the arguments in with callproc calls.
To start with, you have three separate queries - one to determine if a user exists, one to insert a user, and then a similar select query for logging in.  But, we can use the same SELECT for the same task!  Saves us code!
Also, you aren't really using SELECT functions for anything other than checking if a username exists on insert (fixed later), and getting hashed pw data for a given username.
Firstly, on the MySQL side we need to create the functions.
CREATE PROCEDURE GetPWHash(username varchar(50))
BEGIN
    SELECT passwd_hash FROM login_table WHERE uname = username;
END;

CREATE PROCEDURE GetUserData(username varchar(50))
BEGIN
    SELECT * FROM login_table WHERE uname = username:
END;

CREATE PROCEDURE AddUser(username varchar(50), pass_hash varchar(1000))
BEGIN
   INSERT INTO login_table(uname, passwd_hash) VALUES (username, pass_hash);
   COMMIT;
END;

We'll then call the relevant procedures with a cursor.callproc(ProcedureName, [argument]) call instead.  It's not considered smart to build your queries in strings because it is typically extremely unlikely you will be able to properly escape the queries.  The callproc function will automatically escape them before passing them to the function.
You'll see me replace your functions accordingly as we go and edit each function and call.  So let's begin with those.
INSERT function doesn't need a select to check if the user exists - DB insert will simply fail if a user exists because of PrimaryKey restrictions.
You're doing testing here with an extra DB call which requires more disk I/O for reading.
So let's simply rewrite your insert function entirely.  It's not really pythonic in its current state, and you make an unnecessary extra DB call.
Further, you should consider a DB cursor for each one, without global declarations.  So I'll provide you some revisions.
Let's start with your insert function:
def insert(username, password_hash):
    cursor = mydb.cursor(buffered=True)
    cursor.callproc('AddUser', [username, password_hash])
    cursor.close()

We should not access the 'username' ahead of time, we can simply catch the error (the callproc function throws a mysql.connector.errors.IntegrityError class error when we violate a constraint).  No need to check if the user exists already, and as I included earlier I wrote a COMMIT into the AddUser function.  No need to make the db commit as a result, it commits after it adds!  (Actually confirmed this checking the DB after the callproc!)
Logging In Function: Use callproc!
Again, we should be using callproc and such so you eliminate an SQL Injection risk.  Further, your 'logging in' function in loginDbMySQL is... not really 'logging in'.  It's more fetching user data, so let's name it accordingly.
def logging_in(username):

    mycursor = mydb.cursor(buffered=True)
    mycursor.callproc('GetUserData', [username])
    select_query = "SELECT * FROM login_table WHERE usernames= %s"
    data = mycursor.fetchone()
    # INCOMPLETE FUNCTION

But because this is an incomplete function that does nothing, I essentially suggest removing it.
And in its place put a useful function - getUserPWHash - which will call the SQL and only return the PW hash for the specified user (if it exists).
def getUserPWHash(username):
    mycursor = mydb.cursor(buffered=True)
    mycursor.callproc('GetPWHash', [username])
    data = mycursor.fetchone()
    return data

This will be useful later, as you will see when we dig into your other code.

So, taking into account the SQL bits, we have a bunch of code tweaks on the flipside in your login.py script.
Let's start with your LogInSystem class.
Code Duplication - can be reduced by adding a staticmethod for prompting for credentials
You have two cases where you would benefit from a separate function from which you can request credentials.  Registration, and logging in.  Let's start by adding a new method to your class for this - called promptForCreds.  This is going to have a special decorator - @staticmethod - this tells the system that this function is able to stand on its own and does NOT require a dependency on the object itself (self) in the declaration of the method:
@staticmethod
def promptForCreds():
    username = input("Enter a username: ")
    password = input("Enter a password: ")

    return username, password

This will eventually be used here in your sign up and login functions.  We'll apply this in a later revision suggestion.
Reduce the need of multiple variables - like in the SQL sections.
So you end up having a bunch of one-time-use variables in passwordHashing, like you did in the SQL bits.
We can simply replace the use of variables to hold values by directly putting the variables in line.  If we name the items accordingly, we don't need additional variables to hold them, since it's clear what the objects are (they're already arguments passed into functions!)
Oh, and the passwordHashing method can also be a @staticmethod object too - it doesn't depend on any other components within your class specifically.
@staticmethod
def passwordHashing(password):
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')

This looks long but it can be broken across multiple lines if you keep the parenteses around the bcrypt.hashpw call.  But, this reduces those one-use variables AND puts everything into a simple return call - and only one of them.  No extra variables!
Another static method - comparePassword
This one's a minor change and pretty simple - just add a decorator ahead of comparePassword.
@staticmethod
def comparePassword(password, password_hash):
    if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):
        print("Welcome")
    else:
        print("Incorrect Information")

Remove code duplication in sign_up and login.
And now here's why i created that new method - we get to take four lines of code and condense it into two.  This code is duplicated, yes, but we don't have to run the prompt twice individually.
def sign_up(self):
    username, password = self.promptForCreds()
    insert(username, self.passwordHashing(password))

def login(self):
    username, password = self.promptForCreds()
    password_hash = getUserPWHash(username)
    self.comparePassword(password, password_hash)

See what I did here?  Username and password are obtained by the other function and then returned.  Saves us from having to create the prompt twice!  See what niceness I did there?
So your LoginSystem class becomes this:
class LoginSystem:
    @staticmethod
    def promptForCreds():
        username = input("Enter a username: ")
        password = input("Enter a password: ")
        return username, password

    @staticmethod
    def passwordHashing(password):
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')

    @staticmethod
    def comparePassword(password, password_hash):
        if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):
            print("Welcome")
        else:
            print("Incorrect Information")

    def sign_up(self):
        username, password = self.promptForCreds
        insert(username, self.passwordHashing(password))

    def login(self):
        username, password = self.promptForCreds
        password_hash = getUserPWHash(username)
        self.comparePassword(password, password_hash)

Now, let's look at your main() function.
Non-pythonic way of iterating over the checks!
You're doing something I wouldn't do here, which is using while var == True.  Pythonically, you can reduce this to this:  just do while var: for iterating while a variable is True.  However, I suggest you do something else, which (once again) reduces the memory usage by not needing to define a variable.
def main():
    login_instance = LoginSystem()

    while True:
        value = input("1-Login, 2-Sign-up, 3-Exit\n")
        if value == "1":
            login_instance.login()
        elif value == "2":
            login_instance.sign_up()
        elif value == "3":
            pass  # Do nothing, we'll just exit as normal.
        else:
            continue  # Continue prompting until we get a valid value.

        break

This reduces the complexity and need to assign True or False.  Just iterate infinitely and break on any value that is valid (1, 2, or 3), or keep going and prompting more until we get only one valid value.
You really should be triggering errors or returning Bools for your login functionality though.
The only problem with your approach is you have no way to catch whether a login was successful or not (or the same case with a registration).
You can approach this in one of two ways - either return errors on failures, or make your functions return a boolean instead of just printing statements.
I suggest you rename your comparePassword function to validateCredentials and then adjust it to return a True or False - True for valid credentials, False for invalid.  Or, just return the result of bcrypt.checkpw:
@staticmethod
def validateCredentials(password, password_hash):
    return bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8'))

Now, we'll use this for login functionality:
def login(self):
    username, password = self.promptForCreds
    password_hash = getUserPWHash(username)
    if self.validateCredentials(password, password_hash):
        print("Welcome!")
    else:
        print("Invalid Login")

Note that simply printing output is simple - you really should consider making this return a bool as well.  This way you can utilize the results.
So that would look like this:
def login(self):
    username, password = self.promptForCreds
    password_hash = getUserPWHash(username)
    return self.validateCredentials(password, password_hash)

This would then mean we have a revise later for when value is 1:
# ...
        if value == "1":
            if login_instance.login():
                print("Welcome!")
            else:
                print("Access denied")

Now, we have a similar case with insert but we're going to use error codes instead.
Back in loginDbMySQL way earlier in this review, I basically removed print statements and error checking from your insert function.  This was intentional, because we'll handle insert via error code data/returns.
So, in the conditional for when value is 2:
        elif value == "2":
            try:
                login_instance.sign_up()
                print("Sign up complete.")
            except mysql.connector.errors.IntegrityError:
                print("Unable to register account.")

This ultimately makes it a more usable login system function.  It requires a single import added though - mysql.connector.errors.  This is so we can import the error class for the exception handler.

The code with all my revisions:
login.py:
import bcrypt
import mysql.connector.errors
from loginDbMySQL import insert, getUserPWHash

class LoginSystem:
    @staticmethod
    def promptForCreds():
        username = input("Enter a username: ")
        password = input("Enter a password: ")
        return username, password

    @staticmethod
    def passwordHashing(password):
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')

    @staticmethod
    def validateCredentials(password, password_hash):
        return bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8'))

    def sign_up(self):
        username, password = self.promptForCreds
        insert(username, self.passwordHashing(password))

    def login(self):
        username, password = self.promptForCreds
        password_hash = getUserPWHash(username)
        return self.validateCredentials(password, password_hash)

def main():
    login_instance = LoginSystem()

    while True:
        value = input("1-Login, 2-Sign-up, 3-Exit\n")
        if value == "1":
            if login_instance.login():
                print("Welcome!")
            else:
                print("Access denied")
        elif value == "2":
            try:
                login_instance.sign_up()
                print("Sign up complete.")
            except mysql.connector.errors.IntegrityError:
                print("Unable to register - username already taken.")
        elif value == "3":
            pass  # exit
        else:
            continue

        break

if __name__ == "__main__":
    main()

loginDbMySQL.py:
import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="*******",
    database="*******"
)

def insert(username, password_hash):
    mycursor = mydb.cursor(buffered=True)
    mycursor.execute("AddUser", [username, password_hash])
    mycursor.close()
    print("Account created!")

def getUserPWHash(username):
    mycursor = mydb.cursor(buffered=True)
    mycursor.callproc('GetPWHash', [username])
    data = mycursor.fetchone()
    return data
```


Merging two dictionaries together whilst adding keys but multiplying values

It's standard to indent Python with 4 spaces. Not following this standard only makes your life and the life of people that have to interact with you harder.

You can just use the optional default argument to dict.get to remove the need for the if.

for k1, v1 in dict1.items():
    for k2, v2 in dict2.items():
        key = k1 + k2
        dict_merged[key] = v1 * v2 + dict_merged.get(key, 0)

Alternately you can change dict_merged to a collections.defaultdict, rather than a dict. This removes the need to use dict.get, and allows you to just us +=.
defaultdict takes a function that provides the default value to use. Since int() returns 0, we can just pass int as the function. As noted by Ilmari Karonen you can also use float as that returns 0.0 without any arguments.

import collections

dict_merged = collections.defaultdict(int)
for k1, v1 in dict1.items():
    for k2, v2 in dict2.items():
        dict_merged[k1 + k2] += v1 * v2


Find and replace String with a substring result

I would go with Regex for this, with greedy matches so that nested results like your example above would only match the outer string.

So with your example here:

Input                       Terms               Output
The search is cool          {sea, search}       The search is cool

A Regex pattern of search|sea could be derived from the search terms, and only 'search' would be matched. Note that the longest term will need to first for this to work as desired.

String results(String input)
{
 String retVal = input.replaceAll("search|sea", "$1")

 return input;
}

I think this should be close to what you need, but I havn't had time to test and check. Hope it helps.


Transforming an array: take the square root of each perfect square, else square the number

Naming conventions aside (short names in camelCase are typically used in Go), this is the right way of doing what you want. The authors of Go have a different view of what is more readable & maintainable than the authors of Python :-)


If I understand your intent:

Console.WriteLine("Please enter a date in the following formate MM/DD/YYYY");
string date = Console.ReadLine();
DateTime startRange = Convert.ToDateTime(date);
DateTime endRange = startRange.AddDays(6);

foreach (var pair in pagesInRange)
    if (pair.Key >= startRange && pair.Key <= endRange)
        Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);

This does not take advantage of the fact that the dictionary is sorted.


It can be tough, but pretend you're not the developer who wrote this code and try to understand what it does by reading through it. At a quick glance some questions you might ask could be:

What does isValid actually check the validity of?
What is strInput? The line isValid(strInput) just tells me that someone has deemed some input string valid for doing something. Not very useful, right?
When there is an exception in the XMLReader portion, what does it mean to just set the exception text to a random set of instance variables and continue on like nothing happened?

Some quick fixes might be to just use better variable/method names such as: isResolvableUrl(url) and inputXmlUrl.

On to your actual code...it's a very bad practice to use try/catch blocks for flow control. Exceptions should be exceptional (see: When to throw an exception)! Right now, you're just brushing exceptions under the carpet, which makes the rest of your application unable to properly handle them.

Think about the actual flow of your application in an ideal case. First, you make a request to verify if the file is there, which has network cost. Then, you use the same url to create an XmlReader which has to read from there again! Since you're catching all exceptions, you're better off not doing a check to see if it'll fail and just letting it fail without doing the check in the first place.

If each of your methods had a single identifiable functionality, you'll find you don't need all the try/catch blocks:

public XmlReader GetXmlFromRemoteLocation(string xmlLocation)
{ }

public void ReplaceWhitespace(XmlReader xml)
{ }

public void WhateverYourMainMethodIs()
{
    // Let it throw Exceptions that can be caught!
}

// Alternatively (if you must):
public bool TryWhateverYourMainMethodIs()
{
    try { }
    catch ( ExpectedExceptionTypes )
    { }

    return success;
}


Keep your variable naming consistent. Some of your code uses camelCase variable names, others uses snake_case. In JavaScript, we use camelCase by default.
The first argument in a Node-style callback should be reserved for errors.

You do this fairly well, but at one branch inside generateRefreshToken you pass a string error and error code to the callback as success arguments rather than as an Error. Speaking of which, use Error objects rather than strings for errors.

You can create your own derivations of the Error type if you want to be able to determine more specifically what Error you've received. This is generally not necessary unless you want your error to be recoverable.

You should set up your express application such that any Error that bubbles up to the top (That is not an authentication error) is presented to the user as a generic HTTP 500 error with no specific information encoded in it. The easiest way to do this is to throw Errors inside middleware when things go wrong and then have another middleware catch this error and present it to the user. I'd recommend boom for this.

Consider using Promises for async flow.

You can of course continue to use callbacks in this manner with the async library but Promises are (in my opinion) a lot simpler to use and compose. When you are interacting with a library that primarily uses callbacks you can still use Promises at the edges of that API, but I'd recommend using Promises everywhere internally.

The main benefit is that the code is more readable, but also Promises make it much harder for you to forget to handle an error (it's very easy to forget that in callbacks), make code more composable and are also first class citizens in ES6 as well as receiving syntactic sugar in ES7.

Extract the logic inside your async.waterfall code to separate functions

You already alluded to this in your answer, but you can very easily extract this code out so it reads a lot easier.

Rule of silence

Don't console.log unless it's for output to user actions. If you really want to do this, use debug from npm, which enables you to flag all debug actions and have them disabled unless you pass an environment variable.

Errors should be written to console.error as this can be piped to a separate error log file.

Here's my revised version of your code in ES5:

var async = require('async')

function serializeUser(callback) {
  return User.serializeUser(fbId, cb)
}

function generateAccessToken(user, callback) {
  return auth.generateAccessToken(user._id, function (error, accessToken) {
    return callback(null, user, accessToken)
  })
}

function generateRefreshToken(user, accessToken, callback) {
  return auth.generateRefreshToken(user._id, function (error, refreshToken) {
    if (error) {
      return cb(error, null)
    } else if (refreshToken) {
      return cb(null, { user: user, at: accessToken, rt: refreshToken })
    } else {
      const err = new Error('no refresh token was generated')
      return cb(err)
    }
  })
}

function requestHandler(req, res, next) {
  var fb_id = req.body.profile.fbID
  async.waterfall([
    serializeUser,
    generateAccessToken,
    generateRefreshToken
  ], function (error, results) {
    if (error) {
      // Let another middleware handle this (like express-boom).
      throw error
    }

    res.status(200)
      .json({
        user: results.user,
        access_token: results.at.access_token,
        refresh_token: results.rt.tokenString
      })
  })
}

I haven't included Promises here due to your answer about being new to Node - also, they don't really work extremely well with express.


Large matrix with lots of repetitive fields (C++)

Why have nested unordered_maps. Just use a single unordreed map using a key that is the x and y coordinates?

One enhancement I would add is using the operator[][] to access the elements.

#include <unordered_map>
#include <utility>
#include <iostream>
#include <functional>

template <typename T>
class UMapMatrix
{
    public:

        UMapMatrix(T const& default_val = T())
            : default_val(default_val)
        {
        }

        T const& get(int a, int b) const
        {
            auto key    = getKey(a, b);
            auto search = data.find(key);
            return (search != data.end())
                       ? search->second;
                       : default_val;
        }

        void set(int a, int b, T const& val)
        {
            data.insert(std::make_pair(getKey(a,b), val));
        }
        void set(int a, int b, T&& val)
        {
            data.insert(std::make_pair(getKey(a,b), std::move(val)));
        }

        class Row
        {
            UMapMatrix const* parent;
            int a;

            public:
            Row(UMapMatrix const* parent, int a)
                : parent(parent)
                , a(a)
            {}
            T const& operator[](int b) const
            {
                return parent->get(a, b);
            }
        };
        Row operator[](int a) const {
            return Row{this, a};
        }

    private:
        T default_val;
        using Key = std::pair<int, int>;
        struct PairHash
        {
            std::size_t operator()(Key const& key) const
            {
                return std::hash<int>()(key.first) ^ std::hash<int>()(key.second);
            }
        };

        Key getKey(int a, int b) const {

            int x = std::min(a, b);
            int y = std::max(a, b);
            return std::make_pair(x, y);
        }

        std::unordered_map<Key, T, PairHash>  data;
};

int main()
{
    UMapMatrix<int>     data;

    std::cout << data.get(1500, 3000) << "\n";
    data.set(1500, 3000, 234);

    std::cout << data[1500][3000] << "\n";
}


Applying correction to a time series in Matlab

There is really nothing wrong with using a loop in MATLAB. For decades, they have been teaching us to vectorize our code. But in recent years the differences between vectorized code and the equivalent loop code has been shrinking dramatically. And I've run into examples where vectorized code is actually slower!

Nonetheless, there is a simple improvement to be made to your code. Note that what you implemented is an algorithm of \$O(n^2)\$. This simplified bit:

for i = 1:numel(ts)
   ts(i:end) = ts(i:end) + correction(2);
end

does \$n(n+1)/2\$ additions (hence \$O(n^2)\$). Also the indexing is expensive, since you're copying half the array (on average) every loop iteration.

I suggest that, instead of adding correction(2) to all subsequent elements, you store the "current correction", update it every loop iteration, and add it to the current value only.

Below is the test function I wrote. method1 is your code, method2 is my suggestion. At the top is a function that exercises these two methods, compares their output, and times them:

function test_methods
ts = [1 2 3 4 3 2 1 0 -1 -2 -3];
ts1 = method1(ts);
ts2 = method2(ts);
if any(abs(ts1-ts2)>1e-6)
   error('the methods differ');
end
timeit(@()method1(ts))
timeit(@()method2(ts))

function ts = method1(ts)
threshold = [-3.5 3];
correction = [1 -1];
for i = 1:numel(ts)
   if ts(i) > threshold(2)
      ts(i:end) = ts(i:end) + correction(2);
   elseif ts(i) < threshold(1)
      ts(i:end) = ts(i:end) + correction(1);
   end
end

function ts = method2(ts)
threshold = [-3.5 3];
correction = [1 -1];
current = 0;
for i = 1:numel(ts)
   value = ts(i) + current;
   if value > threshold(2)
      current = current + correction(2);
      value = value + correction(2);
   elseif value < threshold(1)
      current = current + correction(1);
      value = value + correction(1);
   end
   ts(i) = value;
end

For the short example input, these functions both run too fast for accurate timing. I see 3.1 μs and 1.4 μs, my version is only twice as fast as yours. But for larger inputs the differences become more important (I figured that the cumulative sum of a random process would imitate appropriately your drifting variable):

ts = cumsum(randn(1,1000));

0.29 ms and 8.33 μs, an order of magnitude difference.

ts = cumsum(randn(1,100000));

Now I see 1.66 s and 0.812 ms, 3 orders of magnitude difference.

Because method1 is quadratic in the input length, and method2 is linear, the time difference grows quadratically.


First up, yes, you're right that the second null check is redundant. If obj is null then the method will return false on the first check:

    if (!(obj instanceof ArrayOfColumn)) return false;

Of course, that would better be written:

    if (!(obj instanceof ArrayOfColumn)) {
        return false;
    }

But, that's the least of my concerns. The synchronized equals is probably there because other methods are synchronized, but synchronization comes at a cost. Unless you are sure you need it, remove it.

Additionally, synchronized methods are seldom the best solution. It is normally better to have tighter control of your locks so that nobody but you can hold them. That normally means using a private, internal "monitor" for synchronization:

private final Objct lock = new Object();

private boolean equals(Object obj) {
    synchronized(lock) {
        .....
    }
}

Using the private lock prevents other people from hanging your application by using your class as their own monitor. Imagine if your class is called MyClass, and someone does:

 private MyClass instance = new MyClass();

 synchronized(instance) {
     Thread.sleep(10000);
 }

If they did the above, your methods in other threads would never run, and your application would "hang".

Now, abut the __equalsCalc variable. It does nothing useful. It is set, and then cleared, inside the synchronized method, and, as a result, it will never, ever have any value in it that is useful. It is completely redundant and a waste of time.

Oh, and what's with the fully qualified java.lang.Object? Just use Object.

I would rewrite the method as (using the same synchronized method to be compatible with other methods in your class):

public synchronized boolean equals(Object obj) {
    if (!(obj instanceof ArrayOfColumn)) {
        return false;
    }
    if (obj == this) {
        return true;
    }
    ArrayOfColumn other = (ArrayOfColumn) obj;
    if (getColumn() == null) {
        return other.getColumn() == null;
    }
    return other.getColumn() != null && Arrays.equals(column, other.getColumn());
}

Note that you still have a synchronization vulnerability - the other column's column could be changed between checking for whether it's column is null, and using the column in the equals. You could still get null pointer exceptions if someone changes the other column in the middle of your equals. You should consider synchronizing on that other column too:

public synchronized boolean equals(Object obj) {
    if (!(obj instanceof ArrayOfColumn)) {
        return false;
    }
    if (obj == this) {
        return true;
    }
    ArrayOfColumn other = (ArrayOfColumn) obj;
    synchronized(other) {
        if (getColumn() == null) {
            return other.getColumn() == null;
        }
        return other.getColumn() != null && Arrays.equals(column, other.getColumn());
    }
}

Unfortunately, cross-synchronizing like that can lead to deadlocks if you are not careful.


So:

function configureDateTimePicker(selector1,selector2)
{
    $(selector1).datetimepicker(
    {
        defaultTime: '07:00',
        lang: 'en',
        className: 'setTimeClicker',
        step: 30,
        onChangeDateTime: function (current_time, $input)
        {
            // alert(ct.dateFormat('d/m/Y'))
            $(selector2).removeClass('empty').val(current_time.dateFormat('Y-m-d H:i'));
        },
        inline: true
    });
}

configureDateTimePicker('.jqDatetimeDateOne','#emailGenDateOne');
configureDateTimePicker('.jqDatetimeDateTwo','#emailGenDateTwo');
configureDateTimePicker('.jqDatetimeSearchDateOne','#searchGenDateOne');
configureDateTimePicker('.jqDatetimeSearchDateTwo','#searchGenDateTwo');

There could be further optimisations if you changed your classes/ids so that one could be derived from the other or from a common string (e.g. if they were all .jqDatetimeSomething and #genSomething). Or if there's a way to find the one of the targets through their relationship in the DOM (e.g. one is a descendant of the other matching a given selector).


Getting multiple table schema and returning them, using one helper method

Generics

When you say, ArrayList<ArrayList<?>>, you are saying that there is a type but that you don't know what it is.  So you write it as a ?.

But in your code, you are putting ArrayList<Attribute> and ArrayList<Group> into the larger list.  These are not one type.  So it has to find a type that covers both Attribute and Group.  Absent both extending or implementing some common class or interface, that will be Object.  So ? is actually Object in your code.

It is natural to think that ? is a wildcard that can match multiple things simultaneously.  But it is not.  It represents exactly one type at a time.  You just avoid having to say which type.  As such, I don't think that it is what you want to use here.

Cast by element not collection

The general way to fix this warning on something like

    ArrayList<Attribute> listAttrs = (ArrayList<Attribute>) lists.get(ATTRIBUTES);

would be something like

    List<Attribute> listAttrs = new ArrayList<>();
    for (Object attr : lists.get(ATTRIBUTES)) {
        if (attr instanceof Attribute) {
            listAttrs.add((Attribute) attr);
        }
    }

You can often leave off the instanceof check because you know what the result should be.

I changed from the implementation (ArrayList) to the interface (List), as is customary in Java when you aren't using implementation specific methods unavailable to the interface.

But I wouldn't recommend that code for this specific problem.  You don't really need to cast here.  You control the code at both ends and in between.  Just write it without casts.

Custom return type

The most direct way to fix this specific problem is to replace your return value with a custom class.

class AttributesAndGroups {

    private List<Attribute> attributes;

    private List<Group> groups;

    public void setAttributes(List<Attribute> attributes) {
        this.attributes = attributes;
    }

    public List<Attribute> getAttributes() {
        return attributes;
    }

    public void setGroups(List<Group> groups) {
        this.groups = groups;
    }

    public List<Group> getGroups() {
        return groups;
    }

}

You can use this like

        AttributesAndGroups result = new AttributesAndGroups();
        result.setAttributes(listAttrs);
        result.setGroups(listGroups);
        return result;

and in the caller

        AttributesAndGroups lists = getAttributesAndGroups();
        List<Attribute> listAttrs = lists.getAttributes();
        List<Group> listGroups = lists.getGroups();

No casts (unchecked or otherwise).

There's a lot of boilerplate code in the class.  It's possible to avoid that here.

Pass to the method

Another alternative would be to pass the lists into the helper method rather than have the method initialize them.

        List<Attribute> listAttrs = new ArrayList<>();
        List<Group> listGroups = new ArrayList<>();
        fillAttributesAndGroups(listAttrs, listGroups);
        request.setAttribute("listAttrs", listAttrs);
        request.setAttribute("listGroups", listGroups);

I changed the name to be more representative of the revised implementation.

And then the method signature would be

private void fillAttributesAndGroups(List<Attribute> listAttrs, List<Group> listGroups) {

Now just delete

    ArrayList<ArrayList<?>> retList = new ArrayList<ArrayList<?>>();
        ArrayList<Attribute> listAttrs = new ArrayList<Attribute>();
        retList.add(listAttrs);
        ArrayList<Group> listGroups = new ArrayList<Group>();
        retList.add(listGroups);
    return retList;

And the remainder of your code should function normally.

Again, no casts needed.  And this code is much terser, particularly if this is the only time you call it.

Another alternative would be to pass request into the method, but I won't try to implement that here.  That would allow you to make the lists inside the method again.


Using nested if statements to select textfield for update of associated label

First thing:

When you have a structure like that:

if (responses[1] != badResult) {
...
   if (responses[2] != badResult) {
   ...
      if (responses[3] != badResult) {
      ...

You probably have to use a loop, as the number of if statement will increase in function of the number of results in your array.

Also, you try to access to an array value without checking if this index is inside the size of your array:

i.e. : if (index >= 0 AND index < responses.cout )

What if your array has less than 4 values?

So to prevent this, it will look like that:

for (int i = 0; i < responses.count; i++) {
    if (responses[i] != badResult) {
        double num = ([responses[i] floatValue] / 1000.0);
        NSString *currentAnswer = [NSString stringWithFormat:@"%.2f km", num];
        // Do something with 'currentAnswer' like putting it inside an array (datasource)
    }
}

Second Thing

When you have that kind of UI (repetitive stuff, block/pattern of component with common function)

=> it's always depending on context,

But, it's better to use a component with reusable view, datasource: UITableView, UICollectionView etc...

You can check this tutorial if you need help to build a table view.

/------------------------------------/
          For testing only
/------------------------------------/

Also, there is another way, which is quick and dirty, but it works:

You can use view tag to access them in an ordinate way.

From your storyboard, set the tag value of the first distance label (distanceA) to 100
for distanceB 101
for distanceC 102

and so on...

Now you can access to the label from an integer thanks to

UILabel *label = (UILabel*)[self.view viewWithTag:100];

So if you put it in the previous loop:

 for (int i = 0; i < responses.count; i++) {
    if (responses[i] != badResult) {
        double num = ([responses[i] floatValue] / 1000.0);
        NSString *currentAnswer = [NSString stringWithFormat:@"%.2f km", num];
        // Getting the label with tag, THIS IS WEAK CODE
        UILabel *label = (UILabel*)[self.view viewWithTag:100+i];
        // set the currentAnswer string
        label.text = currentAnswer;
    }
}

/-------------------------------------------------/

Remember, using UITableView or UICollectionView is much better!


Avoid redundant code in this simple method

There is still some redundant code in there(' - %H:%M' and '%A %e %B %Y'). You could put these in variabels, but i like it so more. Sory for my bad English.

public function formatToFullDate($countryCode, $hideTime = false)
{
    $format = '';
    $time_format = '';
    switch($countryCode)
    {
        case 'us':
        case 'ca':
            $time_format = ' - %I:%M %P';
            $date_format = '%A %e %B %Y';
            break;
        case 'de':
            $time_format = ' - %H:%M';
            $date_format = '%A, den %e. %B %Y';
        break;
        default:
            $date_format = '%A %e %B %Y';
            $time_format = ' - %H:%M';
    }
    if($hideTime)$time_format = '';

    return gmstrftime($date_format.$time_format, $this->getTimestamp());
}


Optimization of Barnes-Hut Multithread Insertion algorithm

You should know, what's the bottleneck. Do you have two locks altogether? This doesn't sound good, as each part of the tree can be worked independently on. This means you could run on hundreds of CPUs efficiently.

The operations you do under lock are rather simple, which means that the overhead of locking can be significant. Can't you separate the three into a few parts and assign one CPU to each part?

Now some boring general comments:

boolean run = true;
while(run){
    i = barnesHut.getIndex();
    if(i < particle.length){ tree.insertThreaded(particle[i], thread); }
    else{ run = false; }
}

Where is i defined? Anyway, unobfuscate to

while (true) {
    int i = barnesHut.getIndex();
    if (i >= particle.length) break;
    tree.insertThreaded(particle[i], thread);
}

public synchronized int getIndex(){
    return index++;
}

That's what AtomicInt#incrementAndGet() is for.

Use better spacing, if (i < particle.length) { instead of if(i < particle.length){.


Prints out all ways to multiply smaller integers that equal the original number

public static void printFactors(int number) {
  if (number <= 0) {

You should include the number into the exception's text.

    throw new IllegalArgumentException("The number should be greater than 0.");
  }
  printFactorsList(number, number + "*" + 1 + "\n", number);
}

That's a bad name for a function.

private static void printFactorsList(int dividend, String factorString, int prevDivisor) {

This should be formatted as javadoc.

      /*
       * This function contains factorString as an argument to facilitate the recursive call for subsequent
       * factors until it reaches prime values. For example, let's say input number = 32 and when i = 8 it prints
       * 8*(32/8) ==> 8 * 4 but the subsequent reduction of 4 is needed and this is done by recursively passing in 4
       * as number. But we also want to maintain the chain "8 * ". So this makes the carry over string as an input
       * argument for the helper function printFactorsList
       */

Why not start this loop from prevDivisor?
Also, you can optimize this loop by storing numbers in factorized form and generating all divisors less than something on the fly. This will be much faster because you will iterate only over valid divisors. You can also memoize all solutions for a number and reuse them.

  for (int divisor = dividend - 1; divisor >= 2; divisor--) {

    if (dividend % divisor != 0) {
      continue;
    }

    if (divisor > prevDivisor) {
      continue;
    }

    int quotient = dividend / divisor;

          /*
           * 32*1 16*2 8*4 8*2*2 4*4*2 4*2*2*2 2*2*2*2*2
           *
           * Note: as we go right, the values keeps descending.
           */

Merge this two ifs into one.

    if (quotient <= divisor) {
      if (quotient <= prevDivisor) {
        System.out.println(factorString + divisor + "*" + quotient);
      }
    }
    printFactorsList(quotient, factorString + divisor + "*", divisor);
  }
}

public static void main(String[] args) {

You are not reading from anywhere. Is this the intended behavior?

  printFactors(32);
}


Interface design

You've lumped all of the functionality into one function.  At the least, you should have a function that is responsible for sequence-generating, and another for the prompting and printing.

To me, this problem cries out to be treated as a enumerator.  With an enumerator, you would automatically benefit from all of the members of the Enumerable mixin, especially #take, which takes the first n elements.

Since this is an infinite sequence, one tricky bit is to ensure that you define a lazy enumerator so that it doesn't try to generate the entire infinite sequence.

Implementation

The implementation would be a lot simpler if you took advantage of Enumerable#chunk.

Suggested solution

module LookAndSaySequence

  # An enumerator that generates the sequence "1", "11", "21", "1211", ...
  # (or with some other initial string of digits)
  def self.strings(init='1')
    Enumerator.new do |y|
      s = init
      loop do
        y << s
        s = s.chars
             .chunk { |digit| digit }
             .map { |digit, list| list.length.to_s + digit }
             .join
      end
    end.lazy
  end
end

print 'Enter the number of elements in sequence: '
LookAndSaySequence.strings.take(gets.to_i).each { |s| puts s }

… and a bonus variant LookAndSaySequence.numbers that produces Fixnums instead of Strings:

module LookAndSaySequence

  # An enumerator that generates the sequence 1, 11, 21, 1211, ...
  # (or with some other initial number)
  def self.numbers(init=1)
    strings(init.to_s).map { |s| s.to_i }
  end
end


Parsing twice

Instead of parsing dateStr twice, consider passing the Date object you have already constructed to the local time zone into prefix(String).

Calendar vs Date

A Calendar object has arguably better semantics than a Date, so it may be easier to access the individual chronological fields (actually, in your case, just the day component).

Lengthy try-catch block

Your try-catch block in convertUTC(String) spans the entirety of the method, but it's generally recommended to keep them short and to-the-point so that you effectively get a fail-fast mechanism. It's also easier to understand what's the exact code that might plausibly throw the checked Exception, so that it can be easier to refactor in the future.


I'd start by converting all the 1's in the input to some value that can't appear in the output  (e.g., -1) and saving each of those locations.

Then I'd basically do a modified flood-fill, starting from each -1. Look at each of its neighbors, and any there are currently 0, set to 1 and save that location. Repeat for every other -1 in the input.

Then walk through all the saved locations. Each neighbor of those that's a zero, set to 2 (and, again, save those locations).

Repeat until you reach an iteration that doesn't find any more 0s in the input (and obviously, incrementing the distance number for each of these outer iterations).

Finally, change all the -1s back to 0s.

As far as your code itself goes, it's tagged C++, but a great deal of it is very C-like. You have a couple of vectors, but quite a few C-things that most C++ programmers would rather avoid (e.g., printf, scanf and built-in arrays). I'm also less than excited about some of the names you've used (e.g., cZeroes and currDist). I'd rather see the names spelled out more completely (e.g., current_distance or, if you insist on camelCase, currentDistance).


Better way to write list of places program

Great start! You're very close. I changed things around a little bit, and added an extra template and a separate event map for that template. This should make it easier to understand, and it means you don't have to store the place's id in a data attribute. Check it out:

Places = new Meteor.Collection('places');

if(Meteor.isClient) {
    Template.places_list.places = function () {
        return Places.find({}, { sort: { name: 1 } });
    }

    Template.places_list.events({
        'keypress #place': function (evt) {
            if (evt.which === 13) {
                // The user pressed enter
                Places.insert({ name: evt.currentTarget.value });
                place.currentTarget.value = ''; // Reset the text input
            }
        }
    });

    Template.place_item.events({
        'click .plc_remove': function () {
            Places.remove(this._id); // Access the document fields with this.foo
        }
    });
}

And the HTML:

    <title>Place List</title>

Place List :

    {{> places_list}}

<template name="places_list">
    <input type="text" placeholder="Insert a place here" id="place" />

        {{#each places}}
            {{> place_item}}
        {{/each}}

</template>

<template name="place_item">

 {{ name}} | x |

</template>


Custom output stream that acts like std::cout

Construction

The construction of a MyStream object will proceed like this:

Construct std::ostream part with pointer to not-yet-constructed std::streambuf part.
Construct std::streambuf part.
Construct MyStream part.

Thus, suggestion: Reorder inheritance list like this:

struct MyStream : std::streambuf, std::ostream

override specifier

Nitpick: Add override specifier for overflow() function:

std::streambuf::int_type overflow(std::streambuf::int_type c) override

struct vs class

Another nitpick. I'm noticing that you are using struct instead of class. It is subjective, but I like to distinguish between struct and class like this:

If the resulting object will mostly be used by calling its methods - it's a class.
If the resulting object will mostly be used by accessing its fields - it's a struct.

Thus, for MyStream I would use class instead of struct. But, as I said, it is subjective.


The indentation needs to be mentioned. Hopefully it's just an accidental tabs vs spaces issue that caused it to render this way, ...but I'm not seeing the Tab characters, so... the indentation needs to be mentioned, becauase this is not normal:

public IList<Employee> ReadEmployees(byte[] file, string companyId)
        {

Expected:

public IList<Employee> ReadEmployees(byte[] file, string companyId)
{

Just like you have here:

            using (var stream = new MemoryStream(file))
            {

And here:

                    for (var rowNumber = 3; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)
                    {

Now, with that cleared, the GetEmployeeRowSummary method looks much cleaner already:

private static Employee GetEmployeeRowSummary(ExcelWorksheet worksheet, int rowNumber, string companyId)

{
    var employeeId = Guid.NewGuid().ToString();
    return new Employee
    {
        CompanyId = companyId,
        EmployeeId = employeeId,
        EmployeeNumber = worksheet.Cells[rowNumber, 1].GetValue<string>(),
        FirstName = worksheet.Cells[rowNumber, 2].GetValue<string>(),
        LastName = worksheet.Cells[rowNumber, 3].GetValue<string>(),
        BirthDate = worksheet.Cells[rowNumber, 4].GetValue<DateTime>(),
        AppointmentDate = worksheet.Cells[rowNumber, 5].GetValue<DateTime>(),
        CompanyRunFrequencyId = 9,
        JobTitle = worksheet.Cells[rowNumber, 8].GetValue<string>(),
        DateCreated = DateTime.Now,
        EmployeeAddress = new List<EmployeeAddress>
        {
            new EmployeeAddress
            {
                EmployeeId = employeeId,
                StreetNumber = worksheet.Cells[rowNumber, 9].GetValue<int>(),
                Suburb = worksheet.Cells[rowNumber, 11].GetValue<string>(),
                City = worksheet.Cells[rowNumber, 12].GetValue<string>(),
                PostalCode = worksheet.Cells[rowNumber, 13].GetValue<int>()
            }
       }
   };
}

Consistent indentation is fundamental for clean, readable code.

But readability isn't the biggest problem here: the repeated calls to worksheet.Cells and {Range?}.GetValue are.

I'm not sure what ExcelPackage is, but it's definitely not VSTO, so maybe this isn't as much of a problem, but invoking worksheet.Cells[...].GetValue<...>() is spawning a RCW (Runtime Callable Wrapper - a .NET wrapper object to access a COM object) whose reference isn't captured, and thus could be leaking the object reference. If you were using VSTO, there would very likely be a "ghost" EXCEL.EXE process lingering in Task Manager forever, well after your application happily terminated.

In any case, working directly with worksheet cells is THE slowest thing you can do, whether in VBA or C# through COM interop, whether it be through VSTO or any other library.

Again I don't know what ExcelPackage is nor what this API has to offer, but in the native Excel object model Range.Value, when the Range object represents multiple cells, gives you a 2D variant array (object[,] in .NET) - if all you're ever interested in is the values that are in the cells (as seems to be the case), then you don't need to deal with worksheets and cells and .GetValue<T>().

So instead of looping through rows:

for (var rowNumber = 3; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)

Grab the values array (not sure what the syntax would be with this API - if your library doesn't allow you to grab a 2D array of values, drop that library and use VSTO):

var values = worksheet.Range(worksheet.Cells[3, 1], worksheet.Cells[lastRow, 13]).Value;

The idea is to get a Range object that encompasses all the cells you're interested in. Maybe that's everything from row 3 to worksheet.Dimension.End.Row, but even without knowing the slightest thing about this particular API I would fear that worksheet.Dimension.End.Row yields something like 1,048,576 - which is very very very unlikely the actual number of rows you need to care about.

With the Excel object model, you'd do something like sheet.Range("A" & sheet.Rows.Count).End(xlUp).Row to get the last interesting row (aka lastRow), and use that row number to make the "interesting range" from which to read the values.

Now that you have a 2D array that contains all the values, GetEmployeeRowSummary doesn't make much sense anymore: we don't care for a rowNumber, and we don't need a ExcelWorksheet reference anymore.

In fact all we need is a "row slice" of the 2D array, by copying the row to a new array (this code looks like it):

public T[] GetRow(T[,] matrix, int rowNumber)
{
    return Enumerable.Range(0, matrix.GetLength(1))
            .Select(x => matrix[rowNumber, x])
            .ToArray();
}

private static Employee ReadEmployee(object[] row, string companyId)
{
    var id = Guid.NewGuid().ToString();
    return new Employee
    {
        CompanyId = companyId,
        EmployeeId = id,
        EmployeeNumber = (string)row[1],
        FirstName = (string)row[2],
        LastName = (string)row[3],
        BirthDate = (DateTime)row[4],
        //...
    };
}

As for mapping the properties automatically, I'm not a fan. Something, somewhere needs to do the mapping, and I'd much rather it be explicit in the code. Automatic mapping would need more metadata than just column indices - you'd likely need column names and data types, so instead of copying the cells to an array you'd be copying the cells to some DataTable, or have the mapper understand what an Excel Range or ListObject is... all of which sound like quite a lot of effort for an error-prone way to just list the properties at the left of an = operator. If your explicit casts blow up, you'll know why. If the automagic mapping blows up, pray the library throws meaningful exceptions.


Type annotations
Using type annotations will make your program a lot more readable and easier to debug. For example:
def __init__(self, name, place, start = (0,0), power = 9):
    # assignments

becomes
def __init__(self, name: str, place : List[int], start: Tuple[int, int] = (0,0), power: int = 9):
    # assignments

I imported List, Tuple from the typing module from the standard library:
from typing import List, Tuple

Here's some further information on using type annotations.

Getter and Setter
Using getters and setters is rather unpythonic. You can instead modify the getting and setting behaviours by using the @property decorator like this:
def __init__(self, name: str, place : List[int], start: Tuple[int, int] = (0,0), power: int = 9):
    self._name = name

    # further assignments

@property
def name(self):
    return self._name

@name.setter
def name(self, value):
    if isinstance(value, str):
        self._name = value
    else:
        raise TypeError("must be a string")

This will allow you to use the properties without explicitly calling getter and setter methods:
my_robot.name = 'foo'
print(my_robot.name)

This question on StackOverflow contains some more detailed explanations.

Logic

You should also take a look at your setters for place and start.
You only check the type of the passed argument value, but do not
verify if the elements in the list or tuple are of type int.
You could consider using a custom class Position or similiar for
handling the positional logic of the robot. That way you can access
the different dimensions by their names instead of indices of
place (self.place[0] or self.place[1]). You'll also be able to put further logic (like clipping, etc.) into it.
power and check_power(): Depending on your intended functionality you might want to limit the number of steps that can be taken by a robot to the power that it has left. As it is now, a robot can take any number of steps as long as it has power > 0 left.
You should check the functionality left(value) and up(value) for big values, especially values that are > 2 * board_dimension. I suspect the results might be unintended.


Making my User model class code more modular, and correct

There are a couple of things that I would personally change about the code, at the moment the model is doing far too much. It's pulling in cookies, request parameters and accessing the database. That's not the responsibility of the model, any domain logic should be separated from the models themselves.

First I would recommend moving the session and cookie related code somewhere more suitable, like a Filter, which can be ran before an action in a Controller is executed (if we're using the MVC pattern here).

Let's call our Filter class UserAuthFilter, before each request is routed to the relevant controller this class will intercept the request and check if the user is currently signed in.

class UserAuthFilter extends Filter {

    public function beforeAction(RequestHandler $request) {
        $uid = $request->session('uid');
        $sessionHash = $request->cookie('shash');

        //check if these variables are connected to a valid login
        if(/*we are logged in*/) {
            $user = ...;
            $request->set('user', $user);
        }

        return true; // continue with execution
    }
}

Second, I would recommend having your User model be nothing more than a representation of data. So no domain logic in the User class, just data. Anything database related we will move into a new class, let's call it UserRepository.

public class UserRepository {

    private $db;

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

    public function create($fname, $lname, $email, $password) {
        // create user
    }

    public function search($searchTerm) {
        // search for $searchTerm
    }

    public function getUserByCredentials($username, $password) {
        // find a user with the gieven username and password or return null/false
    }
}

Now, the last thing left to refactor is the authentication side of things. To do this we'll create another new class, UserAuthService, which will handle authentication and session management.

public class UserAuthService {

    private $userRepo;

    public function __construct(UserRepository $userRepo) {
        $this->userRepo = $userRepo;
    }

    public function authenticate($username, $password) {
        $user = $this->userRepo->getUserByCredentials($username, $password);
        return $user === false ? false : $user;
    }

    public function logout(User $user) {
        // delete from sessions table where uid = $user->id
    }
}

Then instead of inserting into the session table from the UserAuthService on a successful login, from within your controller you check the credentials with a call to $userAuthService->authenticate(...) and if you get a valid result back, then you insert into the session table.

That's about all I can think of besides a couple of small improvements:

Give your classes meaningful names. RequestHandler doesn't seem like a suitable name given the calls you're making to it. Perhaps just Request would be better.
Try to keep your constructors as simple as possible, do you really need to be making calls to the database when a User object is created?

Hope this helps.


pow(x,2) is less efficient than simply multiplying with itself:

static double mj_distance(double x, double y, double x2, double y2) {
    double dx = x - x2;
    double dy = y - y2;
    return sqrt(dx*dx + dy*dy);
}

However because you just compare it against a distance you can do away with the square root and compare it against the square of the distance:

double d = speed * seconds;
if (d*d >= mj_distance_squared(this->x, this->y, x, y)) {

there is a atan2 function which takes a delta y and delta x to return the correct angle.

void mj_dot_rotate(struct mj_dot *this, double x, double y) {
    double dx = x - this->x;
    double dy = y - this->y;
    this->th = atan2(dy, dx);
}


Query the github api and filter the last 1000 commits which include and exclude certain words from the top 3 repositories in a given organization

if request.method == 'POST': is redundant; delete it.
Your

your request is missing the 'org', 'include' or 'ignore' parameters

is less than helpful. Why not tell the user exactly what they're missing?
This except block:
    try:
        org = request.get_json()["org"]
        include = request.get_json()["include"]
        word_to_ignore = request.get_json()["ignore"]

    except:
        return {"error": "your request is missing the 'org', 'include' or 'ignore' parameters"}

will tell the user that their request is missing a parameter even if the server runs out of memory, or the entire payload is the string banana instead of a well-formed JSON body; or someone attaches the server process to a console and presses Ctrl+C to break it. Are you sure that all three of these exceptions constitute the user having submitted a well-formed JSON payload missing one or more keys? Never bare except:.
Move your query string parameters into a params dictionary sent to requests.
This:
    if not "items" in repo_data_dict:
        if "errors" in repo_data_dict:
            return {"invalid_organization": f"{org} does not exist or doesn't have any repositories"}
        else:
            return {"reached_api_limit": True}

is a wild and crazy guess. What if 'errors' told you that the server is down for maintenance, or you submitted a malformed payload, or the endpoint is deprecated? You need to pay attention to the contents of the error message given to you.
Don't json.loads here. Just call .json() on the response.
Be sure to check for HTTP error conditions via response.raise_for_status().
You need to break up get_matches into multiple methods.
You need to improve separation of concerns - get_matches returns dictionaries intended for consumption by the REST API, but that shouldn't be done in that function - payload dictionary formation should be done above, in the Flask handler function. To indicate errors, you can throw your own exceptions, catch them in the method above and add that to the response dictionary. To indicate whether you hit the API limit, you can add a boolean to your return tuple.
total_count is unused; delete it.
Your response format is flat, and this can be inconvenient and inefficient to consume on the client side. Instead consider a dictionary of repositories, each value being a list of messages, rather than adding the repo name to every response element.
This check:
                    if commits["total_count"] < MAX_PER_PAGE:
                        items_exist = False

seems to exist at the wrong level of indentation, since it applies to commits in general and not the current iterated commit.
This:
commits["total_count"] > page-1 * MAX_PER_PAGE

almost certainly does not do what you want, since it's doing
page - (1*MAX_PER_PAGE)

and not
(page - 1)*MAX_PER_PAGE

so add parens as appropriate.
Some of the above suggestions baked into an example:
from pprint import pprint
from typing import List, Tuple

import requests

NUM_REPOS = 3
MAX_PER_PAGE = 100
NUM_PAGES = 10
HEADERS = {"Accept": "application/vnd.github.cloak-preview"}

class InvalidOrganizationError(Exception):
    pass

class APILimitError(Exception):
    pass

# @app.route('/search', methods=('POST',))
def handle_search() -> dict:
    payload = request.get_json()

    try:
        org = payload['org']
    except KeyError:
        return {'error': 'Missing the "org" parameter'}

    try:
        include = payload['include']
    except KeyError:
        return {'error': 'Missing the "include" parameter'}

    try:
        word_to_ignore = payload['word_to_ignore']
    except KeyError:
        return {'error': 'Missing the "word_to_ignore" parameter'}

    matches, api_limited = get_matches(org, include, word_to_ignore)
    return {'matches': matches, 'reached_api_limit': api_limited}

def get_repo(org: str) -> dict:
    with requests.get(
        'https://api.github.com/search/repositories',
        params={
            'q': f'org:{org}',
            'sort': 'stars',
            'order': 'desc',
            'per_page': NUM_REPOS,
        },
        headers=HEADERS,
    ) as resp:
        resp.raise_for_status()
        repo_data_dict = resp.json()

    repo_list = repo_data_dict.get('items')
    if repo_list is not None:
        return repo_list

    if 'errors' in repo_data_dict:
        raise InvalidOrganizationError(
            f'{org} does not exist or does not have any repositories'
        )
    raise APILimitError()

def get_commits(org: str, include: str, repo_name: str, page: int) -> dict:
    with requests.get(
        'https://api.github.com/search/commits',
        params={
            'q': f'{include} repo:{org}/{repo_name}',
            'per_page': MAX_PER_PAGE,
            'page': page,
        },
        headers=HEADERS,
    ) as resp:
        resp.raise_for_status()
        return resp.json()

def get_matches(
    org: str, include: str, word_to_ignore: str,
) -> Tuple[
    List[object],  # All matches
    bool,          # Did we hit the API limit?
]:
    repo_list = get_repo(org)

    matches = []

    for repo in repo_list:
        messages = []
        repo_info = {'repo': repo['name'], 'messages': messages}
        matches.append(repo_info)

        page = 1
        items_exist = True

        while items_exist and page <= NUM_PAGES:
            commits = get_commits(org, include, repo['name'], page)

            if "message" in commits:
                return matches, True

            if "items" in commits and (
                page == 1 or commits["total_count"] > (page-1) * MAX_PER_PAGE
            ):
                for commit in commits["items"]:
                    message = commit["commit"]["message"]

                    if word_to_ignore in message:
                        continue

                    messages.append(message)

            else:
                break

            if commits["total_count"] < MAX_PER_PAGE:
                items_exist = False

            page += 1

    return matches, False

def test():
    matches, api_limited = get_matches('microsoft', 'repo', 'fetch')
    pprint(matches)

if __name__ == '__main__':
    test()


You could make a strong argument that you need 2 tests.

General theory has a unit test (as opposed to an integration test) containing only one assert, see e.g. Programmers.StackExchange

So you probably want:

[Test]
public void Delete_WithValidBook_ReturnsRedirectToRouteResult()
{
    bookRepository.Add(someBook);
    var result = booksController.Delete(someBook.Id);
    Assert.That(result.Type, Is.EqualTo(typeof(RedirectToRouteResult)));
}

[Test]
public void Delete_WithValidBook_RedirectsToValidIndex()
{
    bookRepository.Add(someBook);
    var result = (RedirectToRouteResult)booksController.Delete(someBook.Id);
    Assert.That(result.RouteValues["Action"], Is.EqualTo("Index"));
}

This has the added advantage that it is much easier to find the bug later based on the name of the failed test alone.

For example, if your type test fails, presumably your redirect test will also fail, but I know which I'd look at first during debugging!

If, on the other hand, the Delete method is guaranteed (by the framework) to return a RedirectToRouteResult, then you only want one test:

[Test]
public void Delete_WithValidBook_RedirectsToValidIndex()
{
    bookRepository.Add(someBook);
    var result = (RedirectToRouteResult)booksController.Delete(someBook.Id);
    Assert.That(result.RouteValues["Action"], Is.EqualTo("Index"));
}

If you have multiple tests, or a guard assertion, the reader (i.e. you at some point in the future) will assume that it must be possible to get, say, a null result, which will mean you may feel the need to add null checks, etc, to other parts of the code that may not be required.


Reading a file line by line - Two tokens per entry

1) Control flow clarity

if a and b: ...
elif a and not b: ...
elif not a and b: ...
elif not a and not b: ...

can be improved to

if a:
    if b: ...
    else: ...
else:
    if b: ...
    else: ...

2) Remove unnecessary function calls

' '.join([a, b]) can be simplified to a + ' ' + b. In your case, since you're appending b, you can do a += ' ' + b.

3) Implicit slicing notation

line[0:-2] can be line[:-2].

4) Consolidate constants

The regex string is a constant and is used multiple times. It can be moved to the top as a constant (or even outside the function).

5) Remove unnecessary comments

Assume the reader is familiar with built-in functions like str.split(). Thus, # remove \n and other spaces is unnecessary.

6) Readability

Include exactly one space before and after an assignment. e.g line = line.strip().
No need for if a == True or if a == False. Instead, do if a or if not a.
Remove unnecessary line breaks near the top.
Add spaces after commas in a function's parameters. e.g: f(a, b) instead of f(a,b).
Pick either camelCase or under_scores for variable names. Don't use both.

Final result:

def get_tokens(file_paths):
    REGEX = r'(?<!\\\n)^(0[xX][0-9a-fA-F]+)([^\n]*)'

    for path in file_paths:
        rule_capture = False
        with open(path) as f:
            for line in f:
                line = line.strip()
                if line.startswith('#'): # ignore comments
                    continue

                if line.endswith('\\'):
                    if rule_capture:
                        buffer += ' ' + line[:-2]
                    else:
                        buffer = line[:-2]
                        rule_capture = True
                else:
                    if rule_capture:
                        buffer += ' ' + line
                        rule_capture = False
                        event_rule_match = re.search(REGEX, buffer)
                        yield event_rule_match.group(1), event_rule_match.group(2)
                        buffer = ''
                    else:
                        event_rule_match = re.search(REGEX, line)
                        if event_rule_match:
                            yield event_rule_match.group(1), event_rule_match.group(2)

Notice I didn't change any of the logic, but just moved things around or removed things. See if you can simplify the logic (e.g. removing unnecessary assignments, etc).


Rewriting SQL IN statement with long list of parameters

Inside your SUM, each record has a value of either 1 or 0. The value is 1 if some condition is true for that record, and 0 if false. In other words, you're really counting the records where the condition is true.

The condition appears to be, Sales.TypeID should be one of 1,2,3,4,7,8,10. And if I understood it correctly, these correspond to the ids of the SaleType records where SaleType.Desc = 'US'.

It sounds like you want to join the Sales and SaleTypes tables,
where Sales.TypeID match SaleTypes.ID,
and SaleType.Desc = 'US'.
So this query:

SELECT count(*)
FROM Sales s
JOIN SaleTypes st
ON s.TypeID = st.ID
WHERE SaleTypes.Desc = 'US'


Lookup an array against another with performance

You could create a look up table (a simple object) where you can pre calculate the amount of times a domain is in the repeated in the domains array, this reduces the algorithmic complexity of your current solution which is n * m (dataElements  * domainElements)
Whereas my suggestion has a lower complexity of (n + m)

const data = [
    {
        Domain: 'google.com',
        '# Reocurring Domains': 0
    },
    {
        Domain: 'apple.com',
        '# Reocurring Domains': 0
    },
    {
        Domain: 'facebook.com',
        '# Reocurring Domains': 0
    }
]

const domains = [
    {
        'google.com': true,
        'microsoft.com': true,
        'google.com': true
    },
    {
        'apple.com': true,
        'microsoft.com': true,
        'twitter.com': true
    },
    {
        'facebook.com': true,
        'apple.com': true,
        'facebook.com': true
    }
]

const domainsObj = {}

domains.forEach(domain => {
    Object.keys(domain).forEach(key => key in domainsObj ? domainsObj[key] += 1: domainsObj[key] = 1)
})

data.forEach(element => element['# Reocurring Domains'] = domainsObj[element.Domain]);

console.log(data);

This approach increases memory usage, but improves calculation speed.


Well, your code is indeed doing DFS and it is doing tail recursion. I don't see any improvement from an algorithm perspective.
One low-hanging fruit is to get rid of seen_nodes as it seems to exist only for debugging purposes.


You listed three distinct things that happen when you perform this operation. That means you should have three distinct test cases.
Clumping them all together means:

If one of the assertions about the first thing fails, none of the insertions about the other results occur. If 1 and 3 are both failing, but 2 is succeeding, that is important information to help determine the root cause of the problem.
With the way the code is now, the following can happen. The test case fails indicating that 1 is not happening correctly. You edit the code so that 1 happens correctly. When you re-run the test case, it fails because 3 isn't happening. Was 3 never happening? Is 3 not happening now because of the changes you made to fix 1? You don't know. By using multiple test cases, you will always know what is happening and what is not.

The test case is hard to read. There are 10 lines dedicated to checking if the proper result was achieved. A person who hasn't seen the code before, should have to dig through all of that just to see what the the test case is checking for.

Ways to improve:

One test case for one distinct result. You can have multiple assertions in a test case, but they should be verifying the same concept.

Clear and descriptive test names. Ideally, the method name should tell you 1) What is being tested, 2) What are the inputs (context of the test case)? 3 What the expected result is? This way, you could already have an idea of what might be wrong before even seeing the code. Your test case is following this naming structure, but it is too generic. This is another indication that you might be checking two different concepts in the same test case.

Extract more complicated assertions into a method. Just like with real code, extracting functionality into a method is a great way to improve readability. All of your assertions have very descriptive error messaged. In general, this is not a bad thing, but it might be an indication that just looking at the assertion might not clearly indicate the intent to someone reading the code. Creating a specific method for the assertion can hide away to long string.Format() call and keep the test case clean.

Other comments:

Starting your error messages with "Error:" is redundant. The fact that this message is being shown indicates that there is an error.

Use constants to clean up your test case setup. Since you will likely have many test cases with similar inputs, constructing expectedMRID for a specific point will get repetitive.

Use variable names to indicate if input values have meaning. Are you explicitly testing 5,10 or are those just some value to represent a generic input. This could help someone else know the real intent of a test case.

Not related to the test case, but the API you are testing seems like a real pain to work with. You have to craft this specifically formated dictionary just to create an point with a specified x and y coordinates. Then to get a value, who id happens to be related to the coordinates, you have to pass in a string key to get the value, which then has to be cast to the proper type.


Sorry to bump this one year old question, but there is something inherently wrong in your equality check if you ever extend to more than one level of inheritance.

Consider a class Foo deriving from Circle, assuming the same implementation (with changed types of course).

Foo foo;
Circle circle;
Shape & shapeFoo = foo;
Shape & shapeCircle = circle;

// these two should behave the same, but they don't:
std::cout << (shapeFoo == shapeCircle) << std::endl;
std::cout << (shapeCircle == shapeFoo) << std::endl;

Why does this fail?

shapeFoo == shapeCircle will call shapeFoo.Equals(shapeCircle) which will be dispatched on the implementation of Equals in class Foo. There the dynamic_cast<Foo const *> will fail, correctly returning false.

However shapeCircle == shapeFoo will call shapeCircle.Equals(shapeFoo) which will be dispatched on the implementation of Equals in class Circle. There the dynamic_cast<Circle *> will succeed (as Foo is a descendant of Circle). Then the method will compare only the attributes of Circle, probably returning true.


Follow PEP8 style guide for variable and function naming convention. Both the variables and function names should have snake_case names.
You can use enumerate to get index and value while iterating a list.

For constant space solution, instead of using a list to keep track of current max and min products, use a variable for both positive product and negative product. If the current number is \$ 0 \$, reset them both to \$ 1 \$ (They should be initialised as \$ 1 \$ as well). At the end of for-loop (inside the loop), keep updating your current_max value to keep track of max product encountered so far.

As edge cases, you may also consider returning (or raising errors) when input was empty etc.


Compute the XOR of all the elements in the upper left triangular of a square matrix

You will need to look at \$O(n^2)\$ elements, therefore there is no algorithm that runs faster than \$O(n^2)\$.

That is, unless you have an explicit formula for the solution which abuses the fact that the elements are all consecutive.

Notice what these XOR to:

      cumulative XOR
0 000 000
1 001 001 |
2 010 011 |
3 011 000 |
4 100 100 |
5 101 001
6 110 111
7 111 000

We'll notice a few patterns. The cumulative XOR of all elements \$\lt 2^k\$ for any k is 0.

Here's another, more useful pattern: for any run of \$2^k\$ consecutive elements (e.g. see markers above), all binary digits except the most significant bit will repeat. Therefore we can explicitly compute the XOR of an arbitrarily large sequence \$a \ldots b\$ of length \$2^k\$ in one step (it's all 0s except the most significant digit is b - max(a, largestPowerOf2LessThanB) % 2, I think, where \$\mathrm{largestPowerOf2LessThanB} = 2^{\lfloor\log_2(b)\rfloor}\$).

Therefore we can calculate the sum of any arbitrarily large sequence in roughly \$O(\log(k))\$ steps.

Thus you can make an algorithm with running time \$O(n\log(n))\$ using this explicit formula.

You can maybe make it even faster if you can calculate contiguous blocks of the matrix?


Simplified error handling when reading from stdin and parsing to a type

Here's a few possibilities. They all rely on the fact that Result can be mapped over, both in the success and failure cases.

Additionally, I personally detest having trait bounds on generics inside the generic declaration. I almost always move them to a where clause for readability.

fn read_thing<T>() -> Result<T, &'static str>
    where T: str::FromStr
{
    let mut buffer = String::new();
    try!(io::stdin().read_line(&mut buffer).map_err(|_| "Failed reading from stdin."));
    buffer.trim().parse().map_err(|_| "Failed parsing input.")

This is the most direct modification to your existing code. It transforms the errors into the desired strings and uses the try! macro to return immediately on the first error.

use std::io::BufRead;

fn read_thing<T>() -> Result<T, &'static str>
    where T: str::FromStr
{
    let stdin = io::stdin();
    let v = stdin.lock().lines().next()
        .ok_or("No data to read")
        .and_then(|s| s.map_err(|_| "Failed reading from stdin"))
        .and_then(|s| s.trim().parse().map_err(|_| "Failed parsing input"));
    v
}

This was an attempt to chain it all together. It almost works nicely, but introduces a new error condition - what if stdin is fine, there's just nothing to read? Add to that the lifetime shenanigans that involve locking the standard in, and this isn't the nicest either.

fn one_line_from_stdin() -> io::Result<String> {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).map(|_| buffer)
}

fn read_thing2<T>() -> Result<T, &'static str>
    where T: str::FromStr
{
    one_line_from_stdin()
        .map_err(|_| "Failed reading from stdin")
        .and_then(|s| s.trim().parse().map_err(|_| "Failed parsing input"))
}

Continuing on a quest to chain it together, I extracted a method that just returns a single string. It's probably not very efficient, but reads OK.

fn read_thing2<T>() -> Result<T, &'static str>
    where T: str::FromStr
{
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).map(|_| buffer)
        .map_err(|_| "Failed reading from stdin")
        .and_then(|s| s.trim().parse().map_err(|_| "Failed parsing input"))

Same idea as the previous code, this just inlines the input method.

use std::error::Error;

fn read_thing<T>() -> Result<T, Box<Error>>
    where T: str::FromStr,
          T::Err: Error + 'static,
{
    let mut buffer = String::new();
    try!(io::stdin().read_line(&mut buffer));
    let v = try!(buffer.trim().parse());
    Ok(v)
}

This is what I'd probably write to start with. I find the messages from most errors to be fairly readable and understandable, but I'm not showing them to an end user most of the time. I'd just use a little elegance baked into the try! macro and the From implementation of Box<Error> to pass back the original errors, abstracted out to the generic concept of an error. More information can be found in The Rust Programming Language.

If I cared more about custom messages or efficiency, I'd upgrade to a custom error type. I've also recently discovered the quick_error crate which provides a macro to make custom types easier, but haven't had a chance to try it out yet.


Excel Retrieving Data from website through Internet Explorer

Worksheet functions were not designed for this. User-defined worksheet functions were not made a feature of Excel to go and fetch data online - in my humble opinion, this is a terrible abuse of UDF's.

A function like this should be part of the definition of a class module that defines an object responsible for this task, and wrapped with an interface, say ITickerPriceProvider:

Public Function GetTickerPrice(ByVal ticker As String) As Double
End Function

Then your code moves into a class module with Implements ITickerPriceProvider, and the signature becomes this:

Option Explicit
Implements ITickerPriceProvider

Private Function ITickerPriceProvider_GetTickerPrice(ByVal ticker As String) As Double
    'your code
End Function

What gives? Now you can get fancy and write a macro that looks like this:

Public Sub UpdateTickerPrices()

    Dim provider As ITickerPriceProvider
    Set provider = New WebTickerPriceProvider

    Dim updater As TickerSheetUpdater
    Set updater = New TickerSheetUpdater

    updater.UpdateTickerPrices provider, TickerPricesSheet

End Sub

And the TickerSheetUpdater.UpdateTickerPrices method is where you go and implement the code that locates ticker strings (your worksheet must have a column with those, right?), fetches the prices for each one, and updates the worksheet.

This is a job for a macro, not a UDF.

As a bonus, the TickerSheetUpdater class can be unit-tested because the dependencies are under control - and now if somebody cuts the network cable, you can handle errors gracefully, instead of having 200 UDF calls blowing up one after another.

As for the implementation itself, I don't see any glaring issues. I would have named IE something like browser, URL would have been url, and there would have been an On Error GoTo CleanFail statement at the top, and a CleanExit label to ensure resources get cleaned up whether or not an error occurs:

Private Function ITickerPriceProvider_GetTickerPrice(ByVal ticker As String) As Double
    On Error GoTo CleanFail

    'implementation here

CleanExit:
    Set browser = Nothing
    Set pageData = Nothing
    Exit Function

CleanFail:
    'handle errors
    Resume CleanExit

End Function

Turning ScreenUpdating off isn't going to help much, at least not with a UDF approach - the function isn't updating any cell values, it is a cell value.

However I'd try to see if there wouldn't be a way to remove this:

Application.Wait Now + TimeSerial(0, 0, 5)

...or add a comment that explains why it's needed, and why it needs to be a whole 5 seconds - especially given you've just waited for a specific ReadyState on your IE object:

 Do Until IE.ReadyState >= 4
        DoEvents
 Loop

What's 4 anyway? Make an Enum for the possible values, and use it instead of hard-coding a value like this. Why do you need to wait 5 seconds after the browser gets into that ReadyState? Could you keep loop-waiting for a later state value? An enum would help understanding what's going on and why here.


Typically, a Swing application would be written using a Model-View-Controller pattern to split the responsibilities:

The Model would be a data structure to represent the game state.  It could, for example, consist of an ConnectFourBoard class that holds a two-dimensional array of chips in the board.
The View would be the Swing UI code
The Controller acts as the glue between the Model and View.  It handles actions triggered by the View, and notifies the View when the Model has changed.

Here, I see View and Controller code, commingled.  However, I don't see any Model code.  In fact, in ColButton.actionPerformed(), it appears that the lack of a Model is causing you some difficulty: you're resorting to determining the model state by parsing the icon name out of the view.

Without a Model, you are no doubt going to have a difficult time examining the model state to determine the winner.


When you declare a class, initialize all member variables

char data = '\0';
size_t freq = 0;
...

(depending on your compiler you may need to do that in the
constructor instead)

especially pointers, since a delete on an uninitialized pointer is undefined behavior but a delete on a nullptr is OK (NOP).

void GenerateCode(std::vector<char>& data, std::vector<size_t>& freq, size_t size)

is your intention to modify 'data'? if not, then write const in front

void GenerateCode(const std::vector<char>& data, std::vector<size_t>& freq)

why do you pass 'size'? 'data' already has a size: data.size()

you have an unitialized member variable called 'top', you use it in GenerateCode and it
will be set there, but if you never call GenerateCode, just a simple class declaration will
invoke undefined behavior since delete top is called in HuffManCodes destructor.

memory ownership is not easy to follow in your code

avoid using raw pointers. By using smart pointers ownership is always
clear and you dont need to bother about where to delete.

struct Node
{
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;  // here it's clear that 'right' owns what it points to
    ...
}


Counting lowercase and uppercase letters in a string in Python

Your code is mostly fine. I'd suggest more meaningful names for variables, e.g. i is typically a name for integer/index variables; since you're iterating over letters/characters, you might choose c, char, let, or letter. For stri, you might just name it phrase (that's what you asked for from the user after all). You get the idea. Make the names self-documenting.

Arguably you could make it look "prettier" by performing a single pass per test, replacing:

stri_up = 0
stri_lo = 0
for i in stri:
    if i.isupper():
        stri_up += 1
    if i.islower():
        stri_lo += 1

with:

stri_up = sum(1 for let in stri if let.isupper())
stri_lo = sum(1 for let in stri if let.islower())

That's in theory less efficient, since it has to traverse stri twice, while your original code only does it once, but in practice it's likely faster; on the CPython reference interpreter, sum is highly optimized for this case and avoids constructing a bunch of intermediate int objects while summing.