Your code is indented well, and appears to have no problems in this way.

When you start the game, you should have all code that would otherwise just run defined in a method like this:

if __name__ == "__main__":
    start()

You can learn about this more here: What does if __name__ == “__main__”: do?

It is very good that your main delegates all the work of starting a game to a start() method.

You should probably run your text through a spell checker, should this be "nobody", "civilization", "Burger King" (capitalized as a proper noun), and "sweat"?

  "No bobdy comes for you."
  "You see civiliztion and stop at the first buger king."
  "You sweet to death and die!"

There are many other misspellings in here.

I would probably create a method to print the options the user has, and you can pass the options as a tuple:

def print_options(options):
    for i in range(0, len(options)):
        print str(i + 1) + ". " + options[i]

This can now be called like this:

print_options(("t1", "t2", "t3"))

Your game will be a little boring once the user has played it a couple times.  There seems to be no element of randomness, so there is only one path to victory.  The user won't want to lose, so once they realize this, they probably won't play your game.  To defeat this problem, you should probably use a random number generator to randomly choose options, which can be weighted to give certain actions a higher probability of happening.

In start(), you recursively call start() if the user chooses to stay still.  In this case, it probably is not a big deal because you don't create a bunch of variables and the user won't choose to stay still forever, but it isn't always a good idea to do this because the call will be added to the stack recursively until the stack overflows (if this point is ever reached); instead, you should use a loop to display the prompt until the user chooses to move.

Your win() and dead() methods are essentially the same.  You should combine these into one method for ending the game.

When you open and read the note at cabin 2, I would not put that in a file by itself.  It does not describe what the program is doing any more than just printing the note with print - in fact, I think print shows what is happening better.  What it is doing is describing what the user is doing, which is very different than what the program itself is doing.


Project Euler questions are primarily about math.  This isn't really the place to practice object-oriented programming.  In fact, trying to model the problem literally will lead you to a suboptimal solution.

The "right" algorithm is very simple, and involves no primality testing.

I wouldn't bother with an IsFactor() method at all — if you just write it as a modulo test, there is no confusion about the order the parameters.

class ProjectEuler3
{
    private long number;

    public ProjectEuler3(long number)
    {
        this.number = number;
    }

    public long GetAnswer()
    {
        long n = this.number;
        while (n % 2 == 0)
        {
            n /= 2;
        }
        for (long factor = 3; factor < n; factor += 2)
        {
            while (n % factor == 0)
            {
                n /= factor;
            }
        }
        return n;
    }

}


Overview
Your code produces the exact same set of samples each time you random_shuffle. So the output is always
0 1 2 3 4 5 6 7 8 9
4 3 7 8 0 5 2 1 6 9
0 5 7 8 4 3 9 2 1 6
5 7 6 3 8 4 2 0 1 9
4 6 0 2 8 1 3 9 5 7
4 0 5 1 7 9 6 2 8 3
3 8 5 6 1 7 2 4 0 9
0 4 6 2 9 5 8 3 1 7
1 3 6 8 2 7 5 9 0 4
5 1 7 9 8 0 6 4 2 3

You should initialize the seed. You do that before you call random_shuffle. If you do not do that it will give the same result each time since it relies on the seed.
You can fix that by calling std::srand in the beginning.
int main() {
    std::srand(std::time(0));
}

Now you can see the difference in the output
0 1 2 3 4 5 6 7 8 9
9 2 8 3 6 4 0 7 1 5
8 9 4 6 7 2 1 5 0 3
4 6 0 2 3 1 5 8 9 7
2 3 0 1 6 8 9 5 7 4
8 9 6 5 2 1 3 7 4 0
9 3 2 8 6 7 5 0 4 1
8 1 2 5 9 6 4 3 0 7
7 1 4 6 8 9 3 0 5 2
3 1 9 4 2 7 6 0 5 8

But the top row still will always be the same. The problem lies here
RandomIndex::RandomIndex(unsigned int _size) {
    size = _size;
    index.resize(_size, 0);
    std::iota(index.begin(), index.end(), 0);
}

iota will always will it starting with 0 and incrementing it will it reaches index.end(). get_index will only shuffle the container after the first row since that's when counter < size evaluates to false.
To fix that you can also shuffle in the beginning, when you construct the vector.

Use std::shuffle
random_shuffle has been deprecated. Use shuffle  with a random number generator so that your code can compile on the later c++ versions.

Avoid using _ as a prefix for your variables
There are some naming conventions you need to follow when it comes to underscores to avoid collisions. Moreover, it just looks ugly. To initialize size in your class constructor you are better off using member initializer lists.
RandomIndex::RandomIndex(unsigned int size)
    : size(size)  {

 //...
}

use an array with a fixed size over vector
In your class size is a value that is never going to change. If you plan on keeping it that way you can, use std::array here with a template so you can have a fixed size. This will avoid all the resizing and heap fiddling resulting in faster execution. std::shuffle will work the same way it does with vector thanks to the way STL is designed.
template < size_t s >
class RandomIndex {
   //...

private:
    std::array < uint32_t, s > index;

};


std::vector<std::thread> asyncCalls;

This creates a global variable (so, you know, don't do that) — and it creates the global variable in every .cpp file that imports this header file. So unless you only have one .cpp file in your project, you're going to get linker errors when you try to link your project.

What you wanted to do was put this variable definition in a .cpp file and put a declaration of it (using extern) in your .hpp file.

Alternatively, as of C++17, you could have made it an inline variable:

inline std::vector<std::thread> asyncCalls;

However, global variables are terrible; don't do anything like this. Maybe what you want is some notion of "thread pool":

class ThreadPool {
    std::vector<std::thread> asyncCalls;
    // ...
};

#define asyncCall asyncCalls.emplace_back // Whenever someone calls asyncCall this constructs a new std::thread which calls their function

This is a preprocessor macro (so, you know, don't do that). What you meant was

class ThreadPool {
    std::vector<std::thread> asyncCalls;

public:
    template<typename... Args>
    void asyncCall(Args&&... args) {
        asyncCalls.emplace_back(std::forward<Args>(args)...);
    }
};

void finishAsync(){ //Call to block until all running asyncronous functions return
while(!asyncCalls.empty()){ //Loop until the vector is empty

Two things:

Please indent your code. Four-space indents would be nice.
Who do you expect to call this function? and how do you know that nobody else is going to be calling emplace_back at the same instant that that guy is calling empty? Looks like you have a huge thread-safety problem here.

#ifdef _GLIBCXX_CHRONO //Include <chrono> before this header for this function

Don't do this. For one thing, your code won't do the right thing on Clang with libc++ (or MSVC, or basically any non-libstdc++ distribution). What you meant was

#include <chrono>

This way, your header includes all the headers it depends on, recursively, and you never have to worry about whether your caller included something else before you or not.

As far as "would this code be a good idea if it worked": a resounding no. Your asyncCall function isn't really doing anything that std::async wouldn't do on its own; and std::async on its own is a bad idea because if you call it too many times you'll eventually run out of threads and start getting "Resource temporarily exhausted" errors. If you're going to be writing programs that use asynchrony as their primary implementation technique, the last thing you want to do is run out of threads. You need to figure out some way to queue up "tasks" without tying up a whole std::thread per (stalled) task.


Can this code be cleaned? Multiple objects triggering different hover events

In your hover method you want to select the next two divs after the img. Assuming that the divs are located (in DOM) immediately after the img, then you can select them using the jQuery .next() method, instead of selecting them by name.

ALso instead of selecting each img by id, you could give them all the same class, and then use a single jQuery selector to select every img with that class.

Untested and probably slightly buggy example code:

artist

song title

artist

song2

$(document).ready(function () {

    $("img.album").each().hover(

        $div = $(this).next(); // find the next element after this img

        function () {
            $div.animate({
                'opacity': 1
            });
        },

        function () {
            $div.animate({
                'opacity': 0
            });
        });
    });

If the div element is not immediately after the img (so you can't use the .next method), you can relate each div to its img by defining a new attribute which begins with data-, for example data-img-id:

artist

song title

artist

song2

Then, in your general-purpose hover method, you can get the id of the this img tag, and use that id value to select the corresponding div using its data-img-id element.


First off, you have a bug. This instruction

window.onload = updateNav();

doesn't execute updateNav on load. It executes updateNav immediately and assigns its return value (which is undefined) to onload. Instead it should be:

window.onload = updateNav;

Also assigning event handlers directly to on... properties isn't something you should be doing. The main problem is you are potentially overwriting any other scripts that also addign to onload. You should instead use addEventListener.

You can simplify parsing the URL. document.location already is provides the parts of the URL. In your case document.location.pathname contains the path without domain, query, hash, etc:

function getFileName() {
    var url = document.location.pathname;
    url = url.substring(url.lastIndexOf("/") + 1, url.length);
    if (url.length == 0) url = "index";
    return url;
}

In my opinion you are misusing the id attribute here. This is not what it's made for. (However to be honest I have difficulties finding the right words to explain why not - it just feels wrong.)

Finally you should be aware that this is a bad usage of JavaScript. You are using JS here for something that should be done server-side (that is directly in the HTML).


Dijkstra's shortest path with max intermediate nodes limitation

If you apply your algorithm twice, as in

        g.calculate_shortest_path(1,3)
        ....
        g.calculate_shortest_path(1,2)

it would fail badly.

The reason is that visited, shortest_path, and shortest_path_distance are not, and cannot be, a property of Graph (especially visited). They are ephemeral properties of a particular traversal.

Questionably shortest_path and shortest_path_distance could be made properties of a vertex to allow for some optimization; I not quite sure it worths effort.


Python script to clean out old files from a repository

This is just a brain dump of some things about your code that I hope you find useful.

Automated tools

Automated tools can help you maintain your code more easily.

The first ones I install whenever I start a new Python project, are:

black — The uncompromising Python code formatter
isort — A Python utility to sort imports
flake8 — A tool to enforce PEP 8 compliance (among other things)

I ran them on your code with the following options:

pipenv run black clean_old_files.py
pipenv run flake8 --max-line-length 88 clean_old_files.py
pipenv run isort clean_old_files.py -m=3 -tc -l=88

(An aside, I'm using Pipenv to manage my virtual environments. They're unmissable once you start getting into larger projects with external dependencies, and other contributors.)

Noisy comments

You have several comments that explain what the code does, rather than why.

For instance this:

# Gets the current time from the time module
now = time.time()
# Timer of when to purge files
cutoff = now - (14 * 86400)

which could be rewritten as:

# Timer of when to purge files
cutoff = time.time() - (14 * 86400)

which removes one "what" comment, and inlines a temporary variable.

My advice would be to go over all the comments in your script, and see which are "what" comments, and which are "why" comments.

Code structure

A minor thing to start off, I'd move the main function to the bottom of the script, right before if __name__ == "__main__", which, conceptually makes most sense to me.

You are mutating global variables from functions, which makes it harder to follow your program structure as-is.

On a related note, you also have global All_dest_dirty, which is a typo.

Globals

Instead of, for instance:

all_dest_dirty = []

def dest_files():
    for dest_root, dest_subdirs, dest_files in os.walk(dest):
        for f in dest_files:
            global all_dest_dirty
            all_dest_dirty.append(f)

prefer:

def dest_files():
    dirty_files = []
    for dest_root, dest_subdirs, dest_files in os.walk(dest):
        for f in dest_files:
            dirty_files.append(f)

    return dirty_files

all_dest_dirty = dest_files()

Closing remarks

Correct me if I'm wrong, but from

all_dest_clean = list(dict.fromkeys(all_dest_dirty))

I think that you're trying to remove duplicates from a list?

You can write that as

all_dest_clean = set(all_dest_dirty)

which uses the set data type, which prevents any duplicates. Plus, it's less typing, and also clearer. :-)

I hope you found my mini review helpful. You're doing great for a beginner! Keep it up. Also, let me know if anything is unclear.


For a small array or list of a handful of items, this should be very fast.  But is it efficient as you would scale out?  No.

Before getting on to a better way to achieve the it for a larger number of items, let's look at your current code.  You have some checks that aren't needed.

if (a[i] == a[j] && i != j)

The check of i != j is not needed if you were to simply initialize j to be i + 1 as in:

for (int j = i + 1; j < a.Length; j++)
    if (a[i] == a[j])

The check of if (i < answer[1]) is totally unnecessary.  In fact, answer as an array is not needed at all as you do not really do anything meaningful with answer[1].

But having 2 loops is not efficient as the input array could be larger.  As mentioned in a comment, the use of a HashSet could be used.  I am changing a few things.

The method signature is now IEnumerable<int> to allow for arrays,
lists, or any collection of integers.
I use a HashSet to keep track of items I have already
encountered.
The return type is a Nullable<int>, also written as int?, so that
if there are no duplicates found a null is returned.

The resulting method also looks cleaner.  Someone looking at this understands more readily what the code is trying to achieve:

public static int? FirstDuplicate(IEnumerable<int> items)
{

    HashSet<int> set = new HashSet<int>();
    foreach (int item in items)
    {
        if (set.Contains(item))
        {
            return item;
        }
        set.Add(item);
    }
    return null;
}

As shown in @Denis's answer, and echoed by @Corak, is the method could be made slightly faster and shorter by reducing the logic inside the foreach loop:

if (!set.Add(item))
{
    return item;
}

While this again is slightly faster, slighter cleaner, and recommended in practice, it still lags well behind @vnp 's array solution.

UPDATED Worst Case Array

I composed a worst case array to test of 100000 items where the very last item is the first duplicate of the 2nd to last item.  Your code and mine returned the correct value.

public static int[] WorstCaseArray
{
    get
    {
        int[] items = new int[(int)Math.Pow(10, 5)];
        for (int i = 0; i < items.Length; i++)
        {
            items[i] = i + 1;
        }
        items[items.Length - 1] = items[items.Length - 2];
        return items;
    }
}

UPDATE #2 - Worst Case

Obviously we should be working with the largest array allowed.

As @PeterCordes states in a comment to @vnp's answer, the list should be randomized.

As @Denis states, the worst case for a HashSet would be if the only duplicate was the first and last item.  An extremely close second would be if the last and 2nd to last item were the only duplicate.  Note this second worst case for HashSet would be the worst case for @vnp's array solution, so I will use it as my worst case.

public static int[] WorstCaseArray
{
    get
    {
        // Worst case is largest allowed array ...
        int max = (int)Math.Pow(10, 5);
        int[] items = new int[max];
        for (int i = 0; i < items.Length; i++)
        {
            items[i] = i + 1;
        }
        // ... that is randomly shuffled ...
        Shuffle(items);
        // ... with the only duplicate being the last item matching the 2nd to last!
        items[items.Length - 1] = items[items.Length - 2];
        return items;
    }
}

private static Random random = new Random();
public static void Shuffle(int[] items)
{
    //Fisher-Yates method to shuffle
    for (int i = items.Length - 1; i > 0; --i)
    {
        int randomIndex = random.Next(i + 1);
        int temp = items[i];
        items[i] = items[randomIndex];
        items[randomIndex] = temp;
    }
}

UPDATED Worst Case Timings:

Yours: 14.5105877 seconds
Mine : 00.0065640 seconds
vnp's: 00.0012733 seconds

Tiny array with many duplicates

However, as I said for only a handful of items yours is quite fast.  The problem is - it produces the wrong answer!  Using this array:

int[] array =  new[] { 1, 2, 3, 4, 5, 6, 3, 4, 5, 6 };

Where the expected answer would be 3, yours returns 6.

Yours: took 0.0006141 seconds but returned 6 (wrong)
Mine : took 0.0006162 seconds
vnp's : 0.0003843 seconds

Large, Random Array with No Duplicates

To round out the answer, let's look at the largest allowed array, randomized, but without any duplicates.  Using the shuffle routine from above:

public static int[] NoDuplicates()
{
    int[] items = Enumerable.Range(1, (int)Math.Pow(10, 5)).ToArray();
    Shuffle(items);
    return items;
}

Timings:

Yours: 15.1978462 seconds
Mine  : 00.0055364 seconds
vnp's : 00.0014876 seconds

BEST ANSWER

Also, since you have tagged this question with [time-limit-exceeded], vnp's answer is not just clever, but also the fastest in all tested scendarios, which makes it the best answer (regarding performance).


Formatting

Indenting

The standard ruby indent is 2 spaces.  For example:

def puts(string)
  if @@logger.nil?
    super(string)
  else
    @@logger.info string
  end
end

Design

Class Variables

I would not use class variables to set the logging.  As you
discovered, they have surprising
behavior.

Instead, I would just use a class instance variable that belonged
just to the Plugin class and was not automatically shared with its
descendants.

module Plugin
  class << self
    attr_accessor :logger
  end
end

If that's all you do, then the descendants will have to do this to access the logger:

Plugin.logger.info 'Logging some info'

That's awful, so we'll add an instance method that defers to the class method:

module Plugin

  class << self
    attr_accessor :logger
  end

  def logger
    self.class.logger
  end

end

Now instances of Plugin can log easily:

logger.info "Logging some info"

Ruby tricks

Use #inspect to quote strings

Instead of this,

@logger.info "Loading \"#{class_name}\" from \"#{full_path}\""

Use #inspect to do the quoting for you:

@logger.info "Loading #{class_name.inspect} from #{full_path.inspect}"

Remove eval

You don't need eval here:

unless eval("defined? #{class_name}")

instead:

unless defined?(class_name)

ancestors.include?

Instead of this:

if plugin_class.ancestors.include? Plugin

do this:

if plugin_class < Plugin

See this SO answer, and the rdoc for Module#<

instance_method

Instead of this:

if plugin_class.allocate.method(:initialize).arity > 0

this:

if plugin_class.instance_method(:initialize).arity > 0

This avoids the funny business of allocating one.

exceptions

The code wishes, when a plugin cannot be added, to log it and continue
adding more plugins.  That works well, but the way it's done can be
simplified using exceptions.

Instead of this:

plugins.each do |plugin|
  ...
        unless eval("defined? #{class_name}")
            @logger.error "Class \"#{class_name}\" not found!"
            next
        end

  ...
end

consider this:

class PluginError < StandardError ; end

plugins.each do |plugin|
  begin
    ...
    unless eval("defined? #{class_name}")
      raise PluginError, "Class \"#{class_name}\" not found!"
    end
    ...
  rescue PluginError => e
    @logger.error e.to_s
  end
end

This gets rid of all of those "next" calls, simplifying the error handling.


Avoid using namespace std; - it can cause problems with name collisions. It's best to qualify names where necessary, e.g.: std::cout

std::endl adds a newline, but it also flushes the output stream. Unless we actually need the flushing behavior, it's best to simply output a newline "\n" where necessary (e.g. << "2. to clean your cat, type c\n").

char command; does not need to be a global variable. It's only accessed in a single function, so it can be a local variable.

The exit() function is not necessary. We can call std::exit(0) directly. Note that we should include <cstdlib> for this function, and use the exit codes EXIT_SUCCESS or EXIT_FAILURE instead of a number like 0.

Functions that are used only in a single file do not need to be declared in header files. If necessary, we can declare them above the point of use, or move the function definition higher up the file. e.g.:
void commandIdentify(); // forward declaration

int main() { ... }

void commandIdentify() { ... } // function definition

or
void commandIdentify() { ... } // function definition

int main() { ... }

In the Cat class, the happy and isClean members are not quite correct. They will only be set on initialization. If the cat's happiness or cleanness changes at a later time, they will not be updated. In addition, initialization of variables occurs before the body of the constructor, in the order that they are declared in the class.
For the initial values of happy and isClean to be set correctly, we would have to use a member initializer list:
Cat::Cat():
    happiness(1),
    /* `happy` is initialized here */
    cleanness(1),
    /* `isClean` is initialized here */
{
    // if we set happiness now, `happy` won't get updated!
    happiness = 0.2,
}

In any case, since we want the values to always be updated, we should make happy and isClean member functions instead:
bool isClean() const { return cleanness >= 0.6; }

That way, we don't need to update any extra state.

Member functions that don't modify the state of the class (i.e. any member veriables) should be declared const, e.g.:
void checkHappiness() const { ... }

Cat cat; This doesn't need to be a global variable. We can make the cat a local variable in main() and pass a reference to it to the functions that need to use it:
int main() {
    Cat cat;
    ...
    commandIdentify(cat);
}

void commandIdentify(Cat& cat) {
    ...
    feedCat(cat);
}

void feedCat(Cat& cat) {
    ...
    cat.feed();
}

This may seem like more work, but it's quite important, as means that our commandIdentify function (and the functions for each command) will now work with any cat, not just the one cat that we declared in main().
So now we can feed many cats!


Implementation of Radix Sort algorithm for sorting integers in c++

First things first, don't use using namespace std in header files, where your radix sort implementation should be. Besides, convenience isn't a valid excuse when the only thing you import from std is cout: just type std::cout and you're done.
One liner functions are often useless and noisy: you need to refer to the implementation to know exactly what they do, so they don't make the code more readable, and you have to come up with a name, which is not always easy. In the case of getNumberAtPosition, for instance, it's impossible to tell from the name if the position is meant for the most or least significant digit, and both are equally likely in a radix sort algorithm.
everything that isn't meant to change should be const. The only place where it isn't idiomatic is in function signature, where you often don't tag built-in type arguments passed by value as const.
Also, don't alias variables: length is only used to define sizeOfEachBucket, that's two names to track down instead of one.
Use the standard library: there may not be many things inside compared to other languages, but what's inside is very well implemented. It will also make your code more concise and expressive. For instance, the largest element in a [first, last) sequence is the result of std::max_element(first, last) (std::max_element resides in <algorithm>). Using standard containers is also a statement: a constant size array will be a std::array, whereas a variable-size one will be a std::vector.
Avoid naked loops: by that I mean loops like for (int i = 0; i < z; ++i). The nested ones are particularly difficult to read, with all those meaningless one-letter variable names. Use either range based for loops when you iterate over the whole container (e.g: for (auto item : vector)) or named algorithm when your loop has a standardly implemented purpose (std::for_each, std::copy, etc.).
When implementing your own algorithms, try to use an stl-like interface: iterators are preferable because they abstract the concrete container-type. Your algorithm won't work on an std::list although it very well could be (radix sort doesn't rely on random access like quick sort does).

Here's an example of better-looking (though not thoroughly tested) code:

#include <algorithm>
#include <vector>
#include <array>
#include <cmath>

template <typename Iterator>
void radix_sort(Iterator first, Iterator last) {
    const int max_divisor = std::pow(10, std::log10(*std::max_element(first, last)));
    for (int divisor = 1; divisor < max_divisor; divisor *= 10) {
        std::array<std::vector<int>, 10> buckets;
        std::for_each(first, last, [&buckets, divisor](auto i) {
            buckets[(i / divisor) % 10].push_back(i);
        });
        auto out = first;
        for (const auto& bucket : buckets) {
            out = std::copy(bucket.begin(), bucket.end(), out);
        }
    }
}

EDIT: since the algorithm exposed in the question relies on decimal digits, I also formulated a base-10 based algorithm. But thinking back about this, I feel like my answer isn't complete if I don't precise that a base-two approach is more optimal (and more generally used as far as I know). Why is that?

because binary arithmetic is easier for a computer (not a very strong reason since decimal arithmetic is often optimized into binary arithmetic by the compiler);
because -and that's a much stronger reason- you can the rely on a very well-known algorithm to distribute your number between buckets, an algorithm that moreover does it in place, thus without any memory allocation;
by the way, that algorithm is std::stable_partition

And here is a sample:

template <typename Iterator>
void binary_radix_sort(Iterator first, Iterator last) {
    using integer_type = std::decay_t<decltype(*first)>;
    bool finished = false;
    for (integer_type mask = 1; !finished; mask <<= 1) {
        finished = true;
        std::stable_partition(first, last, [mask, &finished](auto i) {
            if (mask < i) finished = false;
            return !(mask & i);
        });
    }
}


Downsampling n-dimensional data from bins in one dimension

You could use numpy.digitize to determine which bin each point belongs in, allowing for a simpler expression inside where.


Need Feedback on JUnit test comparing two timestamps

The problem here is the call to the new operator inside your code under test (cut). So the way to go is to inject this dependency into your cut. Of cause the (failed) implementation of the Java Singelton Pattern is a problem too.
By looking at the API of the Date class we find that it is mutable (which raised lots of discussions when it was introduced). This gives us the opportunity to define a member variable of type Date and reuse is in all the methods of the cut. Of cause in each method  Date.setTime(milliseconds) needs to be called where we pass in System.currentTimeMillis().
Of cause this is a new requirement to our cut that needs its own UnnitTest methods.
 class InjectDateTest {

    static class LoggerService {

        private Date date;

        public LoggerService(Date date) {
            this.date = date;
        }

        public Long startTimeFrame() {
            date.setTime(System.currentTimeMillis());
            return date.getTime();
        }

    }

    private LoggerService loggerService;
    private Date loggerDate = new Date();

    @BeforeEach
    void setUp() throws Exception {
        loggerService = new LoggerService(loggerDate);
    }

    @Test
    public void shouldSetTimeAfterCall() throws InterruptedException {
        long creationTime = loggerDate.getTime();
        Thread.sleep(200, 0);
        loggerService.startTimeFrame();
        assertTrue(creationTime < loggerDate.getTime(),
                String.format("time in date object %s < %s", creationTime, loggerDate.getTime())
                );
    }

    @Test
    public void testStartTimeFrame() {
        Long startTimeFrame = loggerService.startTimeFrame();
        assertEquals(loggerDate.getTime(), startTimeFrame);
    }

}


Validating that only certain values are unset

A few things:

your indentation looks weird
you could store data[0] in some variable with a relevant name.
you could iterate over both keys and values with iteritems() /items()
you do not need continue here. A simple else would do the trick and is more explicit.
The line you don't quite like could be replaced by something like :

self.assertTrue(any(w in key for w in ('rate', 'percentage', 'ratio')))

The resulting code would be :

first_data = data[0]
for key, val in first_data.items():
    self.assertIn(key, data_model)
    if val is None:
        self.assertTrue(any(w in key for w in ('rate', 'percentage', 'ratio')))
    else:
        self.assertIsInstance(val, data_model[key])


Divide and conquer approach in search for max element, take 2

The code panics with a stack overflow if you provide an empty array:

#[test]
fn test_empty() {
    let array: [u8; 0] = [];
    array.max_elem();
}

thread 'test::test_empty' has overflowed its stack
fatal runtime error: stack overflow
error: Process didn't exit successfully: `/private/tmp/max/target/debug/max-426b0349be06fd52` (signal: 6, SIGABRT: process abort signal)

The tests don't work unless the crate is named max_elem. Instead, use use super::MaxElem instead.
You could choose to embed the helper method inside of the other function, giving a natural scoping (and preventing the need for the longer name):

impl<T> MaxElem<T> for [T]
    where T: Ord
{
    fn max_elem<'a>(&'a self) -> &'a T {
        fn helper<'a, T>(array: &'a [T], left: usize, right: usize) -> &'a T
            where T: Ord
        {
            // ...
        }

        helper(self, 0, self.len())
    }
}

Instead of passing in the entire slice and left / right; try splitting the slice into smaller parts via split_at. Then the slice itself tracks the beginning and the end.
The function cmp::max exists.

Overall, there's a nice functional implementation that weighs-in at about 20 lines.

use std::cmp;

trait MaxElem<T> {
    fn max_elem<'a>(&'a self) -> Option<&'a T>;
}

impl<T> MaxElem<T> for [T] where T: Ord {
    fn max_elem<'a>(&'a self) -> Option<&'a T> {
        let len = self.len();

        match len {
            0 | 1 => self.first(),
            _ => {
                let mid = len / 2;
                let (left, right) = self.split_at(mid);

                let left = left.max_elem();
                let right = right.max_elem();

                match (left, right) {
                    (Some(a), Some(b)) => Some(cmp::max(a, b)),
                    _ => left.or(right)
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::MaxElem;

    #[test]
    fn test_max_elem() {
        let array = [11, 2, 9, 1, 3, 88];
        assert_eq!(Some(&88), array.max_elem());
    }

    #[test]
    fn test_empty() {
        let array: [u8; 0] = [];
        assert_eq!(None, array.max_elem());
    }
}


HeightWeightSize

This doesn't make a good class name. What if you add another property? You'd need to change its name again.

I guess Person or something alike would be much better.

Gaussian gaussian = new Gaussian();
gaussian.Sex = key;
gaussian.Count = gaussianDataSet[key].Height.Count;

gaussian.HeightMean = Statistics.Mean(gaussianDataSet[key].Height);
gaussian.WeightMean = Statistics.Mean(gaussianDataSet[key].Weight);
gaussian.FootSizeMean = Statistics.Mean(gaussianDataSet[key].FootSize);

gaussian.HeightVariance = Statistics.Variance(gaussianDataSet[key].Height);
gaussian.WeightVariance = Statistics.Variance(gaussianDataSet[key].Weight);
gaussian.FootSizeVariance = Statistics.Variance(gaussianDataSet[key].FootSize);

You could simplify this by putting it inside the Gaussian class.

class Gaussian
{
    public Gaussian(string sex, int count, double height, double weight, double footSize)
    {
        HeightMean = Statistics.Mean(Height);
        // ...
    }

    public double HeightMean { get; }
    // ...
}

Adding it to a dictionary would then can be reduced to:

gaussianList.Add(key, new Gaussian(
    sex,
    gaussianDataSet[key].Count
    gaussianDataSet[key].Height,
    ...,
    ...)
);

There is still too much redundancy and you could improve more then the above but I don't know how the HeightWeightSize type looks like.


Delegate that selects a writable property on a generic

Yup, it is possible, but you'll have to delve into the dark world of Expression Trees.

This function creates getter and setter functions using the out parameters. It's ugly, and you usually don't want to use two out parameters, but hopefully it'll get you moving in the right direction.

public static bool CreateGetterSetter<T, V>(Expression<Func<T, V>> getterExpression, out Func<T, V> getter, out Action<T, V> setter)
{
    if (getterExpression == null)
        throw new ArgumentNullException("getterExpression");

    var memberExpression = getterExpression.Body as MemberExpression;
    if (memberExpression == null || memberExpression.NodeType != ExpressionType.MemberAccess || memberExpression.Member == null)
        throw new ArgumentException("The expression must get a member (property or field).", "getterExpression");

    // The expression passed in is the getter, so just compile it.
    getter = getterExpression.Compile();

    // The setter function takes two parameters as input.
    var paramT = Expression.Parameter(typeof(T));
    var paramV = Expression.Parameter(typeof(V));

    // Create the setter function
    if (memberExpression.Member.MemberType == MemberTypes.Field)
    {
        // The getter retrieves a field.
        var field = memberExpression.Member as FieldInfo;
        if (field == null)
            throw new ArgumentException("Could not get field info for member " + memberExpression.Member.ToString());

        // This expression represents the field on the parameter.
        var fieldExpr = Expression.Field(paramT, field);

        // This expression is what the field will be set to.
        Expression rightExpr;
        if (paramV.Type == field.FieldType)
            rightExpr = paramV;
        else
            rightExpr = Expression.Convert(paramV, field.FieldType);

        // This is the assignment expression (sets the field to the parameter value).
        var assign = Expression.Assign(fieldExpr, rightExpr);

        // Compile the expressions into a lambda.
        setter = Expression.Lambda<Action<T, V>>(assign, paramT, paramV).Compile();
    }
    else if (memberExpression.Member.MemberType == MemberTypes.Property)
    {
        // The getter retrieves a property.
        var property = memberExpression.Member as PropertyInfo;
        if (property == null)
            throw new ArgumentException("Could not get property info for member " + memberExpression.Member.ToString());

        // This expression represents what the property will be set to.
        Expression paramSet;
        if (paramV.Type == property.PropertyType)
            paramSet = paramV;
        else
            paramSet = Expression.Convert(paramV, property.PropertyType);

        // Handle read-only properties (have no setter).
        if (!property.CanWrite)
        {
            setter = (t, v) => Debug.Write("Cannot set read-only property: " + property.ToString());
            return false;
        }

        // This expression represents calling the property setter.
        var call = Expression.Call(paramT, property.SetMethod, paramSet);

        // Compile the expressions into a lambda.
        setter = Expression.Lambda<Action<T, V>>(call, paramT, paramV).Compile();
    }
    else
    {
        // The member was not a field or a property.
        setter = (t, v) => Debug.Write("Setter invoked for invalid expression");
        return false;
    }
    return true;
}

Usage:

public class A
{
    public string Property { get; set;}
}

// Define the variables to hold the out parameters.
Func<A, string> getter;
Action<A, string> setter;

// Call function to use expression trees to create the getter and setter.
CreateGetterSetter<A, string>(a => a.Property, out getter, out setter);

// Now you can use "getter" to get A.Property...
var inst = new A { Property = "value" };
var value = getter(inst); // value = "value"

// ... and "setter" to set A.Property...
setter(inst, "new"); // inst.Property = "new"
value = getter(inst); // value = "new";

And to implement Round this way...

public static void Round<T>(IEnumerable<T> collection, params Expression<Func<T, decimal>>[] getterExpressions)
{
    // Create all the lambdas up-front. This is expensive, so you should cache this somewhere rather than
    // re-compiling all the expressions every time.
    var gettersSetters = new Tuple<Func<T, decimal>, Action<T, decimal>>[getterExpressions.Length];
    for(int i=0;i<getterExpressions.Length;i++)
    {
        Func<T, decimal> getter;
        Action<T, decimal> setter;
        CreateGetterSetter<T, decimal>(getterExpressions[i], out getter, out setter);
        gettersSetters[i] = Tuple.Create(getter, setter);
    }

    foreach (var item in collection)
    {
        foreach (var tuple in gettersSetters)
        {
            var getter = tuple.Item1;
            var setter = tuple.Item2;

            var value = getter(item);
            value = Math.Round(value, 1);
            setter(item, value);
        }
    }
}

Hope that helps!


First of all welcome to Codereview.

Good

You have a decent function.
You even have a nice docstring to describe what it does!
You have decent descriptive names.

Overall your code is good, well done!

Improvements

Make the starting_ascii value more generic, no more duplicated code.
Rais an appropriate exeption if no letter is given, you might want to handle that differently.

Revised code

def casear_cipher(letter, num):
    """This function acts like a Casear Cipher.

    Replaces an input letter with another letter a fixed
    number of spaces farther down the alphabet

    Args:
    * letter (string) - any upper case or lower case letter
    * num (integer) - any integer value to shift to a new letter"""

    if letter.isupper():
        starting_ascii = ord('A')
    elif letter.islower():
        starting_ascii = ord('a')
    else:
        raise ValueError('Input is not a letter')

    alpha_index = ord(letter) - starting_ascii
    mod_26 = (alpha_index + num) % 26
    return chr(starting_ascii + mod_26)


IntModulus long addition and subtraction

Small improvements

Overall, it seems that what you wrote is correct and is an improvement over the mod(mod(x)+mod(y)) solution, especially in the case where there is no overflow.  I have three small improvements:

Add instead of multiply by 2

You can replace this line:

   long result = 2L * mod(half) + lsb;

with:

    long halfmod = mod(half);
    long result = halfmod + halfmod + lsb;

The modified version showed a 1% improvement in the overflow case.  (See benchmarks below)

Remove one unnecessary check

Following the code above, you have this code:

    // Now the result lies in the range 0 to 2*modulus+1 (both included),
    // so conditionally reduce it twice.
    if (result>=modulus) result -= modulus;
    if (result>=modulus) result -= modulus;

But actually, the value of mod(half) is in the range 0..modulus-1.  So if you multiply that by 2 and add 1, result will be in the range 0..2*modulus-1, not 0..2*modulus+1 as you stated in the comment.  Therefore, after the first result -= modulus, the range of result will be 0..modulus-1 and there is no need for the second check.

    // Now the result lies in the range 0 to 2*modulus-1 (both included),
    // so conditionally reduce it once.
    if (result>=modulus) result -= modulus;

By removing the second check, I found a 1% speed improvement in the overflow case.

Checking for overflow

I replaced this overflow check for add:

   final boolean overflow = (x^y) >= 0 & (x^sum) < 0;

with this very similar one:

    final boolean overflow = ((x^y^Long.MIN_VALUE) & (x^sum)) < 0;

Edit: Later I found that this inverted version is faster:

    final boolean overflow = ((x^y) | ~(x^sum)) >= 0;

It tests the same thing but uses one extra xor instead of a comparison.  For the overflow case I found a 2% speed improvement, and it was about 4% faster in the non-overflow case.

For subtraction I did a similar thing:

   final boolean overflow = (x^y) < 0 & (x^diff) < 0;

became:

    final boolean overflow = ((x^y) & (x^diff)) < 0;

Here I didn't even have to add an extra xor.

Benchmarks

I took the suggestion of using JMH to run benchmarks.  Here are the results:

Overflow add test
-----------------
Methodology: Add 0x4000000000000000L with itself modulo 0x12345678
             in a loop of 100000 iterations.

Method                   Operations per second     Speed
------                   ---------------------     -----
Original code              238.754 +- 0.778        100.0%
Multiply change            241.527 +- 0.884        101.1%
Remove extra check         241.180 +- 1.007        101.0%
Change overflow check      243.335 +- 1.662        101.9%
All changes                256.452 +- 1.325        107.4%

Non-overflow add test
---------------------
Methodology: Add 0x4000000000000000L with 1 modulo 0x12345678
             in a loop of 100000 iterations.

Method                   Operations per second     Speed
------                   ---------------------     -----
Original code              330.298 +- 1.635        100.0%
Change overflow check      342.496 +- 2.037        103.7%


Caching large object in multithreading environment

I surely dislike your mixing of various mean synchronization. Using synchronized and Atomic* and also volatile together looks very strange. However, it looks like you got it right (a deeper analysis would be needed).

private volatile boolean refreshing;

You need no volatile if you access it inside the synchronized block only.

private long cachePeriodMs = 1000L;

I'd suggest cachePeriodMillis. It's only slightly longer and there's a precedent.

I guess, I'd drop the latch, define a non-anonymous Runnable for getting from the DB and let the first interested thread execute it directly. The others would wait on the corresponding synchronized block's entry (and then leave immediately).

I'd probably also aggregate CachedObject and lastUpdate into one object as they belong together. This might be a problem w.r.t "prevent other threads from calling this method again", but it should be possible to eliminate the need for this.

This way I might get a simpler design which I could trust more.


Print input one word per line (K&R 1-12 exercise) attempt

A few points to consider.

C99 added an actual Boolean type, named _Bool, with constants name _True and _False. By including <stdboolh.h>, you get aliases for those spelled bool, true and false. So unless you need to continue using C89, you might consider using these instead of defining your own names and such.
When you have a value that's conceptually Boolean in nature (e.g., your previous_space) I'd treat it as a Boolean, so to test if it's false, I'd prefer to use if (!previous_space).
Rather than explicitly checking for every possible white-space character in-line, I'd prefer to move that check into a separately little function of its own. Only this is such a common requirement that the standard library already provides isspace, so (at least in real code) it's generally preferred to #include <ctype.h>, and us that (but the book probably hasn't introduced this yet, so I wouldn't worry about it a whole lot just yet).


Review

A little ambiguous, and overly complex. You need to familiarize your self with radians and forget about degrees

Style

Block-less blocks

A block is a section of code delimited by {...} many C like syntax languages allow you to skip the block delimiters for single line blocks after conditional statements.

This can be a major source of life long frustration, and there is not a programmer alive that does not know the insidious nature of the bugs that can result when you make changes to the code and forget the {...}

// worst
if (foo === bar)
       foo = poo

// bad
if (foo === bar)
       foo = poo;

// better but be consistent never mix this with above
if (foo === bar) foo = poo;

// best
if (foo === bar) { foo = poo } // note that ; and } denote the end of
                                // an expression, you don't need to use both

// or
if (foo === bar) {
   foo = poo;
}

Constants

So many magic numbers. If you find your self adding the same numbers over and over it is a good sign that a defined constant is better. You never know when things may change. I.E. switch units from degrees to radians.

const A90  = 90;
const A180 = 180;
const A360 = 360;

Then if you want to change to radians

const A90  = Math.PI / 2;
const A180 = Math.PI;
const A360 = Math.PI * 2;

or clock angles

const A90  = 3;
const A180 = 6;
const A360 = 12;

No need to find each number in the code base.

Logic

The axis argument is ambiguous. Axis? is it the axis of reflection or the axis to reflex from. Also you use a string and to humans "x", "X" and "y", "Y" have the same meaning, but your code sees them differently, this is never a good thing. It would pay to check both (upper and lower) or convert to lowercase, or best use a defined constant,
Why are you using degrees, NO Math functions uses degrees, the only time you need to use degrees is for output, which generally is never needed. Learn to work in radians, it makes a lot of angle related maths so much easier.
The code is just too complex for something so simple. The problem is just one of negating the scalar associated with the direction of reflection. I.E. a vector has two scalars x,y if you reflect along X you negate x, if you reflex along Y you negate y.

Messing around with the cyclic angle is not needed. I have a general rule of thumb that if I ever find my self having to normalize a cyclic value E.G. (angle
% 360) I am doing it wrong and there is a better way.

Rewrite

This is how I would write the function. I would never use degrees, that is only ever needed for display only. That makes the function much simplier.

// defined axis names
const AXIS = {x : 0, y : 1}

// function computes the reflected angle
// rad Incoming angle in radians
// dir direction of reflection. Any of AXIS, defaults to AXIS.y
function reflectAngle(rad, dir) {
    return dir === AXIS.x ? Math.acos(-Math.cos(rad)) : Math.asin(-Math.sin(rad));
}

var reflected = reflectAngle(1, AXIS.x);

Update:

Sorry totally did not add the correct example!

As explained in point 3 (above) mirror x or y depending on which axis you are reflecting from.

function reflectAngle(rad, dir) {
    const c = Math.cos(rad), s = Math.sin(rad);
    return Math.atan2(...(dir === "X" ? [s, -c] : [-s, c]));
}


Merge both sql queries into one to get the performance

if we merge both queries & get the results in single query , then will it give better performance?

There are various aspects of performance here:

time
memory

My inclination is that you are leaning towards reducing time but maybe you mean memory or should at least consider it.

And consider that if the queries were merged into one, there are variables that would affect performance, including:

number of results
separation of data sets (i.e. display on-hold counts vs re-attempted counts in separate lists).

Generally it is best perform as few database queries as are necessary. If there were queries executed inside of a loop where data was selected based on a filter condition, it may make sense to perform one query and filter the data inside of the loop. But in this case, there are simply two similar but unique queries.

You didn't include the implementation for $db_handle->runSelectQuery() but the implementation might affect the answer as well. If that method uses a function to get all results at once (e.g. mysqli_fetch_all()) then it might be better for performance, but otherwise if it fetches results one at a time (e.g. using mysqli_fetch_all() until NULL is returned) then that might add a lot of overhead with looping over results in that method and then your code looping over the results for display purposes.

So in order to get a better answer, you must experiment with your data.

  if so how to merge ?

There are multiple ways to do this. One approach is to simply use UNION. The SQL for the second SELECT query can be appended after the first query and the keyword UNION.

$sql = "SELECT employeename, DATE(reattemptdate) as date,
COUNT(*) as count, 0 as Held FROM orders
WHERE DATE(reattemptdate)  = CURDATE()
GROUP BY employeename, date

UNION

SELECT employeename, DATE(holddate) as date,
COUNT(*) as count, 1 as Held  FROM orders
WHERE DATE(holddate)  = CURDATE()
GROUP BY employeename, date
";

Notice also that those queries have an extra field Held. A field like that can be used to separate the data. That way after the results are fetched, they can be separated into the re-attempted and the held results - perhaps using array_filter().

//formerly $results
$reattemptedResults = array_filter($results, function($result) {
    return $result['Held'] == 0;
});
//formerly $resultsa
$heldResults = array_filter($results, function($result) {
    return $result['Held'] == 1;
});

But keep in mind that this would be iterating over the results potentially 5 times- once to read rows from query results, once for each filtering and then once for each display (though it would be a subset), in that sense performance may actually be worse.

Another option is to use CASE in the queries to conditionally select and filter results:

$sql = "SELECT employeename, CASE WHEN DATE(reattemptdate)  = CURDATE() THEN DATE(reattemptdate) ELSE DATE(holddate) END as date,
COUNT(*) as count, CASE DATE(holddate) WHEN CURDATE() THEN 1 ELSE 0 END as Held
FROM orders
WHERE DATE(reattemptdate)  = CURDATE() OR  DATE(holddate)  = CURDATE()
GROUP BY employeename, date, Held";

And the data would still need to be filtered in PHP after the results are fetched. For small sets of data this likely won't be an issue but for large data sets it has a high potential. I suggest measuring the time with your data in both cases to see how the time compares. I tried it on a small set of data - one distinct employee name, two re-attempted orders and one held order on today's date. The query with CASE was slightly quicker than the original, even with two calls to  filter the data using array_filter().


Project Euler 8: find the maximum product of 13 consecutive digits

Disclaimer: my Forth is extremely rusty.

length does not need to be local; is not a variable, it is a constant. Declare it as such:
13 constant length

Dealing with input. The stack annotation ( a 1000 ) strongly hints that what follows wants to be the word on its own. Indeed, logic should be separated from IO. Consider, for example, something along the lines of
: e008 ( a n -- p)
    ....
;

s" 731671765313306249192...450"
euler008
.

Once the logic and IO are separated, you may use open-file and read-file if you wish.

I do not endorse one-liners, especially if they involve loop. Consider
: e008-multNdigits ( a n -- p )
    1 swap 0
    do
        swap
        dup i +
        c@ [char] 0 -
        rot *
    loop
    nip ;

As a side note, nip is very rarely useful, and usually it is an indication of the suboptimal design. Try to get rid of it. The nipped value, if I am not mistaken, is a base address of the array. I have an impression that its only purpose is to undo a dup in the caller. Try to get rid of both.

The line
  dup maxproduct > if to maxproduct else drop then

is a long way to say
  maxproduct max to maxproduct

Consider having max product at TOS prior to setting up a call to e008-multNdigits. In this case,
  length - 0 do
      dup i + length e008-multNdigits
      max

would suffice, and eliminate the need for the local.

Not Forth-related issues:

The algorithm performs 13000 multiplications. A sliding window approach lets you get away with 1000 multiplications and 1000 divisions. Of course an extra care should be taken when 0 is encountered.

The product of 13 digits may take as much as 42 bits. A naive multiplication fails on a 32-bit cells.

Finally, Project Euler is not about programming. It is about math. To hone your Forth skills, consider implementing classical algorithms, and benchmark them against conventional implementations.


Calculating multiple car prices from a file - follow-up

List<Company> trn = new ArrayList();

You're missing the <> (or <Company> if you're using JDK6 or below) on the right, which means the right side is a raw type and not a generic. Your IDE should be configured to warn you about this.

In addition, what does trn mean? It's completely unclear even from context. You should almost never use abbreviations unless they're industry-standard, and maybe not even then.

Map<String, BigDecimal> map = new HashMap();

This is also a raw type. Its name also tells me nothing. What are you mapping? A better name would be mapTotalPriceByFactoryName, or just totalPriceByFactoryName.

BigDecimal counter = new BigDecimal("0");

BigDecimal has a constant for this, BigDecimal.ZERO. Use it here and below.

for (Company c : trn) {

Another unnecessary abbreviation - call the loop variable company.

counter = new BigDecimal("0");

Is this actually a counter? It seems like a summation, and should be called something like totalPrice accordingly.

if (com.getName().equalsIgnoreCase(name)) {
    counter = counter.add(com.getPrice());
    if ((counter.compareTo(target)) == 1) {
        map.put(name, counter);
    }
}

This code is unclear to me. Why equalsIgnoreCase instead of just equals - do we expect the input file to be inconsistent with itself? That seems like an important caveat to call out in comments.

The behavior of the counter is also very unclear. You only want to store factories with a total price of at least 10000? It would be simpler to do the summation in one step, then filter out the unwanted factories in a subsequent step.

Set<String> set = map.keySet();
System.err.println(">>" + set.toString());

Here you never refer back to the values stored in the map. If you're not going to refer back to them, you might as well just use a List.

As an example, here's how I would store the prices:

Map<String, BigDecimal> map = new HashMap<>();
for (Company company : companies) {
    String name = company.getName();
    if (!map.containsKey(name)) {
        map.put(name, BigDecimal.ZERO);
    }

    BigDecimal totalPrice = map.get(name).add(company.getPrice());
    map.put(name, totalPrice);
}

This becomes an O(N) algorithm instead of the O(N^2) algorithm you're using currently. You can then post-process the map to filter out the companies you aren't interested in.


How Can I Improve/Secure My Login Script?

Rather than an else statement to set false on invalid username/password why not just default to false and only set to true if it worked. Also do you care unless both are valid?

$validUserAndPassword  = false;

if (CheckEmpty($_POST['username']) && CheckEmpty($_POST['password']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    $validUserAndPassword = true;
}

The DB is an expensive resources. There is no point in connecting to the DB or even getting stuff from the DB unless you have a valid username and password.

$ result = array();
if ($validUserAndPassword)
{
    AllYourBase();

    $query = mysql_query(sprintf("SELECT * FROM Users WHERE username = '%s'",
                mysql_real_escape_string($username))) or die(exit());
    $result = mysql_fetch_assoc($query);
}

I am pretty sure that splitting the salt provides little extra entropy.

// Split the Salt
$fs = substr($result['salt'], 0, 10);
$ls = substr($result['salt'], -10);

// Add The Salt
$pass = md5($fs.$password.$ls);

I think doing authentication your self is a bad idea (this is a specialized field with lots of gotchas). Anway don't you want to spend time on your application rather than doing mundane tasks like authentication?

I am not an expert on front-ends so I have no good recommendations on packages that can do it for you. But I did play around with openid-selector (available via google source), which is the same authentication package that the stack exchange sites use. This allows the users to login-in to your site using the open-id credentials (google/open-id/facebook/yahoo/stack-exchange)).


Yes there is a faster way! Your solution is \$O(n)\$, but a \$O(1)\$ (constant time) solution exists.

This is one of my favorite problems since you don't need a computer to solve it.

Triangular Numbers

The nth triangular number is a sum of integers from 1 to n. There are several proofs that show this sum is equivalent to (n + 1) * n / 2.

To get down to constant time, one needs to note that the sum of all multiples of 3 less than n is very similar to a triangular number. Here's a sum denoting what we want:

  3 + 6 + 9 + 12 + ... + 3*(n // 3)

Note the integer division //

If we factor a 3 out of this sum:

  3(1) + 3(2) + 3(3) + 3(4) + ... + 3(n//3)

We get three times a triangular number!

  3(1 + 2 + 3 + 4 + ... + n//3)

Which can be simplified down to:

  3 * ((n//3 + 1) * n//3 // 2)

The same can be done for 5 (or any natural number)

def sum_mul_less_than(m, n):
    return (m * (n//m + 1) * (n//m)) // 2

Now we add the multiples of three and five and subtract the extra set of multiples of 15 (I like how clever the break was in your code for this).

def getmul_3_5(n): # this solution is harder to generalize for any multiple
    n -= 1 # we don't want to include n
    s = 0
    s += sum_mul_less_than(3, n)
    s += sum_mul_less_than(5, n)
    s -= sum_mul_less_than(15, n)
    return s

Constant time is INCREDIBLY faster than linear time, \$O(n)\$. This solution can handle astronomically large inputs bigger than 10**30 even.

Edit: General case

Assuming the list of multiples could be of any size, you should get rid of the unpacking argument list operator since it's less convenient to users. I came up with a solution that is \$O(2^m)\$ where m is the number of multiples. Your solution is \$O(nm)\$ which would be asymptotically faster around \$n < 2^{m-1}\$, so you could fine tune this line and use the strategy pattern to pick the faster algorithm on a case by case basis.

First I removed all of the redundant multiples, (e.g. 4 if 2 is in m since any number divisible by 4 is already counted by 2). Then I found every possible multiple combination of the numbers in m.

Combinations with odd lengths are added; combinations with even lengths are subtracted (the inclusion exclusion principle as noted by user Gareth Rees).

from itertools import combinations
from functools import reduce

def geo(nums):
    '''Multiply a list of numbers together'''
    return reduce(lambda x, y: x*y, nums)

def getmul(n, args):
    n -= 1
    s = 0

    # removing the redundant multiples from args is left as an excercise
    # O(m^2)

    # there are 2^len(args) combinations of args
    for i in range(1, len(args) + 1):
        for c in combinations(args, i):
            if i % 2 == 1:
                s += sum_mul_less_than(geo(c), n)
            else:
                s -= sum_mul_less_than(geo(c), n)
    return s


Firstly you might want to make use of a Haskell feature to combine both functions into one:
unique :: Eq a => [a] -> [a]
unique [] = []
unique xs = [x | (x,y) <- zip xs [0..], x `notElem` (take y xs)]

Now let's talk about performance.  Obviously lists aren't great in this
respect, since take is quite expensive and needs to iterate through
the list, as well as notElem, which will, again iterate through the
list.  Plus this is also constructing new lists, which leads to GC,
which leads to decreased performance.
So best option would be to go through the list only once, putting each
element into a set while it's then only collecting the elements which
haven't been in the set yet at that moment.
That's of course a very imperative way of doing it.  And regardless, if
you're not allowed to use imports you'd have to create the respective
data structures yourself, which I'd say isn't worth the effort.

In any case, at least within the constraints set it's still possible to
make this a bit more
efficient, basically by
copying
nub's
implementation:
unique :: Eq a => [a] -> [a]
unique l = unique' l []
  where
    unique' [] _ = []
    unique' (x:xs) ls
           | x `elem` xs = unique' xs ls
           | otherwise   = x : unique' xs (x:ls)


The Rust Programming Language Pig Latin Exercise

Be aware that Rust typically uses 4 spaces
It's fine if you consistently use 2 spaces (especially if you override it in rustfmt.toml), but just be aware that the standard is different.
Collect directly to a String
Instead of collecting to a Vec and then copying that over to a new Vec (within String), collect to a String directly:
pub fn translate(s: &str) -> String {
    s.split_word_bounds().map(translate_word).collect()
}

Use Chars::as_str
When you use str::chars, the specific iterator that it returns is called Chars. It has a handy function to get the remaining part, so you don't need to allocate a new string:
'a'..='z' => format!("{}-{}ay", it.as_str(), first),

Use Cow
This is a bit of an advanced optimization that you don't need to do—the Book doesn't even mention it once.
Currently, you allocate a new String even when the output is identical to the input. Instead, return Cow<str>: if the first character isn't a letter, you can return Cow::Borrowed(s), which points to the existing &str. If it does start with a letter, return Cow::Owned(format!(...)), which has the same overhead as it did before. Here, I'm using .into() instead of writing Cow::Owned and Cow::Borrowed explicitly. You can do either.
fn translate_word(s: &str) -> Cow<str> {
    let mut it = s.chars();
    let first = it.next().unwrap();
    match first.to_ascii_lowercase() {
        'a' | 'e' | 'i' | 'o' | 'u' => format!("{}-hay", s).into(),
        'a'..='z' => format!("{}-{}ay", it.as_str(), first).into(),
        _ => s.into(),
    }
}

Final code
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=78daca7b7adab4587436cacf35bca90e


Robustness of this first difference function

Rustfmt is a tool for automatically formatting Rust code to the community-accepted style. Specifically, the { after the where should come on the next line.
Accept a &[T] instead of a &Vec<T>.

use std::ops::Sub;

fn first_difference<T>(input: &[T]) -> Vec<T::Output>
    where T: Sub<Output = T> + Clone
{
    let vec_len = input.len();

    input.iter()
        .take(vec_len - 1)
        .enumerate()
        .map(|(ind, val)| val.clone() - input[ind + 1].clone())
        .collect()
}

fn main() {
    println!("{:?}", first_difference(&[1, 3, 1]));
}

However, this code will panic if presented with an empty input slice because it tries to subtract 1 from 0. This can be addressed by using some iterator adapters:

fn first_difference<T>(input: &[T]) -> Vec<T::Output>
    where T: Sub<Output = T> + Clone
{
    let a = input.iter();
    let b = input.iter().skip(1);

    a.zip(b).map(|(a, b)| a.clone() - b.clone()).collect()
}

The Clone requirement is a little sad to have. You could adjust the bounds to work directly on references. This uses higher-ranked trait bounds (for <'a>):

fn first_difference<T>(input: &[T]) -> Vec<T>
    where for <'a> &'a T: Sub<Output = T>
{
    let a = input.iter();
    let b = input.iter().skip(1);

    a.zip(b).map(|(a, b)| a - b).collect()
}

I think the biggest "weakness" to the function is not one of its own. In Rust, subtraction may panic in certain cases. Specifically, when you exceed the range of the type, the compiler may abort the program. This can be controlled by the programmer, depending on the constraints of the problem at hand .

  Why doesn't the compiler complain about that lifetime specifier being
  undefined? The Rustonomicon says

    for<'a> can be read as "for all choices of 'a", and basically produces an infinite list of trait bounds that F must satisfy.
    Intense.

  which I agree is intense, but doesn't seem to tell me what the
  lifetime is. Is it the lifetime of F, or is it bounded in some other
  way externally?

for <'a> declares a new generic lifetime, that's why there's no compilation error. The quote from the Nomicon is fairly literal (as far as it can be) — the restriction in the where clause here is "any possible reference to a T needs to be able to be subtracted from another reference to a T. Those two references will share a unified lifetime 'a and the result of the subtraction will produce a T".

It's certainly a mouthful, but it's not impossible to understand once you've seen it a few times.

Specifically, the concrete lifetime will be the same as the incoming slice. This means I was probably being a over-clever, and the code could have been written as:

fn first_difference<'a, T>(input: &'a [T]) -> Vec<T>
    where &'a T: Sub<Output = T>
{
    let a = input.iter();
    let b = input.iter().skip(1);

    a.zip(b).map(|(a, b)| a - b).collect()
}


Not much to comment on the permutation, but generally speaking you should use try-with-resources, Files.lines() and a healthy dose of Java 8 features for your main() method:

public static void main(String[] args) throws FileNotFoundException {
    try(Stream<String> lines = Files.lines(Paths.get(args[0]))) {
        lines.map(PermutateString::sortString)
                .map(PermutateString::permutateString)
                .forEach(System.out::println);
    } catch (IOException e) {
        // do something with this, e.g. show file not found message?
    }
}

Please check the use of Paths.get() for your case too...


However, i would like to optimize the loop condition.
  Currently 3 operations are done. What can I do to speed it up?

Instead of checking for every position if it's within the bounds of both strings,
you could save the lowest bound using Math.min and use that as the loop condition.
That will cut down one comparison.

  Can anyone suggest a more elegant solution?

The last condition checking destLength !=  sourceLength can be omitted,
you can simply add the value of Math.abs because it will give 0 if the lengths are the same.
The result will be shorter code, which may be slightly more readable.

To make the code look more elegant,
it would be good to follow the common coding style.
For example instead of this:

    for ( int i=0 ;i < sourceLength && i < destLength ; i++){

Write like this:

    for (int i = 0; i < sourceLength && i < destLength; i++) {

I use my IDE to correct the formatting. It's a matter of a few key strokes.

It goes without saying that you should remove auto-generated lines like this:

    // TODO Auto-generated method stub

The revised implementation incorporating the above points (and a point from @user1016274 too):

public static int getEditDistance(String sourceString, String destinationString) {
    if (sourceString == null || destinationString == null){
        throw new IllegalArgumentException("String cannot be null");
    }

    int sourceLength = sourceString.length();
    int destLength = destinationString.length();
    int len = Math.min(sourceLength, destLength);

    int distance = Math.abs(sourceLength - destLength);
    for (int i = 0; i < len; ++i) {
        if (sourceString.charAt(i) != destinationString.charAt(i)) {
            ++distance;
        }
    }

    return distance;
}

I would also recommend to add some unit tests to verify the algorithm is working:

@Test
public void test_coti_cat() {
    assertEquals(2, EditDistance.getEditDistance("coti", "cat"));
}

@Test
public void test_alpha_beta() {
    assertEquals(5, EditDistance.getEditDistance("alpha", "beta"));
}

@Test
public void test_beta_pedal() {
    assertEquals(3, EditDistance.getEditDistance("beta", "pedal"));
}

@Test
public void test_empty() {
    assertEquals(3, EditDistance.getEditDistance("", "123"));
}


Your code looks good, except that you do not really need the c, and hence the nesting, in the list comprehension. You can use line[i:i+7] directly in int, making it a bit shorter:

''.join([chr(int(line[i:i+7], 2)) for i in range(0, len(line), 7)])

However, just removing the 1000001 in the line before seems a bit arbitrary, since (a) the pattern might also be present within a package, spanning two bytes. Instead, you could keep the c variable and ignore the current c if it equals the package delimiter:

>>> line = "10000011100010110111111011111000001100000101000011000001"
>>> ''.join([chr(int(c, 2)) for c in (line[i:i+7] for i in range(0, len(line), 7)) if c != "1000001"])
'boo!'

But, you still lose the information where the packages start and end.
Instead, you could use regular expressions for first detecting the packages, and then finding the bytes within those:

>>> p = r"1000001((?:[01]{7}){,3})1000001"
>>> re.findall(p, line)
['110001011011111101111', '0100001']

Here, p means "package delimiter, followed by up to three groups of seven 0 or 1, followed by delimiter. Then you can use another regex q to split those into bytes.

>>> q = r"[01]{7}"
>>> [''.join(chr(int(x, 2)) for x in re.findall(q, y)) for y in re.findall(p, line)]
['boo', '!']

Of course, the regex q is a bit redundant, since we already checked the same in p. You could also do this part using a range and string slicing, but personally I still find the regex approach cleaner.

>>> [''.join(chr(int(y[i:i+7], 2)) for i in range(0, len(y), 7)) for y in r e.findall(p, bits)]
['boo', '!']

Another way, without regex, might be to first separate the line into groups of 7 bits, and then using itertools.groupby to group those parts into package-delimiter and package-contents:

>>> parts = [line[i:i+7] for i in range(0, len(line), 7)]
>>> groups = [list(g) for k, g in groupby(parts, key="1000001".__ne__) if k]
>>> [''.join(chr(int(b, 2)) for b in g) for g in groups]
['boo', '!']


Two advices:

Use PHP alternative syntax

When mixing HTML and PHP, it is a good practice to use  PHP alternative syntax:

<?php for ($i = 1; $i <= 3; $i++): ?>
..
<?php endfor ?>

Improve the HTML code

Use double quotes in tag attributes (HTML standard)
Try to respect indentation
Move style to css declarations

Final code proposition:

<?php for ($i = 1; $i <= 3; $i++): ?>
  <div <?php echo $i < 3 ? ' class="lt3"' : '' ?>
    <label for="param_kind<?php echo $i ?>"><?php echo $i ?>. Kind
    <select id="param_kind<?php echo $i ?>" class="selFields" name="param_kind<?php echo $i ?>">
      <option value="-1">--- </option>
      <?php for ($j = 1; $j <= 16; $j++): ?>
      <option value=""<?php echo $j ?>"<?php echo $oRecherche->getParamValue("param_kind$i") == $j ? ' selected="selected"' : '' ?>><?php echo $j == 1 ? "&lt; 2 Jah." : $j + "Jahre" ?></option>
      <?php endfor ?>
    </select>

<?php endfor ?>


You can just use concat and splice..

shift %= array.length;
array = array.concat(array.splice(0,shift));

Or if you want the same array referance you can shift and push

for(i = 0; i < shift; i ++){
   var item = array.shift();
   array.push(item);
}

or shorten to

while((shift--) > 0){
   array.push(array.shift());
}


Find number of horizontal brush strokes to paint a skyline

With every height drop by 1 point, a line ends. So you just need to calculate the sum of height drops. Don't forget to account for the last height. You could also do the same thing from the other end (every height increase starts a line).

def skyline(heights):
  diffs = [e1 - e2 for e1, e2 in zip(heights, heights[1:])]
  return sum(diff for diff in diffs if diff > 0) + heights[-1]

Some remarks on your code:

copy = [a for a in A] can be rewritten as copy = A.copy()
some parentheses in (copy[i] > 0) and ((i+1 == len(copy)) or (copy[i+1] == 0)) can be omitted:

if copy[i] > 0 and (i+1 == len(copy) or copy[i+1] == 0):
you can use enumerate in the for loop:

for i, elem in enumerate(copy):
  if elem > 0 and (i+1 == len(copy) or copy[i+1] == 0):
    strokes += 1
  if elem > 0:
    copy[i] -= 1

the ifs can be merged:

for i, elem in enumerate(copy):
  if elem > 0:
    copy[i] -= 1
    if i+1 == len(copy) or copy[i+1] == 0:
      strokes += 1


A multi-threaded key-value cache that only has thread contention while querying for same key simultaneously

I'm working on similar thing at the moment. So my thoughts are that you might use most popular EhCache in order to keep something you already have.
  ehCache.get(key) -> if its there, you return, if it's not there, we call provider.
  When we call provider - we need to wait for response, so I'm thinking about something like
 Question about your data provider - can you have parallel calls? Do you have some throttling there? If so, you could have some concurrent map for calls to store responses for keys. Once API is done you might store response in Ehcache so you have that for future.
 I think EhCache is better than just concurrent map for "caching" because you might define amount of entities, eliminate them, have a disk-backed cache, etc.


Use int rather than Int32
You can write an inline expression rather than a multi-line statement

I would prefer to write an extension method here to wrap this method:

public static class IntExtension
{
    public static int ToInt32OrDefault(this string value,int defaultValue=0)
    {
        int result;
        return int.TryParse(value, out result) ? result : defaultValue;
    }
}


The Javadoc style headers you have provided for this method are already more than enough. If you are adding comments to your method it should only be either for API documentation, or where the code is sufficiently complex to warrant an explanation that you cannot provide by simplifying or more appropriately naming the variables.

You should however make it clear that your method throws these two exceptions by including them in the method definition, e.g.

public static String insertCharAt(String str, char ch, int index) throws NullPointerException, IndexOutOfBoundsException

This way it will be obvious from reading the method definition that these exceptions can be thrown, and your comment will be unnecessary when we read the line above each exception-throwing statement and see the logic that causes it to be thrown.

In general, if your comment is telling us nothing more than what the code already does, make your code as simple and readable as possible and delete the comment. At best it will add noise to the code file and at worst it will get out of sync with the code and become misleading.
In this example, presumably prefer to use a checked exception so that the method calling insertCharAt and can catch these exceptions and handle them in some way. See also https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions
This depends what you mean by more reliable. Do you mean robust in regards error cases?
This also depends on what you mean by more scalable. What do you mean?
This method is very simple and there isn't a great deal of room for performance improvement that I can see.

Edit:
This method is thread safe as it does not modify any parameters passed to it (and strings are immutable anyway) and does not modify any class-local variables. Even if you had assigned the return value to a temporary variable before returning it, it would not be shared between threads as method level variables belong to each thread's stack.


ActiveRecord model for users who have issues or who assist with issues

The foreign key is not needed for belongs_to :creator since rails will infer this foreign key from the association name. The source has to point to the relation for UserIssue (you pluralized this name but active record class names should be singularized in most cases) so instead of source: users, and source: issues, you want source: user, source: issue.

Another way you could have accomplished the same thing, which IMO is a bit cleaner is the following:

class Issue < ActiveRecord::Base
  belongs_to :creator, class_name: 'User'
  has_many :helpings, :foreign_key => 'issue_helped_id'
  has_many :helpers, through: :helpings
end

class User < ActiveRecord::Base
  has_many :issues, foreign_key: 'creator_id'
  has_many :helpings, foreign_key: 'helper_id'
  has_many :issues_helped, through: :helpings
end

class Helping < ActiveRecord::Base
  belongs_to :helper, class_name: 'User'
  belongs_to :issue_helped, class_name: 'Issue'
end

It also gives the join table a more descriptive name. For this to work you need to modify your inflections since rails cannot pluralize issue_helped or singularize issues_helped out of the box. To do this, in config/initializers/inflections.rb add:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.plural 'issue_helped', 'issues_helped'
  inflect.singular 'issues_helped', 'issue_helped'
end


Turning multiple PHP arrays into one array ready for conversion to Javascript

Running a SQL statement in a loop is in general a bad idea. Depending on your $questionsrow you might send a lot of not needed requests.

In relation to MECUs hint you could use something like:

$questions=array();
//add constrains to select only some questions or sort the answers
$result=...query($db_handle, "SELECT * FROM answer");
while ($row=...fetch_array($result))
{
    $qid=$row['questionid'];
    if (!isset($questions[$qid])) =array(); //create subarray if new question
    $questions[$qid][]=$row //append a new element to the question array
}
$json=json_encode($questions);

I.e. $questions[1] will contain a array with all your answers to question 1. The sorting of the answers can be moved to SQL query, also if you don't need all fields you can restrict this in the SQL and don't need to take care of this in your PHP.


Sampling from a distribution with given probabilities

Just a suggestion:

I think you can use better variable names than pp and q.

cdf can be clonedArray, and the same for other variable names.

This doesn't matter so much but increases the readability of the program.


JQGrid with dynamic columns and server-side functionality

Small recommendations:

It seems to me that you can remove async: false parameter for the $.ajax call.
You can remove result.data from the data returned by the ajax call. (After that you should and the line with var colD = result.data). The data will be not really used because you call trigger('reloadGrid'); immediately.
On the other side the values for sortname and sortorder parameters should be included in the data model (as the properties of result).
You can use url: secondFetchURL, datatype: 'json', mtype: 'POST' parameters directly in the jqGrid definition ( in $("#myGrid").jqGrid({/*here*/});. No trigger('reloadGrid') will be needed.

UPDATED: Look at this and this answers. Probably the approach is what you need from the dynamic columns.

You can take a look in the answer in case if you will need to use custom formatters.


std::atoi() is a poor choice of conversion function, as its means of reporting errors is indistinguishable from a valid conversion.  The necessary header hasn't been included anyway.
uint8_t is not declared - did you mean std::uint8_t from <cstdint>?  Similarly, you probably meant to include <cstdio> for std::printf, and <iostream> isn't used.
The repeated calculations during the division of seconds into days, hours, minutes and seconds should be simplified.  I'd go with something like
auto seconds = now % 60;
auto minutes = now / 60;
auto hours = minutes / 60;
auto days = hours / 24;
minutes %= 60;
hours %= 24;

Perhaps even consider making a class for mixed base arithmetic.
The calculation of leap years is flawed, because it gives 100 leap years per 400 years, rather than the 97 expected.
Instead of looping over months, it might be better to keep an array of the start of month as Julian day, so we can use a straightforward binary search to identify the month number and day within month.
Calendrical calculations are often easier if we use a year beginning on the 1st of March for computation (so that leap day is the last day in year), then convert January/February dates to the correct year as a final step.
I'd encourage the use of a function (perhaps with the same signature as std::gmtime()) rather than shoving everything directly into main().
return 0; can be omitted from the end of main() .


I figured out that this assignment could be rephrased as a vectorized multiplication which eliminates the need for a for-loop and costly indexing of individual groups of elements.

import matplotlib.pyplot as plt
import numpy as np
import ipdb

# constants
t_len = 0.5
freq = 10.0
dt = 0.001

# set the see for reproducible results
rng = np.random.RandomState(0)

# create the random values to interpolate between
assert dt < freq
white_size = int(t_len * freq)
white_vals = np.random.uniform(low=-1, high=1, size=white_size)

# do the interpolation
tot_size = int(t_len / dt)
step_size = int(1 / freq / dt)
n_shape = (white_size, step_size)
white_noise = (white_vals[:, None] * np.ones(n_shape)).reshape(tot_size)

assert white_vals.shape[0] < white_noise.shape[0]

# plot the result for visual verificaition
plt.plot(white_noise)
plt.show()


Triangle calculator: calculate if it's a valid triangle and what type

Bug
Your code assumes that the user will enter the longest side last! This is a bug. Id the user enters the values 10, 1, and 1, it will declare that it is a triangle because 10 + 1 > 1
Functions!
Where are your functions?
One of the best ways to document your code, and make sense of it, is to have well-named functions. Your function is main, and.... well, that does not do a good job of telling us what the function does.
What you need is a function called something like boolean isValidTriangle(int sideA, int sideB, int sideC), then make that function "work".
A valid triangle is one whose shorter sides add up to more than the longest side, right? The trick is finding the longest side.... In this case, recursion is a trick that can help....
boolean isValidTriangle(int sideA, int sideB, int sideC) {

    // recursion trick, make sure sideA is the longest side!

    if (sideA < sideB) {
        // call the function with sideB first
        return isValidTriangle(sideB, sideA, sideC)
    }

    if (sideA < sideC) {
        // call the function wwith sideC first
        return isValidTriange(sideC, sideB, sideA)
    }

    // OK, sideA is the longest, for sure!
    return sideA <= sideB + sideC

}

Similarly, you can do the same sort of thing to classify the triangle types.


Next, greater permutation of digits of a number

This is a great question with deep implications imo.  And I think the correct answer is that there is no good answer.
I managed some minor cleanup which is almost not worth posting:
def next_greater_permutation(integer)
  digits = integer.to_s.chars
  k = digits.each_cons(2).to_a.rindex { |a, b| a < b }
  return integer if k.nil?

  l = digits.rindex { |n| digits[k] < n }
  digits[k], digits[l] = digits[l], digits[k]
  [digits[0..k], digits[k+1..-1].reverse].join.to_i
end

But when you say "I'm used to array-manipulation in Ruby being a matter of finding the right methods and chaining them," what you are saying is that ruby code -- and this applies to functional code in general -- looks pleasing and natural when the problem you're solving can be modeled as a series of successive data transformations.
In the case of an array, that means a series of transformations of the array which require no additional temporary variables.  When you do need temporary variables, the solution starts to get uglier, even if you try to paper over the fact by hiding your variables in the accumulator of the faux-functional method reduce (or something similar).
From this perspective, I think it becomes clear that the algorithm you're implementing is by nature procedural, and there is no way around those k and l temporary variables (certainly not k).  In fact, I suspect (but don't know) that there might even be a way to make this intuition rigorous.
Of course, you could imagine a standard library (or a monkey patched one) which provided additional array methods like swap(i,j) and reverse_after(i) that would make this solution prettier.  But again, you'd still be stuck with what is truly making you uneasy imo -- the need of k and l.
So, my non-answer to your question is that, at bottom, this question is unanswerable -- that is, minor improvements may be possible, but not a fundamental one.
UPDATE
Thinking about this more, I just wanted to elaborate on what I see as the larger problem posed by this question -- that is, what categories of problem cannot be solved cleanly with a functional pipeline.
I think it's worth pointing out that this problem can be solved with a pipeline, although probably not with the built-in ruby functional constructs.  Essentially, you need to transform the data, and then pass both the result of that transformation and the original data down the pipe, to functions of more than one argument.  In the J language, forks and hooks provide this mechanism in an elegant way.  But even then, you'd still be passing your k value down multiple steps of the pipe, and at that point you've simply implemented a local temporary variable through a pipe.  And I don't think you've gained anything in readability -- in fact, you've probably lost something.  Indeed, you can view the lines of a  procedural program as steps in a pipe each of which have access to the results of every calculation above them.
So I think the general lesson here may be something like: If you need to use the result of a calculation in multiple places in a sequence of functions, then a procedural solution is probably going to be less verbose and more readable than a purely functional one, unless you're using a language like J with special constructs for this -- and even then it might be a draw.
The only question that remains would be: Is there some clever equivalent version of this algorithm which wouldn't require the use of temporary variables or their equivalent?  I'd still guess the answer is no.


I don't know why you would want to shorten your code. It is already just 73 lines long (including the final blank line). Apart from that, "short" does not automatically mean "good". Maybe concise would be a better fit here, which I would interpret as "the code does what it should do without clutter". IMHO your code is very concise and readable at the moment and that should not be sacrificed to gain a few lines/bytes. We're not at Code Golf here.

Nevertheless, there are a few things you can improve easily.

Documentation

Python's official Style Guide has recommendations on how to comment code and functions. Function docstrings should always be defined inside the function body and be surrounded by triple quotes """...""". Applying this to your code it would look something like

def get_input(response, values):
    """make sure the input is in the choices"""
    # your code here

This will also allow Python's built-in help(...) function and most IDEs to pick up the documentation.

Avoid globals

You should always strive to avoid global variables whenever possible. E.g. in your code colors is not used outside of main() and should therefore be defined there. drawing does not seem to be used anywhere, so you might be able to drop it completely. LINE1 and LINE2 are two valid uses for globals. My only recommendation here would be to put them on two separate lines. Oh, and strictly speaking your comment on them is "wrong" since they are not used as variables but as constants, which is also supported by the ALL_CAPS_NAME (the Style Guide also says something on that).

Variable names

There is this piece of code which I find kind of amusing:

#rt = right turn
rt = random.uniform(100, 300)

Why not just call the variable right_turn or right_turn_angle right away then? The same reasoning would apply to fd, but you didn't care to write the comment there and left it as an exercise to the person looking at your code to find out that it actually stands for forward. You could also rename size to mandala_scale or so and then drop that #universal variables altogether since it does not really help to understand the code better. At least at the moment you could even get rid of size completely since its only use is to be multiplied by 75 on the next line and it's never used after that.

Other aspects

There is a lot of repetition when it comes to the list of available colors. Including the print, you define them four times. If you ever decide to add, change or remove a color from that list, there would be four places that change would need to be applied to. I would recommend to define them in one place, and reuse the list wherever it is needed.

# ...

colors = []
all_colors = ("darkred", "red", "yellow", "darkgreen", "green", "lightgreen", "darkblue", "blue", "purple")
if answer == "random":
    colors.extend(all_colors)
    right_turn = random.uniform(100, 300)

elif answer == "custom":
    all_colors_string = ", ".join(all_colors)[:-2] # -2 to trim of the trailing space and ,
    print(LINE2 + "\nYou can choose any colors from this list for your Mandala: \n" + all_colors_string)
    color1 = get_input("What is the first color? ", all_colors)
    color2 = get_input("What is the second color? ", all_colors)

# ...

In the transformation the set notation ({...}) got lost, but I think your application will not really suffer from the (minuscule) performance impact because a tuple is used instead of a set.

Another handy feature I would like to point out to you is string formatting. So what's that? Let's look at an example from your code:

print("[...] or have the computer generate a random one,", name, ".\n" + LINE2)

Here you are using Python's implicit behavior to print the elements of a tuple separated by whitespace1. That leads to the following output (minus the annotation of course):

[...] or have the computer generate a random one, Alex .
~~~~~~~~~~~~~~~~~~~~~~~~
                                       does look off ~^

Note the unwanted whitespace between the name and the dot?
But we can do better! Python has very powerful string formatting capabilities (doc), and since you have tagged your question as Python 3, you can likely use the new f-string syntax (helpful blog post comparing all the different ways, specification (PEP 498)).
Rewriting the code from above using an f-string would lead to:

print(f"[...] or have the computer generate a random one, {name}.\n" + LINE2)

So f"... {name}" basically generates a string containing the value of name right at the spot we the curly braces and the name of the variable where.2 For the sake of completeness that generates the following output:

[...] or have the computer generate a random one, Alex.
~~~~~~~~~~~~~~~~~~~~~~~~

As a final note, you could/should also add

if __name__ == "__main__":
    main()

(explanation) to highlight what part of the code is actually run if this file is used as Python script.

Bonus: by removing unnecessary globals and comments your script is actually even shorter more concise now, although that was not the main goal of what I was trying to tell you.

1 Depending on your Python experience you might wonder where there is a tuple in that line or you will nod silently. In the first case I would recommend reading this SO post on how Python deals with functions that have a variable number of arguments (often varargs for short), and then to have a look at how the print function is defined in the documentation.
2 In fact, f-strings are way more powerful than this, but you should refer to the resources linked earlier if you want to know more.


If you had tagged this code as C, it would have been acceptable. Since you tagged it as C++, it's horrible.

Instead of writing your own swap function, there's already std::swap in <algorithm>.

Instead of writing bubble sort yourself, just use std::sort, also from <algorithm>.

Instead of using arrays and resizing them yourself, just use std::vector<int>, from <vector>.

After applying these transformations, you cannot have a dangling pointer anymore since your code is completely pointer-free.

As part of an exercise for learning the basic operations on memory management, it's ok to write code like this, but never ever use such code in production. In production the code should look like this:

#include <algorithm>
#include <iostream>
#include <vector>

void Print(const std::vector<int> &nums)
{
    for(int num : nums)
    {
        std::cout << " " << num;
    }
    std::cout << "\n";
}

int main()
{
    std::vector<int> nums { 5, 7, 3, 1 };

    // There's probably a more elegant way to add the elements to the vector.
    nums.push_back(4);
    nums.push_back(2);
    nums.push_back(8);

    std::sort(nums.begin(), nums.end());

    Print(nums);
}

By the way, your original code doesn't have any dangling pointer as well. Well done.

You don't need the != NULL check before the delete[] since that pointer cannot be null. In modern C++ (since C++11 I think) you would also write nullptr instead of NULL. The reason is that historically NULL had not been guaranteed to be of pointer type.

Have a look at https://en.cppreference.com/w/cpp/algorithm for more algorithms that you shouldn't implement yourself in C++.

I would have liked to write the push_back block in a shorter way, as well as the Print function. I'm sure there's a more elegant way, I just don't know it.


First, since you already did so inside of your two last expressions, with the same replacement:

article = article.replace(/\r?\n|\r/g,"")
article = article.replace(/\$|\#|\[|\]/g, "")

I'm puzzled why you didn't simply put both in a unique regexp:

article = article.replace(/\r?\n|\r|\$|\#|\[|\]/g, "")

Then to integrate with the 1st one, you might choose to:

join the two distincts replacements in a single line:

var article = a.replace(/ |\./g, "_").replace(/\r?\n|\r|\$|\#|\[|\]/g, "")

or use a map approach, either suche the one pointed by @greybeard's link, or like this way (even if it might look a bit too sohpisticated for only two cases):

var replacements = new Map([
    [/ |\./g, '_'],
    [/\r?\n|\r|\$|\#|\[|\]/g, '']
    ]),
    article = a;
replacements.forEach(function(value, key){
      article = article.replace(key, value);
    });

The most interesting aspect in this latter solution is that it may be easily expanded if more replacements are needed.

EDIT following a good suggestion from @Niet the Dark Absol.

As soon as there are several unique characters to look for, with the same replacement, this kind of regexp /(a|b|c)/ can be replaced by /[abc]/, which is both simpler and more efficient!

Any of the above proposed solutions can be improved this way, so the latter one becomes:

    var replacements = new Map([
        [/[ .]/g, '_'],
        [/[\r\n$#[\]]/g, '']
        ]),
        article = a;
    replacements.forEach(function(value, key){
          article = article.replace(key, value);
        });