C++ class for disjoint-set/union-find on integers

Seems pretty straightforward. By the way, "disjoint-set" is a less common name for this data structure than "union-find", at least in my experience.

You have several typos in your code; you should always fix those. Sure, the computer doesn't care, but we don't write C++ code for the computer; we write it for the human reader. elment_a should be element_a; you should either implement dup or remove its declaration; and you should use proper indentation.

class DisjointSet {
public:
    DisjointSet(int num_nodes);
    int find(int element);
    void do_union(int element_a, int element_b);
private:
    std::vector<int> parent_;
    std::vector<int> rank_;
};

Notice also that I added the missing std::s to your vectors (and by the way you should #include <vector>), and split each member variable declaration onto its own line so that the struct layout is easier to see at a glance.

Who says using rank_ is an optimization? It feels to me like a pessimization, because you're trading O(N) extra space (and more convoluted code) for something like O(lg N) faster lookups. I do see that e.g. Boost.DisjointSet implements "union by rank" as well, but I'd be interested in seeing some benchmark numbers on your particular use-case.

return parent_[element] = find(parent_[element]);

Modern C++ (like modern any-other-language) strongly prefers not to mix side effects into the middle of expressions, except in idiomatic cases such as *p++ = .... Prefer to put the assignment in its own statement.

parent_[element] = find(parent_[element]);
return parent_[element];

int fa = find(a), fb = find(b);

Same deal as above: prefer to put each variable declaration on its own line for readability.

int fa = find(a);
int fb = find(b);

And then use proper indentation in what follows:

if (rank_[fa] < rank_[fb]) {
    parent_[fa] = fb;
} else {
    parent_[fb] = fa;
    if (rank_[fa] == rank_[fb]) rank_[fa]++;
}

Basically, though, looks good. Looks like you picked the right level of abstraction for this particular problem: not too scattered (keeping related things in a nice neat class), but not too libraryish (you hard-code int, for example, instead of going all in with templates).


Better way to refer to common elements in a sequence of objects?

It is, as you say, slightly odd that a method in Car iterates over the container that Car is in. It really ought to be in Company, and take an argument for how many doors to match:

class Company:
    ...
    def searchByDoors(self, doors):
    ''' Get an iterator of all the cars in self that have the
        specified number of doors
    '''

    for car in self.cars:
         if car.doors == doors:
             yield car

This also brings up another point: you probably want to avoid printing from inside your class (except for debugging). Even if whatever you're writing now wants it printed, you should write your classes so they can be used in any program . So, a search function should give the matches back whichever part of your program called it, and it can print them if it wants to. Similarly, Car.printDoors can go - your program can get that information and print it. If there is a canonical way that you want represent a Car for human consumption, define it this way:

 class Car:
     ...
     def __str__(self):
         return "A {} {} with {} doors".format(self.company, self.type, self.doors)

And your program can just print(a_car) to print something like A porche sedan with 4 doors.

Note that, notwithstanding what the person on SO said about not making objects aware of their containers, it probably does make sense for a Car to know which Company made it.

There are two issues with using id as an attribute name:

The local variable in the constructor shadows the built-in id() function,
More importantly, car.id is different to id(car), even though they're named similarly and have similar purposes.

Consider whether id(car) is good enough for what you would use car.id for - it identifies a unique python object, and is called for you when you do things like a is b. If id needs to reflect something external to your program, consider renaming it. car_id might work, but if it represents something concrete in your problem domain (eg, an official registration number), naming it after that is even better.

There is also one issue with the way you're generating ids, that using Python's id() avoids: your ids are only unique within a company (and even that isn't guaranteed), but you could reasonably expect it to be unique across all cars. So, overall, I would drop id entirely.

typesToNum doesn't belong in Company, and this is really begging for a dictionary rather than a method. I'd make it a module-level private constant:

 # Mapping of car type (eg, sedan) to number of doors
 _DOORS_PER_TYPE = {'sedan': 4, 'convertible': 2, 'motorcycle': 0}

A car should really know what type of car it is, and with this mapping it would make more sense to take this at construction than the number of doors:

 class Car:
      def __init__(self, company, type):
            assert type in company.types
            self.type = type

      @property
      def doors(self):
          return _DOORS_PER_TYPE[self.type]

The assert makes sure that the type of car is one that that company does make. It is optional, its just a sanity check in case something impossible happens. Its a good idea, because that is more common than it sounds. Likewise, you can do:

   class Company:
       def __init__(self, types):

The constraint that a convertible always has 2 doors, and a sedan always has 4 is a little odd. If it might make sense in your program to have a 2 or 4 door sedan, but not, say, a single-door sedan, you could do this:

 _DOORS_PER_TYPE = {'sedan': (2, 4)}

 class Car:
      def __init__(self, company, type, doors):
          assert type in company.types
          assert doors in _DOORS_PER_TYPE[type]

          self.company = company
          self.type = type
          self.doors = doors

This also makes doors an attribute rather than a property since its no longer linked 1-to-1 with type, but the rest of your program doesn't need to care about that difference.

You can also change the valid car types and number of doors to vary between each company, but only if that makes sense for your model. If the number of doors is always 1-to-1 with the type, and that is always going to be independent of the company who built it, then it is better to have your code say so.


Don't use global variables

All your function parameters are global variables that introduce hard to track side effects.

If you want to use the function in multiple threads in parallel it will fail.

Just pass parameters and the code becomes much more readable as well, because you clearly see which variables are needed for the function to execute.

An interface that I'd like to have would be:

std::string convertInfixExpressionToPostfix(std::string infixExpression);

All the user of this function has to care about is to give the required input and retrieve the result.

This would make your calling code much more readable as well:

std::cout << convertInfixExpressionToPostfix("((5+5)*(6+6))") << "\n";

Not returning the result but printing it out is another such side effect which also hinders reuse. Instead of printing the result you would accumulate it in a string and return it (as given in my proposed interface).

Of course this interface does not fit your internal needs for the recursion so you would need another implementation function which does the actual calculation and has some more parameters.

Use specialized code were advisable

You state yourself that you use the std::vector as a stack. Why not use the std::stack, which has a much clearer interface for that.

Readability

Don't put two commands on one line like this:

ops.clear(); i = 0;

It makes it too easy to overlook one of them.

Know when to use switches

Your cascading ifs would be easier to handle with a switch:

switch(ch) {
case '(': /*...*/ break;
case ')': /*...*/ break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': /*...*/ break;
case '+':
case '-': /*...*/ break;
}

Eventually you would retain the if(isDigit(ch)) and leave out the digit cases.

Unnecessary variable

Your len variable just duplicates the length of the inp string. The length() method has constant time complexity so don't be afraid to use it.


I don't understand the point in using this pattern:

    catch (WebException ex)
    {
        var state = (RequestState)result.AsyncState;

        if (state.Response != null)
            state.Response.Close();

        AsyncManager.Parameters["webException"] = ex;
    }
    catch (Exception ex)
    {
        var state = (RequestState)result.AsyncState;

        if (state.Response != null)
            state.Response.Close();

        throw;
    }
    finally
    {
        AsyncManager.Parameters["key"] = "key";
        AsyncManager.OutstandingOperations.Decrement();
    }

When it looks like it could be simplified to this:

    catch (WebException ex)
    {
        AsyncManager.Parameters["webException"] = ex;
    }
    finally
    {
        var state = (RequestState)result.AsyncState;

        if (state.Response != null)
            state.Response.Close();

        AsyncManager.Parameters["key"] = "key";
        AsyncManager.OutstandingOperations.Decrement();
    }

The following may stem from my lack of familiarity with Amazon S3:

I'm not sure what functionality your ReadFully method offers over Stream.Read(Stream.Length) or, more safely, Stream.Read(Stream.Length - Stream.Position) except potentially causing issues if the stream does not have a length of multiplies of 16x1024.

Speaking of which, you've hard-coded that 16x1024 in a magic number:

var buffer = new byte[16 * 1024];

I would recommend converting these values to consts so you can change them later with ease.


RESTful APIs (Create, Read) with flask-restful

The MongoClient was designed to be instantiated once per app life cycle, so this is redundant. You should try to reuse MongoClient instances as much as possible. Basically the only reason to create a new instance is if you want to configure it in a different way.

Also you've mentioned your API is supposed to be RESTful, so a few notes here:

1) To deal with user resource you should include it in the uri in pluralize form and distinguish actions you are performing by standard http codes, like the following:

/api/users POST - to create a new user

/api/users/{userId} GET - to fetch an existing one by userId

2) when you a new user is created it is a good practise to return 201 (Created) http code together with the full url to fetch the user which has been just created, like: http://yourdomain.com/api/users/{userId}

3) "Failed to insert data. Check logs for more details" - it doesn't look like a 400 Bad Request, as the user didn't make any mistake with input params. I suppose it must be either 500 (if the issue is related to something like a database error for example) or 403 Forbidden if any of implicit domain rules has been violated

Hope this helps


Overall Impression

The code displays some good programming practices or habits. It is generally well structured, with well thought out functions. Good definitions of typedefs. The type size_t is used to index arrays instead of int.

There are several potential bugs in the code. They are potential because they could happen, not that they would happen as the code is written currently.

Error Checking

While the return values of malloc() are checked, there should be some additional error checking in 2 places in the code. The first is that in Polynomial* create_poly(size_t capacity) before any memory allocation takes place, the value of the parameter capacity should be checked that is larger than zero, if not the memory allocation should not take place.

The second place for additional error checking is in main(). If p after the call to create_poly() is NULL, assignments to p will fail, possibly causing a catastrophic error. This is one potential bug.

Memory Allocation

It might be better to use calloc() rather than malloc() in the following statement:

    coeffs = malloc(capacity * sizeof(real));

The memory allocation function calloc(size_t count, size_t size) was written with arrays in mind. In addition to being slightly more readable, calloc() sets all of the values to zero when the array is allocated, which means the values in the array are initialized.

    real* coeffs = calloc(capacity, sizeof(*coeffs));

Note that in the example of calloc() usage the sizeof() argument is what coeffs points to. This allows who ever is maintaining the code to change the type of coeffs without have to modify more than the type itself. If the type real was used in the statement, there would be 2 places to change the code and not one.

Unnecessary Statement

In the function void delete_poly(Polynomial* p) the statement p = NULL; is unnecessary. Since p was passed in instead of a pointer to p it only affects the local value of p, it does not affect the value of p in main().

Initialize Variables When They are Declared

In at lest 2 places in the code variables are declared on one line and then initialized on another line like the initialization is an after thought. A better habit to get into is to initialize the variables as they are declared. This can lead to less bugs and less debugging of code.

In main():

    Polynomial* p;
    const real EPS = pow(10, -7);
    p = create_poly(3);

Versus

    const real EPS = pow(10, -7);
    Polynomial* p = create_poly(3);

In create_poly()

    real* coeffs;

    coeffs = malloc(capacity * sizeof(real));
    if (coeffs == NULL) return NULL;

Versus

    real* coeffs = malloc(capacity * sizeof(real));
    if (coeffs == NULL) return NULL;

Magic Numbers

There are Magic Numbers in the main() function (10 and -7), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.

Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.

The code already has a symbolic constant defined in real newton_raphson_poly(const Polynomial*const p, real x0, real eps).

    const int max_iter = 100;

Write the code consistently.

Possible Optimizations

The code in main() could be more flexible or extensible if it modified to create an array of coefficients and get the size of the array as the capacity. The code to copy the coefficients into the Polynomial struct could be an additional function, or it could also be added to create_poly(size_t capacity, real coeffs[]).

int main()
{
    real coeffs[] = {-2, 0, 1};
    size_t capacity = sizeof(coeffs) / sizeof(*coeffs);

    const real EPS = pow(10, -7);
    Polynomial* p = create_poly(capacity);

    real* poly_coeffs_ptr = &p->coeffs[0];
    real* coeffs_ptr = &coeffs[0];
    for (size_t i = 0; i < capacity; i++)
    {
        *poly_coeffs_ptr = *coeffs_ptr;
    }

    printf("The result of sqrt(2) is given by the root of\n");
    print(p);
    printf("Its value is: %f \n", newton_raphson_poly(p, 1.0, EPS));

    delete_poly(p);
}

Reordering of malloc()s might lead to less code.

Polynomial* create_poly(size_t capacity)
{
    if (capacity > 0)
    {
        Polynomial* poly = malloc(sizeof(Polynomial));
        if (poly != NULL)
        {
            poly->coeffs = calloc(capacity, sizeof(real));
            if (poly->coeffs == NULL)
            {
                free(poly);
                poly = NULL;
            }
        }
        return poly;
    }

    return NULL;
}


Make palindrome finder-builder function faster

Make a local instance of word and work with that variable through all your function code, every reference to word it's been fetched through the scope chain.

During code execution, identifiers such as variable and function names are resolved by searching the scope chain of the execution context. Identifier resolution begins at the front of the scope chain and proceeds toward the back. Consider the following code:

function add(num1, num2){
    return num1 + num2;
}

var result = add(5, 10);

When this code is executed, the add function has a [[Scope]] property that contains only the global variable object. As execution flows into the add function, a new execution context is created, and an activation object containing this, arguments, num1, and num2 is placed into the scope chain.

This resolution is performed by inspecting each object in the scope chain until the specific identifier is found. The search begins at the first object in the scope chain, which is the activation object containing the local variables for the function. If the identifier isn’t found there, the next object in the scope chain is inspected for the identifier. When the identifier is found, the search stops. In the case of this example, the identifiers num1 and num2 exist in the local activation object and so the search never goes on to the global object.

Understanding scopes and scope chain management in JavaScript is important because identifier resolution performance is directly related to the number of objects to search in the scope chain. The farther up the scope chain an identifier exists, the longer the search goes on and the longer it takes to access that variable; if scopes aren’t managed properly, they can negatively affect the execution time of your script.

Use Local Variables

Local variables are, by far, the fastest identifiers both to read from and write to in JavaScript. Because they exist in the activation object of the executing function, identifier resolution involves inspecting a single object in the scope chain. The amount of time necessary to read the value of a variable increases with each step along the scope chain, so the greater the identifier depth, the slower the access is going to be.


Simple Calculator to add/subtract/multiply/divide 2 inputs

Formatting strings in Python
foo = 5
print('{foo}'.format(foo))

This is a nice way to format string, But there is a short and cleaner way to format strings in Python 3 known as the f-String. The problem with str.format() is that if you have multiple parameters. Your string starts to look a little werid.For example
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
print(("Hello, {first_name} {last_name}. You are {age}. " +
        "You are a {profession}. You were a member of {affiliation}.") \
        .format(first_name=first_name, last_name=last_name, age=age, \
               profession=profession, affiliation=affiliation))

With f-strings. The same would look like.
print(f"Hello, {first_name} {last_name}. You are {age}. " +
      f"You are a {profession}. You were a member of {affiliation}.")

This is why you should prefer using f-strings.
eval in Python
When you want to perform the arithmetic part, I see that you have used a thread of if-statements. But we can use Python's eval function to make life much easier. We simple place the operator entered by the user un between the two numbers.
old
if operator == 1:
    print('{0} + {1} ='.format(firstnum, secondnum), end =" ")
    print(firstnum + secondnum)
    break
if operator == 2:
    print('{0} - {1} ='.format(firstnum, secondnum), end =" ")
    print(firstnum - secondnum)
    break
if operator == 3:
    print('{0} * {1} ='.format(firstnum, secondnum), end =" ")
    print(firstnum * secondnum)
    break
if operator == 4:
    print('{0} / {1} ='.format(firstnum, secondnum), end =" ")
    print(firstnum / secondnum)
    break

We ask the user to enter the operation the want directly , for example

Choose an operator: +

Or if you want to stick to using numbers.
operators = operators = {'+':1,'-':2,'*':3,'/':4}
I have gone with the 1st method. You can use whatever you prefer to
new
print(f"{firstnum} {operator} {secondnum} = {float(eval(firstnum + operator + secondnum))}")

The new code using eval would like
operators = ['+','-','*','/']
while (True):
    # Gets operator, converts to int and breaks if its not a number
    try: operator = input("Choose an Operator:\n1) Addition\n2) Subtraction\n3) Multiplication\n4) Division\nInput\n(+,-,*,/):")
    except:
        print('Invalid Input: Choose A Valid Operation')
        break

    # Checks the operator is within 1 and 4
    if operator not in operators:
        print('Invalid Input: Choose A Valid Operation')
        break

    # Gets first and second number, converts numbers to float and breaks if its not a number
    try: firstnum = input('First Number:')
    except:
        print('Invalid Input: Not a valid number')
        break
    try: secondnum = input('Second Number:')
    except:
        print('Invalid Input: Not a valid number')
        break

    print(f"{firstnum} {operator} {secondnum} = {float(eval(firstnum + operator + secondnum))}")

With that simple change, I removed about 20 lines of code into one. Making it much more readable
Clearing the screen
It would be nicer to see a clear terminal after finishing one job. There are many ways to clear the terminal in python. A common way for windows users is
os.system('cls')

But this way is considered bad as it is quite expensive. You can get away by simply
print(chr(27) + "[2J")

Adding this to the start of each iteration in the while(True): loop will give a better experience to the user.
Waiting for input
Lastly, adding this line of code to the end will pause on the current text before going to the next one.
input("Press any key to continue...")


Vector vs raw array

When dealing with arrays that have a length know at run-time, you usually use an std::vector, it is cleaner and safer w.r.t the memory allocation (for dynamicity). When the size of the array is known at compile-time, consider using an std::array, which is the C++ way of using raw arrays.

In this case, I'd use an std::vector and a .reserve(length) call

Array out of bound

Here is a concrete argument to why you should use a vector: you are actually writing/reading outside of you array, which can fail immediately (if you are lucky), or can fail way later in your code (if you're unlucky).

int count = -1;
while(count++<length)
{
    unsorted[count] = rand()%max;
}

if you have length == 1 for example, here is what will happen, 'unwrapping' the while:

int count = -1;
if (count++ < 1) // count == -1, so count < 1 is true ; after that we increment count by 1, so count == 0
{
    // accessint unsorted[0]
    unsorted[count] = rand()%max;
}
if (count++ < 1) // count == 0, so count < 1 is true ; after that we increment count by 1, so count == 1
{
    // accessint unsorted[1], which is outside of the array
    unsorted[count] = rand()%max;
}
// after that, the condition is false

For loops vs while loops

Twice in your code, you have a while loop looking like this one:

int count = -1;
while(count++<length)

When you iterate this way, you usually see a for loop instead:

for(unsigned int count = 0 ; count < length ; ++count)

which does (almost) the same thing, but is more readable.

Note that the starting value is 0, leading into one less iteration than previously. However, it is actually the last iteration that is removed

Pass

In your main loop, you are using your pass macro. As jvb mentioned, you usually want to avoid to use macros (as the faq iso cpp says). Moreover, in this particular case, you may consider two alternatives:

Using the continue keyword
Reverting your condition

In this case, the second alternative is way better, as it is easy to put into place (the keyword continue shouldn't be used unless other alternatives are awkward).

if(adjacent_value > current_value) { continue; }
else if(current_value > adjacent_value) {
    // ...
}

would become

if(adjacent_value < current_value) {
    // ...
}

because you are really doing something only if the above condition is fulfilled

Swapping values

To swap your values, you are using your custom code

int tmp = adjacent_value;
unsorted[i+1] = current_value;
unsorted[i] = tmp;

which works well.

However, you may consider using the function std::swap, that swaps two values:

std::swap(unsorted[i], unsorted[i+1]);


Inserting a Java object into a MySQL database

If you don't have Java 8, here are a few things you can do.

Use a string builder instead of concatenating string together. Each time you concatenate to a string, a new string is created. Using a String builder is a more efficient way of doing the same thing.

 StringBuilder sb = new StringBuilder("INSERT into authorizations (");
 sb.append("another string");
 sb.append("another string");
 String query = sb.toString();

You can use String.join to generate a comma separated string of headers

    String headers = String.join(",", authorizationHeaders);
    sb.append(headers);

I'm not sure the best way to generate the list of question marks, but this is how I normally do it.

    sb.append( ") values(");
    boolean first = true;
    for(String header: authorizationHeaders) {
        if(first){
            sb.append("?");
            first= false;
        }else{
            sb.append("?,");
        }

    }
   sb.append(")");

When setting your parameters, using i++ instead of hardcoded numbers makes code maintenance easier. If you end up needing to add one more setString(), you can add the one line of code without having adjust the rest of the indexes

    int i=1;
    ps.setString(i++,  authorization.getCompany());
    ps.setString(i++,  authorization.getPromoType());
    ps.setString(i++,  authorization.getPromoDescription());
    ps.setString(i++,  authorization.getStartDate());
    ps.setString(i++,  authorization.getEndDate());
    ps.setString(i++,  authorization.getVlMarketingNum());
    ps.setString(i++,  authorization.getMarketingNum());
    ps.setString(i++,  authorization.getStatus());
    ps.setDouble(i++,  authorization.getForecast());
    ps.setDouble(i++, authorization.getActual());


If I understand it right, you would want IBehaviourA associated with property A, and IBehaviourB with property B.

If the above is right, could you try something like:

BehaviourQueueItem<T> AddBehaviour() where T : IBehaviour;

instead of

BehaviourQueueItem<IBehaviour> AddBehaviour<T>() where T : IBehaviour;

By this we can determine the object type at BehaviourQueueItem class level itself.


Computing the largest substring starting with a substring

Revise the sub for simplicity with only 2 parameters, reducing 1 char from both                                           end at 1 loop.

#!/usr/bin/python
import unittest
import sys
import os

def subSandwich_new(word, char):
    num = word.count(char)
    if num ==0:
        return 0
    elif num ==1:
        return len(char)
    else:
        # first string with length of char
        first = word[:len(char)]

        match = 0
        if first == char:
            match = match + 1
        else:
            # remove 1 char from word
            word = word[1:]
        # string from end with the length of char
        last = word[-len(char):]
        if last == char:
            match = match + 1
        else:
            # removing 1 char from word
            word = word[:-1]
        if match ==2:
            # first and last both match
            return len(word)
        else:
            return subSandwich_new(word, char)

class SandwichTestNew(unittest.TestCase):
    def test_subSandwich_new(self):
        result = subSandwich_new('catcowcat', 'cat')
        self.assertEqual(result, 9)

    def test_subSandwich_new2(self):
        result = subSandwich_new('catcowcat', 'cow')
        self.assertEqual(result, 3)

    def test_subSandwich_new3(self):
        result = subSandwich_new('ccatcowcatxx', 'cat')
        self.assertEqual(result, 9)

    def test_subSandwich_new4(self):
        result = subSandwich_new('cat', 'cat')
        self.assertEqual(result, 3)

    def test_subSandwich_new5(self):
        result = subSandwich_new('cat', 'cow')
        self.assertEqual(result, 0)


The \$n\$th triangular number is equal to \$n(n+1)/2\$, which can be factored as \$(n/2)(n+1)\$ or \$n((n+1)/2)\$ depending on whether \$n\$ is even or odd.  In either case the two factors are relatively prime, so the number of divisors can be computed as the product of the number of divisors of each factor, which is much faster to run through your getDivisors function.

There are also much more efficient ways to compute the number of divisors: sieving allows you to compute this over a contiguous range of \$n\$ values simultaneously much faster than doing each one individually.  Even for individual \$n\$, factoring-based methods will be tend to be faster than systematically trying all divisors up to \$\sqrt{n}\$.


The names of the function and parameters inner n current don't mean anything; I suggest testFactor num factor instead.  I'd also swap the two parameters so that the one that varies more (the candidate factor) appears last — this is a convention to facilitate currying.

Switching the order of the cases lets you avoid nesting conditions.

let largestPrimeFactor (number:int64) =
    let rec testFactor num factor =
        if factor * factor > num then
            num
        else if num % factor = 0L then
            testFactor (num / factor) factor
        else if factor = 2L then
            testFactor num 3L
        else
            testFactor num (factor + 2L)
    testFactor number 2L


Toby Speight's answer is correct for a normal singleton, but the class that you're replacing doesn't look like a normal singleton.

The original class appears to allow the user to explicitly define the object lifetime. The static variable is actually just for ease of access to that object:

The new code changes the point of construction to the first call to Instance().
The point of destruction is changed from reverse-order of construction inside the owning scope, to reverse-order of construction when C++ cleans up static variables.

This may or may not matter to your use case, but note that these two factors combined can completely alter the order of destruction of your "singleton" objects.

If you want to keep managing the object lifetimes explicitly, it might be better to use something like the Service Locator pattern instead (which is closer to what the original code does).

A related example from my own code (the shared / weak ptrs could be replaced with raw pointers or some sort of handle):

template<class T>
class Service
{
public:

    static void Provide(std::weak_ptr<T> service)
    {
        if (Service::service.lock())
            throw std::runtime_error("Service is already being provided!");

        Service::service = service;
    }

    static void Stop()
    {
        Service::service = std::weak_ptr<T>();
    }

    static T& Get()
    {
        auto strongService = service.lock();

        if (!strongService)
            throw std::runtime_error("Attempting to use a null service!");

        return *strongService;
    }

private:

    Service() = delete;

    static std::weak_ptr<T> service;
};

template<class T>
std::weak_ptr<T> Service<T>::service;


Split a big file into two and then merge back into the original

I would suggest, to get performance and still keep the original intact, that .net libraries are probably not the best choice.

One suggestion that would work, if you can allow smaller chunks(8GB), is 7-Zip.  It's free, open source and includes a file explorer.  It will split a 32GB file into 5 volumes in about 20 min.  Anyone with the same software installed can combine the volumes back again.  It even includes the option to calculate a checksum for the file to help confirm it's still the same file.


By looking at your code it appears to me that your basic problem is that isDailyRateRequired, isWeeklyRateRequired and isMonthlyRateRequired are distinct boolean variables instead of an enum.  If you just turned them all into an enum things would be a lot more simple, there would be no possibility of inconsistencies between their values, and you would not even have this multiple-choice issue.


Writing memory is s.l.o.w. - especially if writing less than the processor word/bus width.
Loop jamming has a chance to speed up things - from a distance, this is just a source code variant of the Streaming SIMD code hoffmale linked.

Instead of table lookup, one can turn LeastSignificantFirst bits in word to MSF bytes in u32 using bit manipulation - I failed to produce a readable variation taking full advantage of CHAR_BIT & co.:

leastBits = ((((1<<CHAR_BIT)+1 << CHAR_BIT)+1 << CHAR_BIT)+1);
bytes = (bits & 0xf) * ((((8<<CHAR_BIT)+4 << CHAR_BIT)+2 << CHAR_BIT)+1);
bytes = (bytes >> 3) & leastBits;
bytes = (bytes<<CHAR_BIT) - bytes;

should work like an evil spell, even extended to eight bytes.
The problem with LSF bits to MSF bytes and no less bits to convert than bits/byte is part products running into each other - use

bytes = (bits & 0xf | ((bits & 0xf0)<<32))*0x204081;

(and no >> 3(7)))

Warning tried out, but not even tested systematically.

const int NBFL = sizeof(float) * CHAR_BIT;

static void BitsToBytesImproved(benchmark::State& state) {
  // Code not measured
  float value = 1000.1234567;  // Params initialization
  unsigned char * buffer0 = new unsigned char[1024];
# define BASE_TYPE long
# define UNSIGNED_TYPE unsigned BASE_TYPE
# define UNSIGNED_SIZE sizeof(UNSIGNED_TYPE)
# define UNSIGNED_BIT  (1 << UNSIGNED_SIZE)
  UNSIGNED_TYPE bits = 0xff,
  *buffer = (UNSIGNED_TYPE *)buffer0,
  patterns[UNSIGNED_BIT] = { 0 };
 // set up pattern look-up table
  for (int done = 1 ; done < UNSIGNED_BIT ; bits <<= CHAR_BIT)
    for (int i = 0, next = 2*done ; done < next ; )
      patterns[done++] = patterns[i++] | bits;

  for (auto _ : state) { // this loop is measured repeatedly
    value += .1;            // to prevent static evaluation
    int fl = *(int*)&value;
    for (int i = 0 ; i < NBFL ; i += UNSIGNED_SIZE) {
      UNSIGNED_TYPE *pui = (UNSIGNED_TYPE *)(buffer0 + i);
      bits = patterns[fl & UNSIGNED_BIT-1];
      benchmark::DoNotOptimize(*pui = bits);
      fl >>= UNSIGNED_SIZE;
    }
  }
}

(Benchmark results have been too ticklish to the way I put the code for me to put much trust in them. FWIW, table look-up was reported faster than bit-bashing.)


Print character + the ASCII value, 10 pairs per line

A few issues, in no particular order:

put main last to avoid the need for a prototype.
main normally takes argc/argv parameters
special_chars should be static - but it is debateable whether a separate
function is necessary in a short program like this.
main defines variable x and passes it to special_chars.  This is
unnecessary. Just define ch in special_chars and define the function as
taking void (i.e. nothing)
why does special_chars return a value?
indenting is wrong
too many blank lines (8)
missing {} brackets after if (pairsNum == 10)
mixed naming styles (pairsNum should be pairs_num or special_chars should
be specialChars - I prefer the former)
special_chars is a bad name for the function.
pairsNum is an odd name; n_pairs would be my choice.
you don't print a final \n at the end of the program
you don't start a new line after reading a \n, as required - it appears that you do    when you type at the keyboard because entering a \n causes a new line. But if you redirect input into your program it
does not.  Also you don't start a line after each ten, only after the first ten. e.g. if your program executable is called program

$ cat x
abcdefgh
ijklmnop
qrstuvwxyz

$./program < x
please enter a some characters, and ctrl + d to quit
a,97 b,98 c,99 d,100 e,101 f,102 g,103 h,104 \n i,105
j,106 k,107 l,108 m,109 n,110 o,111 p,112 \n q,113 r,114 s,115 t,116 u,117 v,118 w,119 x,120 y,121 z,122 \n $


Trim files by removing bytes from the beginning in bash

Some suggestions
Get the byte size of a file
Instead of:
"$( wc -c < "$file_path" )"

use stat:
stat -c %s "$file_path"

=> better query the file system than count the number of bytes in files, some of which can be pretty large
Redirect or copy console output to a file
Instead of enclosing the whole block between brackets, I would set up file redirection from the beginning eg:
#!/bin/bash
LOG_FILE="/tmp/test.log"
exec > >(tee -a "${LOG_FILE}") 2>&1

# this should show on console AND in the log file
echo "Hello world $(date)"

based on this example
This is more flexible, because once it's set up you don't have to bother about appending your commands, and you can disable or redefine the behavior on the fly if desired.
And the benefit is that since we are redirecting both stdout and stderr, any errors will show up in the log file as well.
Misc
I think parsing the output of ls to count files in the directory is a bit primitive. Let me think but hopefully someone will come up with a better way.


Addition of two number using array of unequal size

Define an API

The first thing you should do is define a function to wrap the implementation.  This gives it a name and a defined interface.  You can then set expectations such as the first number is the largest, the caller needs to pre-allocate a buffer for the result, etc.

Naming

It would be easier to follow your code if i and j had more meaningful names.  num3 could be target_number or sum etc.

Unused variables

You define variables z and digi, but don't use them.  If you don't need them, get rid of them, they simply add unnecessary noise.

carry?

Do you really need your carry flag?  You could simply combine the code that sets it with the code that checks it:

if(num3[i+1]>9)
{
    num3[i+1]=num3[i+1]%10;
    num3[i]=1;
}

Bugs

Your code has two major issues.

As pointed out by @chux in the comments, if num1 has the same number or more digits than num2 your code skips the addition step and then accesses num3 to print it out.  This will probably crash because num3 hasn't been allocated.
If num1 has more digits than num2, you access a negative index of num2.  Once you pass the left side of the shortest number you should stop adding from it.


Custom concurrent stack implementation in Java

The synchronization you are currently using is not even working the way you intend to: as nothing else is synchronizing on this (like the sizeOf() method) you might as well not make the method synchronized.

You could stick a size field into your Node which gets set on inserting, something along the lines of this:

do {
    headNode = head.get();
    newHead.next = headNode;
    newHead.size = (headNode == null) ? 1 : headNode.size + 1;
} while (!head.compareAndSet(headNode, newHead));

This should allow reduction of the sizeOf() method to:

public int sizeOf() {
    return head.get().size;
}


Manual slide-in animation using delta time

The following makes the assumption  that all durations are totaled together (as duration) and should give a smoother animation. with a pause based on the original box width (presently height);

void OnGUI() {
    float progress = elapsedTime / duration;
    float leftPositon = progress * positionFromLeft - boxHeight;
    float width = (progress * (boxWidth + positionFromLeft)) - positionFromLeft;

    if (leftPositon > positionFromLeft){
        leftPositon = positionFromLeft;
    }

    if (width < boxHeight) {
        width = boxHeight;
    }
    else if ( width > boxWidth){
        width = boxWidth;
    }

    GUI.Box (
        new Rect (
            leftPositon,
            positionFromBottom,
            width,
            boxHeight
        ),
        boxString
    );
}


You mentioned OOP, and thats great, and OOP is all about code reusability and extensibility,and this code is a good example of a Candy Machine Interface. And that is, users of this class might do mistakes while using it. users could call the static the method getShortestPathTo before calling instance method computePaths and this would lead to wrong routes because weights weren't computed properly. You should try your best to force right behavior.
class RouteFinder{

   RouteFinder(Vertex source){
     computePaths(source);
   }
   private computePaths(Vertex source){
     //It is private,users dont need to know about this
   }

  public List<Vertex> getShortestPathTo(Vertex target){
    //..
   }
}

As you can see here no static methods anymore, static usually presents a global behavior, and I need to force users to go through the constructor so I make sure weights are computed properly.
I suppose that what you using is Dijkstra algorithm (not sure though), where your class name is RouteFinder, that's a bit misleading because Dijkstra is not the only algorithm and it doesn't work with negative weights, and you need something like Bellman-Ford for that.If you don't want to support negative weights for now, it is fine, but you should be able to add this functionality in the future.And this leads for extracting the Route finder to an interface
 interface RouteFinder{
   List<Vertex> shortestPath(Vertex target);
 }

 class Dijkstra implements RouteFinder{
   ...
 }

 class BellmanFord implements RouteFinder{
   ...
 }

And it would be great if you just expose the interface and keep concrete implementation with package access, a good API is a compact one. And for that you can have a static factory to get the right implementation
public static RouteFinder getInstance(Vertex source){
 if(hasNegativeWeight){
  return new BelmmanFord(source);
 }else{
  return new Dijkstra(source);
 }
}

One more thing, is it possible to have duplicated vertices on the same graph? I dont think so, and hence getShortestPathTo should return a Set of vertices rather than a List


Displaying fields in a sidebar of a custom page template

Your code can be simplified a bit.
The parantheses on the right side is not needed. Instead of

        $name = (get_field('name'));

you can just say

        $name = get_field('name');

However, since you are outputting the values directly, I'd use another approach for preparation. Collect all output strings in an array:

        $result = array();
        $result[] = get_field('name');
        $result[] = get_field('address');
        $result[] = get_field('company');
        $result[] = get_field('phone');
        $result[] = get_field('fax');
        $result[] = get_field('mobile');
        $result[] = mailTo(get_field('email'));
        $result[] = mailTo(get_field('second_email'));
        $result[] = linkTo(get_field('website'));
        $result[] = linkTo(get_field('facebook'), '');
        $result[] = linkTo(get_field('twitter'), '');
        $result[] = linkTo(get_field('linkedin'), '');

The functions mailTo and linkTo will build the links; I'll describe them later. The point is, that now you have a single array with all lines. Some of the lines will be empty, because no data was provided. You can filter those empty lines easily with

         $result = array_filter($result);

To show all the lines with a
 in between, you just implode the array into a single string and echo it:

         echo implode('
', $result);

Now your main functionality is done, and the only thing left is to put the formatting code, that you used repeatedly, into proper functions.

function mailTo($address)
{
    if (isValidEmailAddress($address)) {
        return printf('%1$s', $address);
    } else {
        return '';
    }
}

With this function, you have one single place, where the rendering of an email address is defined, so, if you want to change the appearance (eg. link it to a contact page instead of using mailto), you only have to that once.

Here a new function is introduced to check the validity of the email address. To keep it close to what your original code did, for now we'll only check if it is non-empty.

function isValidEmailAddress($address)
{
    $address = trim($address);
    return !empty($address);
}

You can of course add other validations to it.

The same has to be done to URLs.

function linkTo($url, $linkText = null)
{
    $url = trim($url);
    if (empty($url)) {
        return '';
    }

    if (is_null($linkText)) {
        $linkText = $url;
    }

    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = 'http://' . $url;
    }

    return sprintf('%2', $url, $linkText);
}

As you can see, putting repetitive code sequences into their own functions increases the readability of your code and make future changes easier.


Data structure (Map-like implementation) in C++

You should implement a private function find, that returns the index of a key

const int find(const int key) const
{
    for (unsigned i=0; i < pairs.size(); ++i)
    {
        if(pairs[i][0] == key )
        {
            return i;
        }
    }
    return -1;
}

This should simplify your functions considerably

const int size(const int key) const
{
    const int index = find(key);
    if (index == -1)
        return -1;
    return pairs[index].size() - 1;
}

const int* data(const int key) const
{
    const int index = find(key);

    if( index == -1 )
        return nullptr;
    return &pairs[index][1];
}

void insert(const int key, const int value)
{
    const int index = find(key);

    if( index != -1 )
    {
        pairs[index].push_back(value);
    }
    else
    {
        std::vector<int> v = {key, value};
        pairs.push_back(v);
    }
}

Generally i would strongly recommend to split keys and values. One possibility would be to create a std::pair

std::vector<std::pair<int, std::vector<int>>> pairs;

Otherwise you could split it into a map and a vector.


Consider using a Collection when matching values in multiple list.  Scripting Dictionaries are well suited for this task.  You'll need to create a Key by concatenate the multiple values with a delimiter.  You will then store the Key with its associated Cell reference  in the Dictionary.

This solution can be further optimized using array but should process 2 list with 10k entries each in seconds (less than a second if optimised using Arrays).

Sub CompareLists()
    Dim cell As Object, dic As Object, key As String
    Set dic = CreateObject("Scripting.Dictionary")

    With ActiveWorkbook.Worksheets("Approved Master")
        For Each cell In .Range("E1" & .Range("E" & .Rows.count).End(xlUp))
            key = cell.Value & "|" & cell.Offset(0, 1).Value
            If Not dic.Exists(key) Then dic.Add key, cell
        Next
    End With

    With ActiveWorkbook.Worksheets("Manifest")
        For Each cell In .Range("B2" & .Range("A" & .Rows.count).End(xlUp))
            key = cell.Value & "|" & cell.Offset(0, 1).Value
            If dic.Exists(key) Then dic.Add key, cell.Offset(0, 2).Value = dic(key).Offset(0, -2).Value
        Next
    End With

End Sub

Here is a good reference to learn how to use Scripting Dictionaries: Excel VBA Introduction Part 39 - Dictionaries.


find matches between attributes from two different Objects

First off, a bug (or probably just a copy/paste error): countMatches is comparing age instead of eye color.
Then, any reason you are limited to Java 8? At the very least you should be using the LTS release 11, or better the current release 15.
Also, you have some minor formatting issues that don't confirm with standard Java conventions. Mostly it's wrong spacing: there should be spaces before { and between keywords (e.g. if) and (, but no spaces between method names and (.
Lombok
The annotations on the data classes could be most likely simplified to @Data @AllArgsConstructor. And you should even consider using @Value instead for immutable objects when ever possible, which can help avoiding bugs.
Spring DI
Generally autowiring private properties has been discouraged. You should prefer constructor injection. With Lombok's @RequiredArgsConstructor it becomes quite easy:
@Service
RequiredArgsConstructor
public class UserServiceImpl implements UserService{

    private final UserRepository userRepository;

    private final UserFilters userFilters;

    //....
}

Since you are injecting UserFilters it shouldn't be static i.e. @UtilityClass.
For a matter of fact I don't see why UserFilters is a separate class at all. Those methods don't look like they should be used outside of UserService, so they should belong as (private) methods in UserService.
Method UserServiceImpl.getMostMatchingUserId
The name isn't quite right and doesn't give enough information in my opinion. It's not a "getter", so it should be called find... and nt get..., the meaning "Most matching" needs to be defined in a comment and the word "youngest" needs to be added.
Also it seems quite limiting to have the method return just the user ID.
One problem in here is the use of orElse on the result of min(). min() only returns an empty Optional, if the stream is empty, so in that case .get(0) will throw an exception.
A final though here, is that normally one would expect that the repository (or usually the database behind it) should filter the list of results. If the database would do the filtering, then this would scale better with more users.
Method UserFilters.getMostMatchingUserList
Also not a "getter". filter... would be the most appropriate prefix here.
One could consider using a stream here, however in this specific case I don't think it would make the task much simpler/better to read. The only change I'd make here would be choose some better variable names: newUserList should be called filteredUserList and matchesInitialCount should be currentMatchesCount.
Method UserFilters.countMatches
This implementation is fine. Personally I'd leave it like this, and just add/change more property checks when needed, unless the list of properties needs to changed quickly or easily, for example, via configuration. It that case you need to work with reflection to find the properties.


Filtering (search) a model with multiple params in hash

Have you looked into using a pre existing gem for this? I found one called has_scope that seems like it might do exactly what you're trying to refactor. You would need to add a scope for each of your filters and then add some has_scope calls in your controller.

Here's a few examples. I'm not as familiar with Rails 3 scopes as I am with 2, so the code likely won't work as is.

Model:

class Profile < ActiveRecord::Base
  scope :country, lambda {|country| where(:country => country) }
  scope :keyword, lambda {|keyword| where(["keyword LIKE :term", {:term => "%#{keyword}%"}]) }
  scope :driver, where{:driver => true)
end

Controller:

class ProfileController < ApplicationController
  has_scope :country
  has_scope :keyword
  has_scope :driver, :type => :boolean
end


Renaming video files based on episode title lookup

Looks good; there's nothing I'd really do differently. Good structure, no overly imperative code, appropriate use of pipes (including not piping for calling a single function with a single argument, which many people do, but I think reduces readability), pattern matching, even Active Patterns. Nice use of a type provider with a web data source too.

Two very minor things:

You don't need new when calling a constructor; the compiler only recommends it when creating an instance implementing IDisposable. (I'm very happy about not needing new, because I find it terribly annoying and redundant in C#.)
I've recently started either putting if-then-else on a single line if short enough, or giving the then part its own line as well because that better represents the structure of the construct.


As far as security goes, rather than just using "AES" for your algorithm, from the documentation:

  Every implementation of the Java platform is required to support the
  following standard Cipher transformations with the keysizes in
  parentheses:

  AES/CBC/NoPadding (128)
  AES/CBC/PKCS5Padding (128)
  AES/ECB/NoPadding (128)
  AES/ECB/PKCS5Padding (128)
  AES/GCM/NoPadding (128)
  DES/CBC/NoPadding (56)
  DES/CBC/PKCS5Padding (56)
  DES/ECB/NoPadding (56)
  DES/ECB/PKCS5Padding (56)
  DESede/CBC/NoPadding (168)
  DESede/CBC/PKCS5Padding (168)
  DESede/ECB/NoPadding (168)
  DESede/ECB/PKCS5Padding (168)
  RSA/ECB/PKCS1Padding (1024, 2048)
  RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048)
  RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)

Likewise, here's more documentation on the subject of what is supported.

If you're unsure which one to choose, this answer will shed some light. Here's the summary:

  In general, stick with CBC or CTR, with PKCS#7 where necessary (you don't need padding on stream cipher modes) and use an authenticity check (HMAC-SHA256 for example) on the ciphertext. Both CBC and CTR come recommended by Niels Ferguson and Bruce Schneier, both of whom are respected cryptographers.

What's the difference between PKCS5 and PKCS7?

  ... fundamentally PKCS#5 padding is a subset of PKCS#7 padding for 8 byte block sizes. Hence, PKCS#5 padding can not be used for AES ...

  Some cryptographic libraries such as the SUN provider in Java indicate PKCS#5 where PKCS#7 should be used - "PKCS5Padding" should have been "PKCS7Padding". This is a legacy from the time that only 8 byte block ciphers such as (triple) DES symmetric cipher were available.

However, that doesn't stop you from using PKCS#5 with AES.

Given the answers to the question linked above, I would suggest using the following:

"AES/CBC/PKCS5Padding"

After that, reading erikson's answer will tell you most of what you need to know about how to write this code in a relatively secure manner.


Just a few things I noticed.

Utilize built in functions

This

S = 0
for k in range(1, N):
    S += function[a + k * h]

can be this

S = sum(function[a + k * h] for k in range(1, N))

Python3's sum takes an iterable, and returns the sum of all the values in that iterable. So, you can pass in the for loop and it will return the sum for you. Looks neater, too.

Operator Spacing

There should be a space before and after every operator and equal sign. Here's an example from your code:

d = 1/2 * h * (function[a + k*h] + function[a + (k+1) * h])

This should be

d = 1/2 * h * (function[a + k * h] + function[a + (k + 1) * h])

Spacing just helps you and other programmers read your code.

This, however, doesn't apply when passing default parameters. Have a look:

plot(time, distance, "g--", label = "position") # WRONG
plot(time, distance, "g--", label="position") # RIGHT

Variable Naming

A lot of single character variable names can confuse you, and make a program hard to read. I see you have comments such as #x_initial and #x_final. Why not use those as variable names? They're a lot more concise than a and b. h can also be something like diff.


Move Semantics

One of the rules you have to remember is:
A named variable will not bind to an r-value ref parameter.

void doMoreStuff(Type const& x) {std::cerr << "Normal Reference\n";}
void doMoreStuff(Type&& x)      {std::cerr << "RValue Reference\n";}
void doStuff(Type&& x)
{
    doMoreStuff(x); // Here you are using a named variable
}                   // So this will not bind to an r-value ref.
                    // So it will call the top version above.
                    // The `&&` just mark the bind point they
                    // don't change the type of the variable in
                    // any special way.

So your Move Constructor does not do what you think it is doing.

  Stack(Stack<T> &&other) {
    *this = other;  // You are using a named variable.
  }                 // So this will bind to the "Copy Assignment"

To make it work the way you think, you need to use std::move:

  Stack(Stack<T> &&other) {
    *this = std::move(other);
  }

Copy And Swap Idiom

You are implementing the Constructors in terms of Assignment. I suppose it's not wrong. But it is very non-standard. Usually it is done the other way around - implement Assignment in terms of the Constructor (it even has a name: The Copy and Swap Idiom).

  Type& operator=(Type const& rhs)
  {
       Type copy(rhs);    // Make a copy of the rhs.
       swap(copy);        // Swap the content of this and copy
       return *this;
  }

This can even be simplified. You can remove the explicit copy and use an implicit copy by taking the parameter by value:

  Type& operator=(Type copy)
  {
       swap(copy);        // Swap the content of this and copy
       return *this;
  }

Move by swap

The simplest way to implement a move is to use swap. You swap the content of the current object with the source object. The great thing about this is move semantics are supposed by exception safe as is swap. This also has the advantage of delayed destruction (the destruction of the object is delayed until the source object is destroyed; this gives an opportunity for the resources to be re-used).

So two things wrong with your move are that you forgot to mark them noexcept and, as mentioned above, you don't actually move because you use the named parameter.

Type(Type&& rhs) noexcept
   : member(default init)
   , ....
{
    swap(rhs);
}
Type& operator=(Type&& rhs) noexcept
{
    swap(ths);
    return *this;
}
void swap(Type& other) noexcept)
{
    using std::swap;
    swap(member,  other.member);
    ...
}
friend void swap(Type& lhs, Type& rhs) {
    lhs.swap(rhs);
}

Rule of Zero

If all the members already obey the rule of three/five and you don't have any special resource management to do in your class, then the rule of zero springs into effect.

The rule of zero means you don't need to define any constructors/assignment/destructors as the default compiler-generated versions will work perfectly for you.

Since your only data member is storage and this is a std::vector, then you are covered because std::vector obeys the rule of three and does all the correct resource management for you. So you don't need to specify any of the copy or move constructors as the compiler will correctly generate them for you.

Premature Optimization (is actually a pessimization)

This test

if (this != &rhs)
  storage = rhs.storage;

actually decreases performance in normal circumstances (I can't claim it always makes things worse but it usually does). You see, the problem is that self assignment is extremely rare (your code needs to work for it, but in reality it hardly happens).

This means you are adding a branch into your code (one of the worst things to do for optimizations) that is basically never taken. So you have to execute this test even though it is never taken. So you make the normal code path longer and it has a branch.

Now it does pay off if you do self assignment. But if you multiply the cost of checking the branch by the number of times per actual self assignment then subtract the cost of an extra copy then on average you are taking longer (thus a pessimization).

The normal way to implement assignment using the copy and swap always does a copy even though this is hideously more expensive on self assignment than it needs to be and it still pays off for normal usage of strings and vectors.

Pushing Efficiently

You sort of half do it.

void push(T item) noexcept {           // You make a copy of the parameter.
    storage.push_back(std::move(item));// Then you move the copy.
}

But what happens if I want to move an item into the stack? It could be more efficient than making a copy of it first. Also if you are going to copy delay the copy until the end.

// A moving push
void push(T&& item) noexcept {
    storage.push_back(std::move(item));
}
// A copy push
void push(T const& item) noexcept {
    storage.push_back(item);
}

The third choice we have is to build an item in place. Some large types may be easier to create in-place on the stack rather than pushing or moving them (say the constructor takes a single integer but creates a huge object that is expensive to create or move).

template<typename... P>  // template var arg (can be many parameters.
void push(P&&... args) {
    storage.emplace_back(std::forward<P>(args)...);
}

Top efficiency

When you call top() you always make a copy of the top item. But what about when you want to mutate the top item. Do you have to call item = top();pop();/*modify item*/;push(item) to mutate the top item?

Also it means you have to construct an object externally (a empty object) before you can copy into it. Not all types can have an empty object. Not all types are cheap to construct. Additionally copying the item from the stack may be expensive. So this is not a desirable interface.

I would suggest you simply return a reference to the top item. That way it can be mutated in place or if the user wants they can make a copy by assigning to a local variable.

This does mean that your top() can not return true/false on successes but I would suggest that should be its own function to test for empty anyway.

bool empty() const   {return storage.empty();}
T&       top()       {return storage.back();}
T const& top() const {return storage.back();}

Notice I don't even check to see if there is an item. This is because the calling code can check with a call to empty(). The reason is I don't want to check if there is no need to check and if there is a need to check then the user can call empty(). If you need a checked version then you can add a specific checked version.

This is exactly why most C++ containers have checked and unchecked version of the interface. You should not need to force a check (as that will be inefficient).

while(!stack.empty())
{
    std::cout << stack.top() << ",";   // No need to copy if I am printing.
    stack.pop();  // Should not force a check in pop.
                  // We already know from context there is an item in
                  // the stack.
}

Your original code would have looked like this:

T  tmp;                        // You have to build a tmp object.
                               // Is this expensive?
while(stack.top(tmp))          // Check here.
{
    std::cout << tmp << ", ";
    stack.pop();               // Another check here. Even though
                               // we know the stack is not empty at
                               // this point.
}

Some minor notes:

Usually user types and namespace begin with an upper case letter, while objects and functions begin with a lower case letter.

This makes user types easier to spot.

 Stack::Stack<Int>  aStack;

Also the type modifiers * and & are part of the type. So in C++ (unlike C) they are usually grouped with the type not the variable.

Stack(const Stack<T> &other)
// More normally written like:
Stack(const Stack<T>& other)
// Or like this:
Stack(Stack<T> const& other)

The standard comment

Please avoid using namespace X;

using namespace stack;

This is really bad idea and will get you into a lot of trouble in larger code bases. So it is best not to get into the habit of this. Prefer to always prefix your types with the namespace.

stack::Stack<Int>   aStack;

If you have an exceedingly long (or nested namespace) you can use a namespace alias to simplify it (I usually use short three letter aliases).

namespace TSt = ThorsAnvil::Stack;

TSt::Stack<Int>     aStack;

See Why is “using namespace std” considered bad practice?.
Best Answer

Using Rule of zero to rewrite:

namespace stack {

// Exception safe moveable stack.
// No constructors or detructors are needed as the members
// do all the work correctly.
template <typename T>
class Stack {
private:
  std::vector<T> storage;

public:

  bool empty()   const noexcept {return storage.empty();}
  T const& top() const noexcept { // still no exception looking at object is safe
      return storage.back();      // will not cause an exception.
  }                               // It may be undefined if you top an empty stack.
  T&       top()       noexcept {
      return storage.back();
  }

  void push(T const& item) {     // Adding an item is not exception safe.
      storage.push_back(item);   // As adding an item to a vector may
  }                              // cause reallocation.
  void push(T&& item) {
      storage.push_back(std::move(item));
  }

  void pop() noexcept {
      storage.pop_back();
  }
};


Some your variable naming could be clearer. pad seems to be for padding, but it's a bit unclear that you're using it to format printing calls. Aside from a different name (padding at least) you could improve this by using the naming convention of constants. Python's naming convention for constants is to use UPPER_SNAKE_CASE, ie. PADDING. It signals that this is a constant value that you wont be changing. As @alexwlchan noted, non constants (including functions) are lower_snake_case and classes are in PascalCase. Aside from that, sInput, eOutput, pA, pB. Using words is more verbose but it's going to communicate much more than short codes. Even if they seem clear to you, you can't be sure people will correctly interpret what word they're stand ins for.

You could also improve clarity by adding docstrings that explain what each of your functions do. GetAIOutput is a short simple function, but explaining it's usage is still good to remove ambiguity.

def ai_choice():
    """Returns a random int from 1 - 3 as the AI's choice."""

    return random.randint(1, 3)

A docstring simply explains what a function does, how it works, how you should use it. They've very helpful for understanding functions. For an even more useful one, consider your clear screen function. As clear as the name is, it doesn't fully explain it's need:

def clear_screen():
    """Calls the relevant clear screen command from the user's OS."""

os.system('cls' if os.name=='nt' else 'clear')

In general, I think you have your functions too split up. Is there any need to have GetResult and UpdateStats as separate functions? Wouldn't it be easier to get the result, update stats from that and then print the result message all in one function. Generally functions should have one 'job', but that's different to performing just a single operation. The two above functions make sense as single functions. But sometimes multiple related operations are worth combining into one function. Specifically the game's results, particularly if there's no reason you'd want to call the component parts separately.

Lastly your commenting in the StartRPSGame doesn't give your good function names enough credit

    # Clear the screen
    ClearScreen()
    # Display the intro
    DisplayIntro()
    # Get user input
    uInput = GetInput()

All of those are perfectly clear without comments. Your concise names tell me the basics about the function, so why double it up with a comment saying practically the same thing? (using mostly the same words too).


Unity3d class that inherits from button and add OnHold Event

There is a few thing you can improve :

TimeMax is used like a constant here, but is not given the access modifier const.
Try to group your class members in a meaningful way. It could depend on their function(member of same interface), access-modifier, or what makes sense to you.

public ButtonHoldEvent onHold { get; set; }

private static float TimeMax = 2;

private bool isBeingPressed;
private float currTime;
private bool startTimer;

The name currTime doesn't reflect what it contains. heldDuration is more appropriate. The same applies for TimeMax and should be renamed TriggerTime.
isPressed is fine, but isHeldDown fits more the theme here.

Full code :

[AddComponentMenu("UI/Hold Button")]
public class HoldButton : Button
{
    public ButtonHoldEvent onHold { get; set; }

    private const float TriggerTime = 2;

    private bool isHeldDown;
    private float heldDuration;

    public override void OnPointerDown(PointerEventData eventData)
    {
        isHeldDown = true;
        heldDuration = 0;
    }
    public override void OnPointerUp(PointerEventData eventData)
    {
        isHeldDown = false;
        heldDuration = 0;
    }

    void Update()
    {
        if (!isHeldDown)
        {
            heldDuration += Time.deltaTime;

            if (heldDuration >= TriggerTime)
            {
                onHold.Invoke();

                // uncomment next line, to make `onHold` trigger only once per mouse press-hold
                //isHeldDown = false;
            }
        }
    }

    public class ButtonHoldEvent : UnityEvent
    {
        public ButtonHoldEvent() : base()
        {

        }
    }
}


Cross-post from SO-  Palindrome finding function

Reading a file:

while(fin){

    fin >> str;
    sWords.push_back(str);
    if(!fin){
        break;
    }

You push the value str before checking it worked. It should be:

while(fin)
{
    fin >> str;
    if(!fin){
        break;
    }
    sWords.push_back(str);

Or even better would be:

while(fin >> str)
{
    sWords.push_back(str);

Why are you doing this:

    else{
        getline(fin, str);
    }

Mixing operator >> and getline() makes the code hard to read.
Either use all operator >> or use getline() to get a line at a time then parse the line internally.

Note:: operator>> will ignore the '\n' at the end of the line and work. So if your file is a list of words one per line there is no need to use getline(). If on the other hand your file is a lot of text and you only want the first word on each line then you need to use getline().

Method 1: Use operator>>

 // If your input file has one word per line (or you want to use all words)
 while(file >> word)
 {
      // Do stuff
 }

Method 1: Use getline()

 // If your input file contains lots of words
 // But you only want to use the first word on each line
 while(std::getline(file, line))
 {
     std::stringstream  linestream(line);
     linestream >> word;

     // Do stuff
 }

You seem to reversing the line just to print it:

reverse(sVec.begin(), sVec.end());
for(int i =0; i < sVec.size(); i++){
    cout << sVec[i] << " is a Palindrome " <<endl;
}

Rather than reversing the array, just iterate it in reverse order:

for(std::vector<std::string>::const_iterator& loop = sVec.rbegin(); loop != sVec.rend(); ++ loop)
{
    cout << (*loop) << " is a Palindrome " <<endl;
}

Note on efficiency:

Using push_back() on an vector can be in-effecient if you are pushing a lot of data. As evertime the vector runs out of space it must allocate more memory and copy the string to the new buffer. You help by pre-allocting space.

sVec.reserve(1000); // Guess at the size
                    // Note when the vector runs out of space it will approximately
                    // double its internal buffer.


I am not well versed in coding node.js as I'd like to be (I can read and debug, but learning to program in it is still ongoing) and I did not see anything that said I could not present an answer using a compatible language, so I converted your code into SmartBASIC.

If you were expecting node.js code, I will understand. I needed a quick way to show you several areas where you can improve on your own program, and suggestions that will smarten your program's AI. For yes, SIRI seems to be human like, it is not perfect. And it is harder to have a computer write something in one of the arts, whether a poem, lyrics or even a short story.

I did notice one slight error. In the statement below, you have a period instead of a comma, which will get you strange errors (had been.will be):

var lv = "was,had been.will be,could be,might be,should have been,would have ...

I experimented with several ideas, and several show promise. I incorporated them in my SmartBASIC program, which I commented thoroughly.

Your dictionary is limited, but I found out that this is not always a bad thing. I experimented with nouns, verbs, adjectives and articles where I created several hundred in each, and while it was still hit or miss, it was more miss than yours hit. Quantity does not always equate to quality.

One of the problems I noticed is when you want to use a color. Rarely does a color stand alone, nor does it always work with every word. A "white beard" is fine, but what is a "white crash?"

But a white crash can be poetic if the theme is right. That later.

So with colors, I created in my table colors with modifier tags. These are color words with a tag at the end so the program knows that another word is needed after a color word is used.

Here is a sample DATA statement that you should be able to convert to a "VAR[" Table:

DATA "*beard","fool","white*","black*","green*","blue*","yellow*","red*","light beams","*river","*garment","*ship","*snake","*snakes","*sails","voice+","ship+","ocean blue"

What you want to look at are the words with an "" in front of or at the end. The "" is my token that color is involved, and a modifier is needed.

If the "" is before the word, then I need to add a color before it. If the "" is after the word, then it is a color word and it needs a modifier.

I also created a table of colors only for the times I need to add a color to the front of a word. The word can be a noun or a verb. "White lightning," depending on how it is used, can be a noun or a verb. If you said "White lighning struck a tree," it is a noun. "Dear ole Fred, lay dead, when met by white lightning" could be considered a verb/adverb use.

The second thing is the "+" modifier. In the same DATA statement, the word "voice+" means it needs a modifier after it. I created a specific table for this type of modifier.

You will see in my code that since I used a random generator to start either with an article or verb, every word is in or converted to lowercase. I had to create another modifier, "@" that is placed in front of proper nouns or words that must be capitalized, no matter where in the sentence they appear. @moon and @sun are two examples in my DATA statements.

The third thing that shows promise is to create files that you can read into your VAR tables, but with a twist. I am currently creating theme-based poems. So I created files with words that are used in a particular theme.

For example, "hope" is one of the themes I am developing, so I am using everything from other poets to a thesaurus to even the Bible to gather as many words, Articles, Nouns, Verbs, Adjectives, and Modifiers that fit the theme of "hope" along with some generic words that would work.

This is where you asked if it would be better to have .CSV instead of tables. It will add flexibility to what your computer program writes about. You would have a VAR table with just themes, and .CSV file names for each theme that holds your vocabulary for that theme. You would first randomly pick a theme, load your tables, then can randomly pick your words.

By moving your tables out to .CSV files, you allow for many different types of dictionaries. And you can even get as complex as having a main theme and a sub-theme and load the appropriate dictionaries.

Another improvement I demonstrated in my code is that sentence structure does not always have to be article-noun-verb-adjective. It doesn't even have to always be subject-noun-verb or noun-verb-subject. Try starting one of your lines with a verb instead of an article. Then you can use verb-noun-subject or even article-verb-noun-adjective.

For example, "Stepping on Mike's foot felt great" shows how a verb can start a sentence.

I mentioned subject. For now, you can use nouns, but you may want to eventually create another table with just items that are considered "subjects." "Science" is a subject. "A Dear John letter" can be a subject rather than a noun. A "Divorce" can also be a subject.

I tried to keep to the same logic you used, but I wrote as vanilla a BASIC program as I possibly could so those with other dialects need to change very little. Like statement separator (!) or some of the statements for lower and upper-case. With minimal changes, I had this working in techBASIC.

But Javascript, being a C-based language, there are enough similarities to BASIC that you should have no problems adapting the routines in my code below into your program.

Not a plug, but incase there are those who never heard of SmartBASIC, it is an app (less than $5 in iTunes) that runs a pretty robust BASIC dialect on iPad and iPhones, and comes with the ability to create Xcode apps for distribution on iTunes. You also do not need access to the internet to run and test your programs.

This code works when run in SmartBASIC and is not broken code.

Here is it with the changes I made (commented):

/*
Poem Generator
By George McGinn (Poems by SmartBASIC)

Program uses very little AI in the beginning as once I have all the
word pieces in place, the AI will then determine if a word needs a
qualifier before or after it.

As this program grows, so will its AI, and the next phase will have it
learning words, for example, if it chooses a "A" and the next word
begins with a vowel, it will correct the "a" to an "an", thus its start
of learning grammar.

UPGRADES/BUG FIXES:
v1.0 - March 1, 2017
    Translation from simple NODE.js program
    Initial logic with limited vocabulary

v1.5 - March 4, 2017 (Minor upgrade - only because this was also v1 updates)
    Improved vocabulary by adding:
       17+ Articles
       31+ Nouns/Subjects
       35+ Verbs/Adverbs
       15+ Adjectives
       28+ Color Modifiers (new)
    Randomize start (Article or Verb)
    Improved AI to now include:
       – Capitalization at start of line
       – Created word capitalization modifier tag
       – Added Color Table for words needing a color before it
       – Added additional word and new color modifier table
       – Added Noun modifier table for before and after tagged noun
    The AI can now do rudimentary word enhancement by addind modifiers
    from specialized tables, including colors and added nouns, verbs,
    and adjectives before or after a noun. It is capable of recognizing
    words that require capitalization. However, the title still does
    not work right
*/

OPTION BASE 1
RANDOMIZE

REM Initialize variables/arrays (comments to prevent confusion)

x=0                                            REM Index to poem length (# lines)
i=0                                            REM Index to loading Arrays
cr$=CHR$(10)                                   REM Add a Carriage-Return character
Author$ = "By George McGinn"                   REM Name of Programmer running code
DIM article$(35),noun$(60),verb$(46),adjective$(45)
DIM colormodifier$(28),colortable$(7),nounmodifiers$(14)

REM Load Arrays from Data Statements

GOSUB LoadWordArrays

REM Pick a 2-word title

ta$ = article$(RND (35)+1)
b$=LOWSTR$(noun$(RND(60)+1))
b1$=LOWSTR$(noun$(RND(60)+1))
IF LEFT$(b$,1)="@"  OR LEFT$(b1$,1)="@" THEN GOSUB CheckForCapitalization
IF RIGHT$(b$,1)="*" OR RIGHT$(b$,1)="+" THEN GOSUB CheckForModifierAfter
IF LEFT$(b$,1)="*"  OR LEFT$(b$,1)="+"  THEN GOSUB CheckForModifierBefore
tb$=b$

Title$ = ta$ & " " & tb$

REM Create the poem, 16 lines in 4 4-line stanzas

PRINT Title$
PRINT Author$
PRINT!PRINT

REM NOTE: b1 & c1 placeholders for future use as modifiers, or
REM       to initially use b1 & c1 as modifiers themselves.
FOR X=1 TO 16
    a$=LOWSTR$(article$(RND(35)+1))             REM Pick an Article
    b$=LOWSTR$(noun$(RND(60)+1))                REM Pick a primary noun
    b1$=LOWSTR$(noun$(RND(60)+1))               REM Pick a noun-color modifier
    c$=LOWSTR$(verb$(RND(46)+1))                REM Pick a primary verb
    c1$=LOWSTR$(verb$(RND(46)+1))               REM Pick a verb modifier
    d$=LOWSTR$(adjective$(RND(45)+1))           REM Pick an adjective
    bc$=LOWSTR$(colormodifier$(RND(28)+1))      REM Pick a modifier for a color
    color$=LOWSTR$(colortable$(RND(7)+1))       REM Pick a color as a modifier
    nounmod$=LOWSTR$(nounmodifiers$(RND(14)+1)) REM Pick a non-color noun modifier

REM Check for modifiers to nouns
    IF LEFT$(b$,1)="@"  OR LEFT$(b1$,1)="@" OR LEFT$(bc$,1)="@" THEN GOSUB CheckForCapitalization
    IF LEFT$(b$,1)="*"  OR LEFT$(b$,1)="+"  THEN GOSUB CheckForModifierBefore
    IF RIGHT$(b$,1)="*" OR RIGHT$(b$,1)="+" THEN GOSUB CheckForModifierAfter

 REM Capitalize the first word of each sentence or stanza (whether noun or verb)
REM r=whether or not the sentence will start with a verb or article
    r=RND(2)+1
    IF r=1 THEN
       z=LEN(a$)
       a$=CAPSTR$(LEFT$(a$,1)) & RIGHT$(a$,z-1)
       Line$=a$ & " " & b$ & " " & c$ & " " & d$
    ELSE
       z=LEN(c$)
       c$=CAPSTR$(LEFT$(c$,1)) & RIGHT$(c$,z-1)
       Line$=c$ & " " & b$ & " " & d$
    ENDIF
    IF X%4=0 THEN Line$=Line$ & "." & cr$
    PRINT Line$
NEXT X

endPROG:
   PRINT!PRINT!PRINT "© 2017 "&Author$&" (if it is good), All Rights Reserved"
   PRINT "Date/Time Stamp: "&CURRENT_MONTH ()&"/"&CURRENT_DATE ()&"/"&CURRENT_YEAR ()&" at "&CURRENT_HOUR()&":"&CURRENT_MINUTE()&":"&CURRENT_SECOND()
   END

REM FUNCTIONS, SUBROUTINES, LABELED DATA STATEMENTS
REM ***********************************************

LoadWordArrays:
REM ***********************************************
REM Load Arrays from Data Statements

REM Load Articles
    For i=1 TO 35!READ article$(i)!NEXT i
REM Load Nouns
    FOR i=1 TO 59!READ noun$(i)!NEXT i
REM Load Verbs
    FOR i=1 TO 46!READ verb$(i)!NEXT i
REM Load Adjectives
    FOR i=1 TO 45!READ adjective$(i)!NEXT i
REM Load Color Modifiers
    FOR i=1 TO 28!READ colormodifier$(i)!NEXT i
REM Load Color Table
    FOR i=1 to 7!READ colortable$(i)!NEXT i
REM Load Noun Modifiers
    FOR i=1 to 14!READ nounmodifiers$(i)!NEXT i
RETURN

CheckForCapitalization:
REM Check for modifiers (@=Capitalize Word)
IF LEFT$(b$,1)="@" THEN
   z=LEN(b$)
   b$=RIGHT$(b$,z-1)
   b$=CAPSTR$(LEFT$(b$,1)) & RIGHT$(b$,z-2)
ENDIF
IF LEFT$(b1$,1)="@" THEN
   z=LEN(b1$)
   b1$=RIGHT$(b1$,z-1)
   b1$=CAPSTR$(LEFT$(b1$,1)) & RIGHT$(b1$,z-2)
ENDIF
IF LEFT$(bc$,1)="@" THEN
   z=LEN(bc$)
   bc$=RIGHT$(bc$,z-1)
   bc$=CAPSTR$(LEFT$(bc$,1)) & RIGHT$(bc$,z-2)
ENDIF

RETURN

CheckForModifierBefore:
REM Check for modifiers Before

REM "*" the noun needs a color before it
IF LEFT$(b$,1)="*" THEN
   z=LEN(b$)
   b$=RIGHT$(b$,z-1)
   b$=color$ & " " & b$
ENDIF

REM "+" the noun needs another noun to follow it (selection from noun modifier)
IF RIGHT$(b$,1)="+" THEN
   z=LEN(b$)
   b$=LEFT$(b$,z-1)
   b$=nounmod$ & " " & b$
ENDIF

RETURN

CheckForModifierAfter:
REM Check for modifiers after

REM "*" the noun is a color only color-friendly nouns considered
IF RIGHT$(b$,1)="*" THEN
   z=LEN(b$)
   b$=LEFT$(b$,z-1)
   b$=b$ & " " & bc$
ENDIF

REM "+" the noun needs another noun to follow it (selection from noun modifier)
IF RIGHT$(b$,1)="+" THEN
   z=LEN(b$)
   b$=LEFT$(b$,z-1)
   b$=b$ & " " & nounmod$
ENDIF

RETURN

REM DATA Statements for Poem Generator

REM 35 Articles
articles:
DATA "The","All of the","Most of the","Some of the"
DATA "My","Your","His","Her","Their","Our","Everybody's","Almost all of the"
DATA "That","I knew that the","We knew that the","She knew that the","He knew that the","They knew that the","And the coming","Oh, the","A spring of","Beyond the","Within the","And the","Alone, alone,","I fear","I looked upon","A","But where the","Like","A still and","Alone","All alone, a","The moving","It is"

REM 60 Nouns
nouns:
DATA "darkness","morning","morning+","light","feeling","feeling+","beauty","love","hatred","happiness","sadness","anger","frustration","expression","message","ship","lips","mouth","voice","garment","saint","snake","snakes","water","fire","lead","dreams","air","ghost","sails","sleep","river","cloud","@moon","@sun","waters","life","stars","the stars","lightning","beams","beams+","*beard","fool","white*","black*","green*","blue*","yellow*","red*","light beams","*river","*garment","*ship","*snake","*snakes","*sails","voice+","ship+","ocean blue"

REM 46 Verbs (lv)
verbs:
DATA "was","had been","will be","could be","might be","should have been","would have been","could have been","drunk","drank","lite","heavy","blessed","glossy","velvet","flash","kind","coiled","swarm","swarmed","fire","pity","filled","fill","moved","wind","danced","steep","wide","steep and wide","thick","light","roar","loud","more loud","lightning","struck","fell","more horrible","horrible","awful","hit","huge","holds","long","surrounds"

REM 45 Adjectives
adjectives:
DATA "abstract","mysterious","permanent","unfortunate","was unfortunate"
DATA "intricate","confusing","serene","confusing"
DATA "true","false","fake","a lie"
DATA "a stranger","a friend","an enemy"
DATA "terrible","enchanting","is mine","was yours","is his","is hers","was theirs","was ours"
DATA "fortunate","was understood","mine","interesting","is mutual","with an artistic flair","was musical"
DATA "golden pond","glossy lake","blessed","moment","unaware","no","yes","sure"
DATA "like","dreams","between","inbetween","alone","than that"

REM 28 Color modifiers
colormodifiers:
DATA "morning","light","beauty","love","ship","lips","garment","knight","saint","snake","snakes","water","fire","ghost","sails","river","cloud","@moon","@sun","waters","stars","lightning","beams","beard","velvet","flash","grass","book"

REM 7 Color table entries
colortable:
DATA "red","yellow","blue","green","white","black","orange"

REM 14 Noun Modifier Table (Nouns, Verbs/Adverbs, Adjectives)
nounmodifier:
DATA "sunshine","light","glow","fog","of peace","of love","blue","great","unloved","sad","happy","loved","of light","of love"


This is a different approach to the problem. Here is the idea:

I am making the assumption that your music collection does not change too much between start-ups of your script and that all your songs are longer than it takes to scan your entire music collection.

Introduce a function to save the mp3_list to a file
On start-up look for that file and start playing a first random song (where we need to check that it still exists) from that file if it exists.
Meanwhile or if the file does not exist yet, (re-)scan the music collection in the background, while the first song is playing and write it back to the file once it is finished.
After the first song, just play n - 1 songs from the now up-to-date music database (if the scanning is finished, otherwise use the old file).

This approach might be slower than your approach, if many music files disappeared since the last start. It might fail if all of them disappeared (but we can check for that).

This approach has a different random distribution for the first song. (Consider that you only had one song in your directory during the first start of the script, and 1000 now. It will chose that one song on start-up the next time).

And here is the code. I used the python bindings of vlc, which are available here from their official github. Just download vlc.py and save it in the same directory as the script.

The functions read_db and save_db should be self-explanatory. get_existing_file gives one random track from mp3_list, making sure it actually exists.

When calling media_player.play(), this starts the playback in the background, so we are free to scan the folders now and save the new state.

After that I included some rudimentary playback controls.

By default, the player will continue looping through the playlist. Type stop, followed by Enter to stop it and exit the script.

This could use some more encapsulation of the methods, but it is a start.

import os
import sys
import random
import vlc
import time

# http://ubuntuforums.org/showthread.php?t=2136340
# http://stackoverflow.com/questions/19859840/excluding-directories-in-os-walk

def scan_folder(rootpath, exclude_dirs, file_ext):
    musiclist = []
    for path, dirs, files in os.walk(rootpath):
        dirs[:] = [d for d in dirs if d not in exclude_dirs]
        for f in files:
            if f.endswith(file_ext):
                mp3 = os.path.join(path, f)
                musiclist.append(mp3)
    return musiclist

def save_db(mp3_list, file_name):
    """Write `mp3_list` to `file_name`"""
    with open(file_name, "w") as db_file:
        db_file.write("\n".join(mp3_list))

def read_db(file_name):
    """read `mp3_list` from `file_name`"""
    mp3_list = []
    with open(file_name) as db_file:
        for line in db_file:
            mp3_list.append(line.strip())
    return mp3_list

def get_existing_file(mp3_list):
    """Get a random file name from `mp3_list` that exists"""
    first_song = random.choice(mp3_list)
    while not os.path.isfile(first_song):
        first_song = random.choice(mp3_list)
    return first_song

if __name__ == "__main__":
    # input variables
    vlcpath = r'/usr/bin/vlc'
    musicpath = r'/home/andreas/Musik'
    excludedirectories = {'_baby music', 'Buble, Michael', 'ballroom dancing'}
    db_file = os.path.join(os.getenv('HOME'), ".music.db")
    filetype = r'.mp3'
    len_playlist = 50

    # get mp3_list
    print 'party on... filling glasses!'
    try:
        mp3_list = read_db(db_file)
    except IOError:
        mp3_list = scan_folder(musicpath, excludedirectories, filetype)
        save_db(mp3_list, db_file)

    # setup vlc
    vlc_instance = vlc.Instance()
    media_player = vlc_instance.media_list_player_new()

    playlist = vlc_instance.media_list_new([get_existing_file(mp3_list)])
    media_player.set_media_list(playlist)
    media_player.play()

    # Rescan library
    print "Scanning music library for changes..."
    mp3_list = scan_folder(musicpath, excludedirectories, filetype)
    save_db(mp3_list, db_file)
    # time.sleep(10)
    print "done"

    # add songs to playlist
    all_songs = [first_song] + \
        random.sample(mp3_list, min(len(mp3_list), len_playlist - 1))
    playlist = vlc_instance.media_list_new(all_songs)
    media_player.set_media_list(playlist)

    # add rudimentary playback controls
    actions = {"next": media_player.next,
               "previous": media_player.previous,
               "pause": media_player.pause,
               "stop": sys.exit}
    # keep alive
    while True:
        key_pressed = raw_input("enter next, previous, pause or stop: ")
        if key_pressed in actions:
            actions[key_pressed]()

As a next iteration, I encapsulated all media_player functionality into a VLCPlayer class and all functionality surrounding the mp3_list into a MediaLibrary class.

import os
import sys
import random
import vlc
import time

# http://ubuntuforums.org/showthread.php?t=2136340
# http://stackoverflow.com/questions/19859840/excluding-directories-in-os-walk

class VLCPlayer():

    def __init__(self):
        self.vlc_instance = vlc.Instance()
        self.media_player = self.vlc_instance.media_list_player_new()
        self.actions = {"next": self.media_player.next,
                        "previous": self.media_player.previous,
                        "pause": self.media_player.pause,
                        "play": self.media_player.play,
                        "stop": sys.exit}

    def set_media_list(self, playlist):
        self.playlist = self.vlc_instance.media_list_new(playlist)
        self.media_player.set_media_list(self.playlist)

    def play(self):
        self.media_player.play()

    def playback_control(self):
        key_pressed = raw_input("enter next, previous, pause or stop: ")
        if key_pressed in self.actions:
            self.actions[key_pressed]()
        else:
            print "Unrecognized command"

class MediaLibrary(list):

    def __init__(self, file_name, path, excluded=set(), extensions={".mp3"}):
        self.file_name = file_name
        self.path = path
        self.excluded = excluded
        self.extensions = extensions
        list.__init__(self, [])
        try:
            self.read_db()
        except IOError:
            self.scan()

    def scan(self):
        self.scan_folder()
        self.save_db()

    def scan_folder(self):
        self[:] = []
        for path, dirs, files in os.walk(self.path):
            dirs[:] = [d for d in dirs if d not in self.excluded]
            for f in files:
                for extension in self.extensions:
                    if f.endswith(extension):
                        track = os.path.join(self.path, f)
                        self.append(track)

    def save_db(self):
        """Write self to `file_name`"""
        with open(self.file_name, "w") as db_file:
            db_file.write("\n".join(self))

    def read_db(self):
        self[:] = []
        with open(self.file_name) as db_file:
            for line in db_file:
                self.append(line.strip())

    def get_existing_file(self):
        first_song = random.choice(self)
        while not os.path.isfile(first_song):
            first_song = random.choice(self)
        return first_song

    def get_songs(self, n):
        if n > len(self):
            print "Warning: less files in library than requested"
            n = len(self)
        else:
            n -= 1
        return random.sample(self, n)

if __name__ == "__main__":
    # input variables
    vlcpath = r'/usr/bin/vlc'
    musicpath = r'/home/andreas/Musik'
    excluded = {'_baby music', 'Buble, Michael', 'ballroom dancing'}
    db_file = os.path.join(os.getenv('HOME'), ".music.db")
    filetype = r'.mp3'
    len_playlist = 50
    print 'party on... filling glasses!'

    # get music list
    library = MediaLibrary(db_file, musicpath, excluded, {filetype})

    # setup vlc and start playing first song
    media_player = VLCPlayer()
    first_song = library.get_existing_file()
    media_player.set_media_list([first_song])
    media_player.play()

    # Rescan library
    library.scan()

    # add more songs to playlist
    media_player.set_media_list(library.get_songs(len_playlist))
    # add rudimentary playback controls and keep alive
    while True:
        media_player.playback_control()

This is still not perfect, VLCPlayer could inherit from vlc.MediaListPlayer, but that makes it harder, because it is immutable.