Don't use relative import paths.

Such as "../stack".
Instead, use full import paths like
(e.g.) "github.com/kyranstar/RPN/stack".
That would be a reasonable path to use if you put your source somewhere like
$GOPATH/github.com/kyranstar/some-repo-name/, since you're a GitHub user.
This is discussed in How to write Go code.

So for example:

$GOPATH/src/github.com
└── kyranstar
    └── RPN
        ├── calculator
        │   ├── calculator.go
        │   └── calculator_test.go
        └── stack
            ├── stack.go
            └── stack_test.go

Note that you can do this even if you never have any intention of making this available on github.
In that case you'd just be using "github.com/kyranstar" as a convient prefix
that won't conflict with anyone else
(e.g. I use "bitbucket.org/myname/…", "github.com/myname/…", and "myname-test/…" as Go import prefixes depending on what I'm doing).

You didn't include anything to build a run-able command.
If you're fine with just go testing your packages, you don't need to.
But if you want to build a standalone non-test program you could either
put a simple package main right in …/kyranstar/RPN/anyname.go
or if the repo might have multiple commands to build, in …/kyranstar/RPN/cmd/name-of-command/anyname.go.
In either case, go build and go install will use the base name of the containing directory as the executable name.

Run go fmt (or gofmt, or goimports) on all your Go source.

On your source the changes it makes includes removing extraneous parenthesizes,
it's idiomatic to use if x { rather than if(x) {.

Slices vs arrays and your stack package.

It's usually better to use slices rather than fixed sizes arrays (like you do in stack.go)
unless you actually have a fixed size (e.g. perhaps type CoordinateVector [3]float64).

Then stack can become just something like:

package stack

type Stack []int

func (s Stack) Len() int    { return len(s) }
func (s *Stack) Push(i int) { *s = append(*s, i) }
func (s *Stack) Pop() int {
        n := len(*s) - 1
        v := (*s)[n]
        *s = (*s)[:n]
        return v
}

Note, Len() is more common/idiomatic than Size()
(and gorename
can help rename such things for you including all references anywhere in your $GOPATH).
This doesn't have a fixed size like yours does at the slight expense
of re-allocations as it grows.

Note that naming a package stack with a single type Stack causes code using it to stutter,
e.g. s := new(stack.Stack).
There is a blog entry about Package names that addresses this.
For example, perhaps such a stack package could have several types like Int, Int64, Float64, etc
and then callers would use stack.Int, stack.Int64, stack.Float64, etc.

Alternatively, the changed package becomes so small that it is common to just stick it into a stack.go
file in the current (calculator in this case) package and use it as a non-exported package type.

Finally, where you use this you have stack := new(stack.Stack).
Note that you are creating a local variable which shadows the import name.
You've made it difficult/impossible to use anything from the stack package anywhere else in the function
(e.g. to make a second stack for any reason).
If for no other reason then to prevent confusion in people reading the code, it's usually best to avoid such
things.

Strings by byte or rune.

Again there is a blog entry that covers this:
Strings, bytes, runes and characters in Go.

You have:

    for i := 0; i < len(input); i++ {
            c := rune(input[i])

this loops by bytes instead of by Unicode code points (called runes in Go).
This should normally be:

    for i, c := range input {

But then it iterferes with your parseNumber usage.
Sadly, strconv doesn't appear to have a function that will parse
out a number from the start of a string and tell you how many bytes/runes
were parsed.
Since you're only handling digits (and not decimal, negatives, floating point, etc)
it'd be pretty use to just make parseNumber such a function.

Return error, don't panic!

You should never panic out of a package for anything other than
critical unrecoverable programming errors.
(For example, the above Stack.Pop will just panic if the caller
miss-uses the stack, it's up to the caller to check Len if they need to.)
You should instead do something like this:

func Calculate(input string) (int, error) {
        // …
        if stack.len() != 1 {
                return 0, errors.New("did not fully simplify")
        }
        return stack.Pop(), nil
}

Note that it's recomended that error strings should not be capitalized
or end in punctuation.
golint
can help catch such things.

Testing

Instead of:

        t.Log("something")
        t.Fail()

Use t.Error
and/or t.Errorf.

Use a slice instead of a map for testcase data.
A map isn't needed, and it's unordered.
You don't show what input caused the failure which makes it
harder than needed for someone fixing a problem down the road.
You don't test failure cases
(see Go's testing coverage to see what your tests are missing).

So something like this perhaps:

func TestCalculate(t *testing.T) {
        tests := []struct {
                in  string
                out int
        }{
                {"3 4 +", 7},
                {"3 4 -", -1},
                {"3 4 *", 12},
                {"3 4 /", 0},
                {"1 1 + 2 -", 0},
                {"5 10 * 2 /", 25},
        }
        for _, d := range tests {
                result, err := Calculate(d.in)
                if err != nil {
                        t.Errorf("Calculate(%q) failed: %v", d.in, err)
                }
                if result != d.out {
                        t.Errorf("Calculate(%q) gave %v, expected %v",
                                d.in, result, d.out)
                }
        }
}

You mention repeated code in stack_test.go and assert methods.
Although there are various third party testing/assert packages,
I don't recommend them.

Usings what I've just mentioned, if I wanted to test a few
series of operations on something
I'd likely do something like this:

func TestStack(t *testing.T) {
        const (
                doPush = iota
                doPop
        )
        tests := [][]struct {
                op  int
                val int
                l   int
        }{
                // Simple 3×Push then 3×Pop:
                {
                        {doPush, 1, 1},
                        {doPush, 2, 2},
                        {doPush, 3, 3},
                        {doPop, 3, 2},
                        {doPop, 2, 1},
                        {doPop, 1, 0},
                },
                // … other cases here …
        }
nextTest:
        for i, steps := range tests {
                s := new(Stack)
                for j, d := range steps {
                        // Could use t.Log/t.Logf to verbosely
                        // log something about the step/op being done.
                        switch d.op {
                        case doPush:
                                s.Push(d.val)
                        case doPop:
                                if g := s.Pop(); g != d.val {
                                        t.Errorf("%d:%d poped %v, expected %v",
                                                i, j, g, d.val)
                                        continue nextTest
                                }
                        }
                        if g := s.Len(); g != d.l {
                                t.Errorf("%d:%d end len %v, expected %v",
                                        i, j, g, d.l)
                                continue nextTest
                        }
                }
        }
}

Then it becomes easy for anyone to just add data to the struct
for more testcases or more steps.

One complication here is that I wanted it to stop a specific
test case on the first failure (since each remaining step
depends on the previous ones working).
Normally you'd just use t.Fatal in place of t.Error to signal
that your test function can't proceed.
Here I just continue on with the next test case so I need the
(some would call ugly) loop label.

In addition to the previously mentioned links,
Effictive Go
and the Go Author's Go Code Review Comments
should be considered required reading.


Create a WordPress site data with Nginx app data automatically

Shellcheck.net

I strongly recommend to start using https://shellcheck.net/.
Simply copy-paste your script,
and it will tell you many issues with this code.

Don't use return outside of functions

The return statement only works within functions.
You probably meant exit instead:

domain="$1" && test -z "${domain}" && exit

Variables in command arguments

Always double-quote variables in command arguments to prevent glob expansion and word splitting, for example:

cat ~/myAddons/nginx_app > "${sava}/${domain}.conf"

Inconsistent paths

Here, the last argument of the second command starts with a /, but not the last argument of the first command:

cat ~/myAddons/nginx_app > ${sava}/${domain}.conf
sed -i "s/\${domain}/${1}/g" /${sava}/${domain}.conf

I suspect the last arguments are intended to be the same in both of these commands. This is confusing.


Run loop for a text-based adventure game

Avoid wildcard imports. Import from rooms just what you need, named explicitly.

while 1 is an unnatural way of writing while True

Don't use != or == with None. Use is not None and is None.

The scene.run call that returns another scene object is not very intuitive. Functions are best named after what they do and/or what they return. In this example "run" is a pretty vague term, it could mean anything. If it transitions the game state to the next scene, I think scene.next_scene would be more intuitive.

Do you really need SCENES ? How about just passing around scene instances? This approach using a global dictionary of index to instance mappings seems fishy.


There is no single correct answer in all circumstances. You have to weigh the costs and benefits of the alternatives. Oddly enough my analysis seems to match yours, but here's one additional alternative you didn't explicitly cover:

Add redundant typedefs. All types you create will follow your standard, and those from the standard library will not. However you can easily provide aliases that expose parts of the standard library using names of your choosing. This is a little more code than the first option, and provides an opportunity for users of your class to use either name they like. If more than one name is used, the readability of the code can suffer. As such, while this initially may look like it combines the best of both extremes, in reality it also offers the worst.

template <class T>
struct IsOptional : std::false_type {
    using Type = std::false_type::value_type;
    using Value = std::false_type::value;
};

template <class T>
struct IsOptional<Optional<T>> : std::true_type {
    using Type = std::true_type::value_type;
    using Value = std::true_type::value;
};

However, once you're done writing the library, I would posit this is not all that important. I do not routinely use std::true_type or std::false_type when consuming a library. Template specialization is typically used to achieve two objectives at the same time:

Make the classes easy to use in flexible ways
Make the code that uses the classes really fast

Neither of these objectives really involve the consumers of the library having to care about the names of the types used in specializing its templates.

And thus my answer is this: don't sweat it. Do what makes you, and anyone else who is helping to implement your library, happy. This probably means choose the least amount of work, leaving you with mismatched conventions, but the ability to leverage knowledge of working with the standard library, but could mean writing your own TrueType and FalseType classes that follow your chosen naming conventions.


99 simple asynchronous bottles on the wall

Here are some things that may help you improve your code.

Don't use usleep()

The usleep() function was part of the POSIX standard, but it was marked obsolete in 2001 and removed entirely from the 2009 version of the POSIX standard.  You can use nanosleep instead.

Make it clear when loops end

The code currently uses while (1) in main, but it doesn't really loop infinitely.  It's better, generally, to have the loop exit condition explicitly stated.  For example we could rewrite your main() loop:

while (events_head.next) {
    update_time();
    check_events();
    usleep(900000);
}

This makes it much more clear when and why the loop will end.

Return something useful from the subroutines

Many of the functions that claim to retun an int don't return anything at all, so they should be declared void instead.  Alternatively, if there's a value that could usefully be returned, modify the functions to return that instead.

Check return values and handle errors

The code calls malloc but never checks for error return values.  This is a serious problem that must be addressed.  If the sytem ever runs out of memory, the program will crash.

Consider re-using memory items

Each time an event is registered, new memory is allocated, and each time an event is processed, that memory is freed, even when, as in the case of event_99_bottles, the task re-registers itself.  One way to do this would be to have a reregister_event call.

Use a void * as the argument

Right now, if you decide to create a new type of event which uses a new type of argument, you'll have to recompile the whole code.  If instead of the EventArugment structure, the EventList contained a void *, then that part of the code would be able to remain the same, even if more elaborate data needed to be passed to specific events.  It would then be up to the called function to cast this to whatever it was expecting as input.

Consider using a priority queue

What you seem to be working toward is something like the event dispatcher for a generic task scheduling routine as might be used in a simple operating system.  Such task schedulers often use a priority queue to allow for higher and lower priority tasks.

Consider using an intelligent wait

The check_events() routine doesn't currently return anything useful, but it could.  If it traversed the list, checking for the next deadline and returned that time, then the code could simply sleep for that amount of time, very efficiently only waking up when there was work to do.

Eliminate global variables where practical

The code currently uses two global variables (current_time and events_head) that probably don't really need to be global.  Better would be to pass those as arguments to the functions that need them and/or putting them both inside an Events structure.  If you decide to keep either those (or an Events structure) outside of any function, consider making them static which limits them to file scope.  Generally speaking, it's good practice to make the scope of variables as small as practical.


It looks like it was written in another language and then translated to Go. It looks complicated. Go is designed to be efficient. Maps are not as efficient as slices and arrays for simple indexing. decode(secret, i) executes 26 times instead of once. Etc.

Here's an alternate version,

package main

import "fmt"

const alphabet = "abcdefghijklmnopqrstuvwxyz"

func rotate(s string, rot int) string {
    rot %= 26
    b := []byte(s)
    for i, c := range b {
        c |= 0x20
        if 'a' <= c && c <= 'z' {
            b[i] = alphabet[(int(('z'-'a'+1)+(c-'a'))+rot)%26]
        }
    }
    return string(b)
}

func decode(cipher string, rot int) (text string) {
    return rotate(cipher, -rot)
}

func encode(text string, rot int) (cipher string) {
    return rotate(text, rot)
}

var frequencies = []float32{
    .0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241,
    .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007,
}

func crack(cipher string) (text string) {
    var sums [26]float32
    for _, c := range cipher {
        c |= 0x20
        for j := range sums {
            if 'a' <= c && c <= 'z' {
                sums[j] += frequencies[(int(c)-int('a')+j)%26]
            }
        }
    }
    var maxi, maxsum = 0, float32(0)
    for i, sum := range sums {
        if sum > maxsum {
            maxsum = sum
            maxi = i
        }
    }
    return rotate(cipher, maxi)
}

func main() {
    fmt.Printf("%s\n", encode("hello", 10))
    fmt.Printf("%s\n", decode("rovvy", 10))
    fmt.Printf("%s\n", crack("pybrscpexnkwoxdkvmyxdbsledsyxcdydronopsxsdsyxkxnnocsqxypzbyqbkwwsxqvkxqekqoc"))
}

Output:

rovvy
hello
forhisfundamentalcontributionstothedefinitionanddesignofprogramminglanguages


I have performed some benchmarks to get the optimum combination of block and slice sizes using 32-bit and 64-bit compiler. 64-bit because we are also developing an optimized 64-bit implementation on the sidelines. Here are the results for generating 320000 IPs on our server with all the server applications also running, the values are in Milli-seconds and floored over 5 runs;

Block-Slice  32-bit 64-bit
32-0         3479   3120
32-16        3464   5912
64-0         2059   2980
64-16        2028   1606
64-32        2013   1622

The algorithm gave the worst results with 8-bit slices.
So the best bets are 64-32 for 32-bit and 64-16 for 64-bit for this algorithm.


Some of the general things I would work on:

split the code into separate modules logically. Currently, you have all the code mixed up in single file - you have argument parsing, database interactions, web-scraping code blocks in one place
consistent indentation. Use 4 spaces for indentation
variable naming. Use descriptive variable names. Variable names like l, i or j are not meaningful and raise questions when reading the code

Code Style

avoid handling broad exceptions with a bare except
remove unused imports and re-group them based on PEP8 recommendations
make sure to properly use whitespaces in expressions in statements
put the main execution logic of the program into the if __name__ == '__main__':
you don't need that pass in the get_list_of_urls() function
depth = depth + 1 could be shortened to depth += 1

Performance

since you are requesting the pages from the same host multiple times, consider switching to requests making use of a single session instance which allows to re-use an underlying TCP connection making subsequent requests to the same host faster
importing SoupStrainer was actually a good idea. You can use it and scope the parsing to only the desired parts of the HTML
since you are using regular expressions checks here and there, consider pre-compiling them and using the compiled patterns for searching and matching


From my research, the slowest part of your script is by far SpreadsheetApp.openById(docid), there is nothing much you can do about that. I am not sure how this script will behave once you have a 100 instances of it running, but my prediction is that it will be bad..

Furthermore from a once over:

You never use cell in var cell = sheetFrom.getRange('A1').offset(lastRow, 0);
You never use row2 in for (var row2 in values2Rule1) {, I dont think you need it
You only have to declare cellreference and getsheet once
You should consider lowerCamelCasing: getsheet -> getSheet, cellreference -> cellRefeference
getSheet is a terrible name, you should name the variable of the sheet:

var monitoringSheet = doc.getSheetByName("monitoring");

You call doc.getSheetByName("monitoring") twice, you could simply:

var toSheet = monitoringSheet;

Instead of reading one cell value and then assigning it to another, you could simply use copyTo:

var dataSheet = doc.getSheetByName("getdata");
// Get url from C1 and insert to multiple-referenced cell C4
var c1 = getsheet.getRange("C1"),
var c4 = getsheet.getRange("C4");
c1.copyTo(c4);

At the end you already had a reference to C4, so you could simply:

c4.setValue( 'blockxmlimport' );


Checking whether relations are equal to foreign fields using LINQ Any()

Can you not simply do SequenceEqual?

var list = new List<string> { "test1", "test2", "test3" };
var list2 = new List<string> { "test1", "test2", "test3" };

var areListsEqual = list.SequenceEqual(list2);


Using @RubberDuck's reference to the Sieve of Eratosthenes, I came up with the following code for listing prime numbers:

def list_primes up_to
  primes = (2..up_to).to_a
  primes.each {|num| primes.delete_if {|i| i > num && (i % num) == 0} }
  primes
end

The code is fairly simple. We build an array of all the numbers up to up_to and start deleting from that list every number that is devisable by any of it's predecessors (not a prime).

This promises less iteration, since we don't have to review numbers more than once and all the predecessors we check against are prime numbers, so we don't have to check against numbers that are irrelevant (i.e. checking against 6 when we already checked agains 2 and against 3).

Benchmarking this code in comparison to your code showed that listing the prime numbers up to 10,000 took 0.09 seconds using this application for the Sieve of Eratosthenes vs. 3.65 seconds using your code... That's about 40 times faster(!)*.

I would say, although my code might not be the best way to write the Sieve of Eratosthenes in Ruby, that @RubberDuck's advice is pure gold.

Reading about it in Wikipedia, it seems that n * log(n) would offer a number close to the prime number... so this will help up determine up to what number we should search....

Here's my version of the code, which assumes the first prime number to be 2:

def my_nth_prime n
  up_to = n * (Math.log(n) + 2)
  primes = (2..up_to).to_a
  primes.each {|num| primes.delete_if {|i| i > num && (i % num) == 0} }
  primes[n-1]
end

up_to will designate the upper limit for the prime numbers (prime numbers up to that number will be calculated). It is calculated using the rule of n * log(n) suggested by Wikipedia...

...BUT, that rule might brake down, as it's only an approximation. So, just to be on the safe side, we add another 2 ns to the up_to, making sure we don't get caught by a lower approximation than the actual nth prime.

Once these two things are done, we build an array of all the primes up to up_to and select the n-1 prime (arrays are 0 based, meaning the first item is at [0] so the nth prime is actually [n-1]).

To build the array we use the same code as before, collecting all the numbers up to up_to and deleting any number that is devisable by any of it's predecessors (leaving the predecessors to be only prime numbers, this saves us a lot of testing and iterations).

Good Luck!

although the Ruby code I provided might be faster, it's extremely slow compared to the Prime core class... Getting the 10,000th prime using my code took my computer 7.52 seconds, vs. 0.002925 seconds using the native module(!).


This is absolutely insecure.

I will list only a handful of things which I think need to be absolutely rewritten.

Do not use crypt. Instead, please use password_hash. Along with password_verify, your code could be simplified a great deal.
If you're going to use PDO, use it. Do not mix in other database access modules (MySQL). Especially not MySQL, it is not current and is not supported nor will it ever be supported in the future. mysql_real_escape_string gives a false sense of protection, but in reality, it does nothing for you.
Along with number 2, comes the possibility of SQL injection in your app. If you follow what I've said in number 2 (Use PDO (bind parameters, prepare statements), get rid of anything MySQL), you should be good.
If you're going to try something, catch it! I want to know when something goes wrong.


Usually when I see your questions there isn't much for me to say, because you usually flesh everything out really well. :) (Probably why this has been unanswered so long.)

That said, I think I do have one comment here:

If you have support to edit the HeaderAttribute or the GetAttribute, I would consider replacing the {0}, {1} (etc.) format symbols with a named format symbol.

[Get("posts/{id}")]
Task<BlogPost> GetAsync(int id);

[Site("https://jsonplaceholder.typicode.com")]
public interface ITypicode
{
    [Get("posts/{id}")]
    [Header("X-API-KEY: {apiKey}")]   // req - in
    [Header("Content-Type: {contentType}; charset={charset}")]  // res - out
    Task<BlogPost> GetAsync(
        int id, string apiKey, out string contentType, out string charset);
}

It makes everything more meaningful.

If it's WebAPI you probably don't have access to the source for these attributes, but you can probably wrap them with a new one to add support for this feature. (Adds a little complexity, but should be really awesome to see happen.)


Simplifying casting in my C/C++ qsort char** comparator function

How about this?

int comparator(const void* a, const void* b)
{
#ifdef __cplusplus
    auto a_recast = static_cast<const char* const *>(a);
    auto b_recast = static_cast<const char* const *>(b);
    return std::strcmp(*a_recast, *b_recast);
#else
    return strcmp(*(const char* const *) a, *(const char* const *) b);
#endif
}

To elaborate, the reason that you had to go through the convoluted series of dangerous casts is that you actually were stripping constness.
const void* means a promise not to change whatever the void turns out to be. That is, the thing pointed at by the rightmost star is const. const char ** on the other hand means a promise not to change the individual characters, but doesn't guarantee that you won't change the direct pointers to those characters. However, it's the pointers to those characters that are pointed at by the rightmost star. Intuitively perhaps, think of char * as being in a unit by itself a c_string, and your a and b are arrays of constant c_strings.

The reason that clang warns about c style casts is precisely that they let you apply such a crazy list of operations and changing constnesses without necessarily realizing what is happening.

As an aside, as far as the compiler is concerned, it is actually only necessary to enforce constness on the pointer. That is, you could also compile with static_cast<char * const *>. I put the additional const in because when your conceptual c_string is constant, you conceptually don't want to be changing any of the characters. (And you probably want the compiler to alert you if anything tries to do that.)


Find common preamble of a list of strings

First of all, I think it is very good that you used reduce, as it clearly shows how the algorithm works. At least, to a reader who understands functional idioms.

One problem in your code is that you keep using $a and $b. These two names do not convey any meaning. We could do instead:

my $prefix = reduce {
  my ($current_prefix, $string) = ($a, $b);
  ...

Then, I would shorten the $current_prefix until it is at the beginning of the other $string:

until (0 == index $string, $current_prefix) {
  chop $current_prefix;
}

I did not use the statement modifier form of until or while – I don't believe that they make code much easier to read the way a postfix if or for can do. Note that the empty string occurs at the beginning of any string, so the termination condition of that loop is safe.

If you do not like index or chop, you could equivalently use the less efficient

until ($string =~ /\A\Q$current_prefix/) {
  $current_prefix =~ s/.\z//s;
}

Either way, the concept of shortening the prefix by removing one character at a time until it fits should be easier to read than all the substringing you used.

Cutting the prefix to the length of the string would just be an optimization:

$current_prefix = substr $current_prefix, 0, length $string;

Put together, we would get the following code:

my $prefix = reduce {
  my ($current_prefix, $string) = ($a, $b);

  # the prefix cannot be longer than the string
  $current_prefix = substr $current_prefix, 0, length $string;

  # remove characters from the prefix until it occurs at the beginning.
  # "" is always a prefix, so the loop properly terminates.
  until (0 == index $string, $current_prefix) {
    chop $current_prefix;
  }

  return $current_prefix;
} @strings;

The code might be easier to understand for people who don't know reduce if you express it in the imperative form:

my ($prefix, @strings) = @original_strings;
for my $string (@strings) {
  # the prefix cannot be longer than the string
  $prefix = substr $prefix, 0, length $string;

  # remove characters from the prefix until it occurs at the beginning.
  # "" is always a prefix, so the loop properly terminates.
  until (0 == index $string, $prefix) {
    chop $prefix;
  }
}
# now $prefix is the prefix of all @original_strings

Oh look, it's shorter too!


Filling up a hand with random cards that are not yet drawn - Monte Carlo

In the end, I opt to replace Mersenne Twister with another PRNG, xoroshiro128+, it managed to cut the compute time by around 15%. I also did some minor optimization on the for-loop but the improvement is minuscule. Anyway, here is the same function but with new PRNG:

Seeding in HandEvaluator's constructor:

HandEvaluator::HandEvaluator()
{
    Initialize();
    MTGenerator.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());

    s[0] = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::cout << "Seed 1: " << s[0] << "\n";

    s[1] = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::cout << "Seed 2: " << s[1] << "\n";
}

HandEvaluator's RandomFill function:

void HandEvaluator::RandomFill(std::vector<std::shared_ptr<Card>>& _Set, std::vector<std::shared_ptr<Card>>& _Dead, unsigned int _Target)
{
    //Add the cards that are currently in Set as dead cards
    for (auto const& CardInSet : _Set)
    {
        if (CardInSet == nullptr)
            break;

        _Dead.push_back(CardInSet);
    }

    bool IsDead;
    unsigned int RequiredAmt = _Target - _Set.size();

    for (unsigned int Index = 0; Index < RequiredAmt; Index++)
    {
        while (true)
        {
            _Set.push_back(ReferenceDeck[next() % 52]);

            IsDead = false;

            for (auto const& Dead : _Dead)
            {
                if (Dead->IsEqualTo(_Set[_Set.size() - 1]))
                {
                    IsDead = true;
                    break;
                }
            }

            if (IsDead)
                _Set.pop_back();
            else
                break;
        }
    }
}


Python 3 function to rotate an image 90°

You can use NumPy module that's good with arrays and matrices. It has a built-in for exactly that purpose -

import numpy as np

np.rot90(image).tolist()

With array manipulations, that's essentially same as performing matrix/array transpose and then flipping the rows -

np.asarray(image).T[::-1].tolist()

If the input is already an array, we can skip the array-conversion. Also, if the output as an array is okay, it would be simply a view into the input and as such the entire operation would be virtually-free.

Thus, with image_arr as the input array, it would be -

np.rot90(image_arr)

With transpose and flipping rows -

image_arr.T[::-1]

Let's take the provided sample and check out outputs on an IPython console -

In [48]: image
Out[48]:
[[1, 1, 5, 9, 9],
 [2, 2, 6, 0, 0],
 [3, 3, 7, 1, 1],
 [4, 4, 8, 2, 2],
 [5, 5, 9, 3, 3]]

In [50]: np.asarray(image).T[::-1].tolist()
Out[50]:
[[9, 0, 1, 2, 3],
 [9, 0, 1, 2, 3],
 [5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5]]

Timings on a large 5000 x 5000 sized image

1) Image as a list :

In [53]: image = np.random.randint(0,256,(5000,5000)).tolist()

# @Dima Tisnek's soln
In [54]: %timeit list(reversed(list(zip(*image))))
1 loop, best of 3: 1.09 s per loop

In [55]: %timeit np.array(image).T[::-1].tolist()
1 loop, best of 3: 1.06 s per loop

Time-complexity

There's no time-complexity involved here (not on computation anyway) and the entire play is about array and list conversion, as shown below when we break down the steps -

In [72]: image_arr = np.array(image)

In [71]: %timeit np.array(image) # convert to array
1 loop, best of 3: 771 ms per loop

In [73]: %timeit image_arr.T[::-1] # perform 90deg rotation
1000000 loops, best of 3: 372 ns per loop

In [74]: %timeit image_arr.T[::-1].tolist() # convert back to list
1 loop, best of 3: 296 ms per loop

2) Image and output as arrays :

In [56]: image = np.random.randint(0,256,(5000,5000))

# @Dima Tisnek's soln
In [57]: %timeit list(reversed(list(zip(*image))))
1 loop, best of 3: 1.34 s per loop

In [58]: %timeit image.T[::-1]
1000000 loops, best of 3: 363 ns per loop

In [59]: %timeit np.rot90(image)
100000 loops, best of 3: 9.05 µs per loop

The last two NumPy based ones are virtually free as discussed earlier.  This is because internally image.T[::-1] is same as input image, but with different stride pattern representation. Let's verify that they are same by checking their memory occupancy -

In [60]: np.shares_memory(image, image.T[::-1])
Out[60]: True

Conversion to list on own-data for slight perf. boost

Closer inspection on list conversion reveals that converting to list when the strided pattern isn't regular (row-order) might not be the most optimal scenario. So, one way would be create a copy of array data once we have the rotated one and then convert. This seems to give around 10% improvement -

In [2]: image = np.random.randint(0,256,(5000,5000)).tolist()

In [8]: %timeit list(reversed(list(zip(*image))))
1 loop, best of 3: 1.12 s per loop

In [9]: %timeit np.asarray(image).T[::-1].tolist()
1 loop, best of 3: 1.11 s per loop

# Have own-data (copy) and then convert to list
In [10]: %timeit np.asarray(image).T[::-1].copy().tolist()
1 loop, best of 3: 1.01 s per loop


Learning OOP PHP, simple MySQL connection class.

Let me show my version of this code:

DatabaseException.php:

class DatabaseException extends Exception {
}

Database.php:

abstract class Database {
    protected $login;
    protected $password;
    protected $database;
    protected $hostname;

    public function __construct($login, $password, $database, $hostname) {
        // NB: password not checked and may be empty
        $this->throwExceptionIfNotSet('login', $login);
        $this->throwExceptionIfNotSet('database', $database);
        $this->throwExceptionIfNotSet('hostname', $hostname);

        $this->login    = $login;
        $this->password = $password;
        $this->database = $database;
        $this->hostname = $hostname;
    }

    private function throwExceptionIfNotSet($argName, $argValue) {
        if (empty($argValue)) {
            throw new DatabaseException("'${argName}' not set");
        }
    }

}

Mysql.php:

class Mysql extends Database {

    private $link = null;

    public function __construct($login, $password, $database, $hostname) {
        parent::__construct($login, $password, $database, $hostname);
        $this->connect();
        $this->selectDatabase();
    }

    public function connect() {
        if (! is_null($this->link)) {
            return;
        }

        $link = @mysql_connect($this->hostname, $this->login, $this->password);
        if (! $link) {
            throw new DatabaseException(
                sprintf(
                    'Cannot connect to database. mysql_connect() to %s with login %s fails',
                    $this->hostname,
                    $this->login
                )
            );
        }
    }

    public function selectDatabase() {
        $ret = @mysql_select_db($this->database, $this->link);
        if (! $ret) {
            throw new DatabaseException("Cannot select database {$this->database}");
        }
    }

}

application.php:

try {
    $db = new Mysql('root', '', 'magic', 'localhost');
    print('ALL PASSED'); //for debugging

} catch (DatabaseException $ex) {
    print('redirect to custom error page will go here');
}


Just require a file, or check if_readable first?

I don't recommend B:

A file being readable does not guarantee that it can be successfully included.  The specified path could be a directory (weird and unlikely, but possible), or it might point to a file with a syntax error.
is_readable() does not check the include_path the way require_once would.

Supposing that you could write a function to ensure that it is a regular file, and that it does not contain syntax errors, and checked all directories in the search path, you would have written a significant amount of code that reimplements PHP's built-in functionality.  The built-in functionality isn't broken to begin with.  If you say that a file is required, and PHP is unable to include it, that's a fatal error.  What is the point of prettifying a fatal error and suppressing the error code?

If the file to be loaded is not entirely essential, or if you want your script to commit suicide on its own terms, a better strategy might be to check the return value of include_once.


You've got a good use of match and some solid iterator usage, very nice!

Your closures don't need to be closures -- they don't capture any environment. You can just make them functions (even defined inside the other function, if you'd like). Normally, prefer to define closures at the site of use, instead of as variables ahead of the use. This allows type inference to work on them more effectively (probably why you had to specify types for the closure arguments and return values).
Chars::as_str allows you to get the remainder of the underlying string, so you don't need to iterate though all the remaining characters.
The format! macro allows you to build a string from components in a nicer way.
The code doesn't handle empty strings (unwrap makes this easy to find); there's no reason to not handle them.
You don't need to create a new String in folder, just mark the incoming String as mutable

fn pigify_one(word: &str) -> String {
    let mut chars = word.chars();

    let first_char = match chars.next() {
        Some(c) => c,
        None => return String::new(),
    };

    match first_char {
        'a' | 'e' | 'i' | 'o' | 'u' => format!("{}-hay", word),
        _ => format!("{}-{}ay", chars.as_str(), first_char),
    }
}

fn folder(mut current: String, next: String) -> String {
    if !current.is_empty() {
        current.push(' ');
    }
    current.push_str(&next);
    current
}

fn pigify(text: &str) -> String {
    text.split_whitespace()
        .map(pigify_one)
        .fold(String::new(), folder)
}

I'm a big fan of itertools, which provides methods like join:

extern crate itertools;

use itertools::Itertools;

fn pigify(text: &str) -> String {
    text.split_whitespace()
        .map(pigify_one)
        .join(" ")
}

See What's an idiomatic way to print an iterator separated by spaces in Rust?


Comparing dates with SharePoint PnP PowerShell

I think it's okay, but we can do better. Let's see what Get-Date returns. Run this:

> get-date | get-member

It shows that Get-Date returns a DateTime object, and it also lists all the properties that has. I notice that DateTime has a Date property. Looking on the Web, it says that this is the date part of the DateTime but with a zero time component. So let's use that instead of converting to "yyy-MM-dd":

if((Get-date).Date -eq $ListItem["Aviseringsdatum"].Date){
Write-Output "True"
}

Since this is a code review, let's improve the formatting, and indent and add spaces:

if ((Get-Date).Date -eq $ListItem["Aviseringsdatum"].Date) {
    Write-Output "True"
}

I think that's as far as you need to go. If it were my code, however, I would probably go a bit further.

I would use [DateTime]::Today instead (Get-Date).Date because I think it is clearer.

I would also introduce local variables. I think if you are ever using a "today" or "now" value in your code, then it's better to capture them in a variable for the sake of consistency so that all parts of the script agree on what "today" or "now" is. What if for instance your script ran over midnight? Then the (Get-Date).Date value would suddenly change. A local variable might be overkill in this case, but it's a good practice in general to avoid some subtle bugs.

I also like making local variables to capture bigger expressions because they make for self-documenting code. It might be overkill again in this case, but I will add a $notificationDate variable.

$today = [DateTime]::Today
$notificationDate = $ListItem["Aviseringsdatum"].Date
if ($notificationDate -eq $today) {
    Write-Output "True"
}

I think that $notificationDate -eq $today makes the logic very clear to anyone reading the code.


first = next

That needlessly pollutes the top-level namespace. Please bury that within def trash. Also, the first() call is odd -- it would be more idiomatic to simply call next() when obtaining first element.

    '''unused_names('f.txt') yields f.txt, f.txt_1, f.txt_2, ...'''

That's a code defect. The comment meant to refer to candidate_names().

You might choose to shift the responsibility, to only yield unused names, but the current code is fine, too.

    yield path.with_name('{path.name}_{i}'.format(**locals()))

Passing in **locals() isn't the most readable way. Please just phrase it as

    yield path.with_name(f'{path.name}_{i}')

Docstring:

Metadata is copied; See Python documentation on shutil.copy2 for details.

Kudos for delegating to official docs rather than copying a sentence from them. But it's probably better to point to move(), which itself points to copy2().

\b

Not sure what you meant by \b.

Maybe you don't need the metavar?

The trash_files can sometimes have long directory paths -- consider using SHA1 to compress the directory down to a short unique string.

if not trash_dir:

I don't understand why the click default wasn't set to os.environ.get('TRASH_DIR', '').

You have three expressions you want to probe here, call them d1, d2, d3. Rather than if / then, consider using or:

trash_dir = d1 or d2 or d3

Consider phrasing this

for trash_file_ in trash_files:

as

for trash_file in map(Path, trash_files):

I like the business of finding trash_dest_candidate relative to $HOME or /, whichever works. This could easily be a list of (more than 2) dirs.

    try:
        shutil.move(trash_file, trash_dest)
    except Exception as e:
        print(str(e))
        sys.exit(2)

Catching all exceptions doesn't seem to help you here -- might be better to not catch anything and live with the stack trace. The str() is superfluous. Consider calling exit() with errno from e, rather than constant 2. It appears to me that Ctrl-C is disabled during cross-filesystem file copies.

Overall, it looks like pretty good code that offers a nice service of "collapsing" filenames while avoiding collisions. Consider appending timestamp + pathname to a log file, and automatically pruning month-old files at end of each run, so trash does not grow without bound.


Since the HTTP response implements Writable Stream and Express wraps around HTTP, you can pipe the output to the response, like so:

app.get('/getTime', function(req, res) {
    var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';

    http.get(url + '?key=' + apikey, function(incoming) {
        incoming.pipe(res);
    }
});

It will not only cut down on latency times but also cut down on lines of code.


Is there a better version for verbosing the output of the euclidean method?

There are a couple of "newbie" things here, yes.

Your method has an uppercase first character, it should be lower-case.
Your method is not static, which means that an instance of the class has to be created just to use your method. You can make the method static, and add a private constructor to the class so that it can't be initialized from outside.
As @skiwi says in a comment, please use English identifier names when you code.
boolean lepesrolLepesre is used to toggle whether or not the method should log anything to console. This is a bad thing. A method like this should not output anything to the console, it should simply return the result.
This code:

if (a < b) {
    r = a;
    a = b;
    b = r;
}

is used to switch so that a always is the largest variable, and it's using r as a temporary variable. Even though this works, I would use a temp variable here that's only visible in this scope.

if (a < b) {
    int temp = a;
    a = b;
    b = temp;
}
int r = a % b;

Note that here, I put the initial calculation of r after this switch has taken place.
There is no need to use the else as you return inside the if. You can remove else and reduce the indentation there.

Edit:

In the comments below you asked for a cleaner way for the user to see every step, you can accomplish this by using a callback interface.

Then you can modify your code to:

public static interface EuklidesStepCallback {
    void onStep(int a, int b, int r);
}
public static int gcd(int a, int b, EuklidesStepCallback callback) {
    ...
    while (r != 0) {
        r = a % b;
        if (callback != null) {
            callback.onStep(a, b, r);
        }
        a = b;
        b = r;
    }
    return a;
}

public static void main(String[] args) {
    EuklidesStepCallback callback = new EuklidesStepCallback() {
        @Override
        public void onStep(int a, int b, int r) {
            System.out.println(a + "=" + a / b + "*" + b + "+" + r);
        }
    };
    System.out.println(gcd(24, 16, callback));
}

If you're able to use Java 8, you can use a lambda for the callback:

public static void main(String[] args) {
    System.out.println(gcd(24, 16, (a, b, r) -> System.out.println(a + "=" + a / b + "*" + b + "+" + r)));
}

This callback system is more flexible in case you'd want to save each of the steps to a List or similar.


You have the right idea here by replacing an imperative loop with recursion.

The main improvement I would suggest is that in firstStop you are simulating waiting for the bus i minutes at a time instead of calculating how long to wait. The formula I came up with for that is (renaming i to interval as below):

where
  remainder = current `rem` interval
  firstStop =
    case remainder of
        0 -> remainder
        x -> interval - remainder

e.g. if we're at time 26 and interval = 5 then remainder is 1 and interval - remainder is 4 which correct since we need to wait until time 30. The exception is for when the wait time is 0, in which case interval - remainder would tell us 5 instead of 0, so I wrote out a case expression for that.

There are some Haskell practices you could do better. For example, head and tail are discouraged when you can use pattern matching instead. Here's one refactoring you could do:

calcTime :: Integer -> [Integer] -> [Integer] -> Integer
calcTime current [] intervals = current
calcTime current (travelTime:travelTimes) (interval:intervals) =
    calcTime (firstStop + travelTime) travelTimes intervals
        where firstStop = ...


That looks already quite good and clean. Here are my remarks:

private var first: StackNode? = nil // The topmost node in the stack

An optional value is initalized to nil by default, so

private var first: StackNode? // The topmost node in the stack

is sufficient. And with a different variable name it becomes self-explaining:

private var top: StackNode?

There are trailing semi-colons at some places, these are not needed in Swift.

Here

    let newElement = StackNode(newElement)
    newElement.next = first
    first = newElement

you pass one property of the new node as parameter of the init method, and
set the other via accessor, which looks asymmetric to me. With

private class StackNode {
    var next: StackNode?
    let element: T

    init(_ element: T, next: StackNode?) {
        self.element = element
        self.next = next
    }
}

this simplifies to

    let newElement = StackNode(newElement, next: first)
    first = newElement

or even

    first = StackNode(newElement, next: first)

Note also that the element property in StackNode can be a constant.

A better property name for

/// The number of elements in the stack
var size: Int

might be count – that is what all Swift collection types use. The forced
unwrap in

    // Traverse the list
    while current != nil {
        count += 1
        current = current!.next
    }

is safe, but can even be avoided with

    // Traverse the list
    while let node = current {
        count += 1
        current = node.next
    }

A common practice is to put the implementation of protocols into separate
extensions:

extension StackList: CustomStringConvertible {
    var description: String { ... }
}

Naming: class StackNode is defined within the StackList “namespace,”
so you can simply name it Node. And I would name StackList just
Stack – it is an implementation detail that it uses a linked list.

Further suggestions

Make StackList conform to Sequence. A simple implementation would be

extension StackList: Sequence {
    func makeIterator() -> AnyIterator<T> {
        var current = first
        return AnyIterator {
            guard let node = current else { return nil }
            defer { current = node.next }
            return node.element
        }
    }
}

That allows to enumerate all elements easily:

for item in stack { print(item) }

In addition, you can use it in the description method which then simplifies
to

extension StackList: CustomStringConvertible {
    var description: String {
        return "[" + self.map { "\($0)" }.joined(separator: ", ") + "]"
    }
}

Implement a peek() method to get the top element without removing it,
and an isEmpty property.


Updating Google Sheets table efficiently

These are my suggestions regarding performances:
Generate random numbers only if needed
The new value for the column 7 can be generated after you are sure that needs to be updated. From:
elif (row[3] == '4'):
    random_1 = randint(1, 3)
    if chance <= 0.1:
        print('4 EXECUTED!')
        sheet_store.update_cell(i+1, 8, random_1)

To:
elif (row[3] == '4'):
    if chance <= 0.1:
        print('4 EXECUTED!')
        sheet_store.update_cell(i+1, 8, randint(1, 3))

In this way, the new random value is generated only if chance<=0.1. Same for the other cases.
API call cost
I assume that you are using gspread. The doc says:

Under the hood, gspread uses Google Sheets API v4. Most of the time
when you call a gspread method to fetch or update a sheet gspread
produces one HTTP API call.

Given this statement, your code sends 1 API call with get_all_values() and 1 APIs call for each row to update with update_cell(). In the worst case, there are 5 API calls.
One suggestion is to generate the list of all new values for the column 7 and send a single update call with update(), so that the total number of API calls will be reduced to 2.


Invalidate a JS Object when any of its values is null or empty

Say hello to your new friend, Array.prototype.every. You'll have a callback which actually returns false on any element which is null or ''. The .every call will be short-circuited and your iteration won't have to go over all the nested elements. No need for extraneous invalid array either.


Performance of summing one value from join of three tables

Avoid LEFT JOIN clauses

I'm not sure that I'd pick the OR as the problem.  The real problem is more likely to be the LEFT JOIN clauses.  A LEFT JOIN is a slow operation and to be avoided if you aren't looking for NULL values.

Try using two subselects instead:

SELECT tblU.Name AS Name, tblU.UserID AS ID,
  (SELECT SUM(IF(Action=1, 1, -1))
   FROM Kudos AS tblK
     INNER JOIN Discussions AS tblD ON tblK.DiscussionID = tblD.DiscussionID
   WHERE tblD.InsertUserID = tblU.UserID) +
  (SELECT SUM(IF(Action=1, 1, -1))
   FROM Kudos AS tblK
     INNER JOIN Comments AS tblC ON tblC.CommentID = tblK.CommentID
   WHERE tblC.InsertUserID = tblU.UserID ) AS rep
FROM Users AS tblU;

Note that this only works if Kudos never has a non-null CommentID in a row with a non-null DiscussionID.  This also has the side effect of getting rid of the OR, but I'm not sure that's what matters.

Use indexes

Another thing that you can do is add indexes on the relevant columns if you don't already have them.  Hopefully you already have PRIMARY KEY indexes on the ID column for each table.  If that's not enough, it is possible to add indexes on things like UserID, Name and DiscussionID, InsertUserID, Action.  These can move critical columns into memory.

Consider merging Comments and Discussions

The Comments and Discussions tables use the same columns here.  Consider putting both in the same table with a type column.  Then Kudos would have to do only one join.

You don't include the various table definitions.  If there's too much stuff in Comments and Discussions for a simple merge, you could also consider refactoring them into three tables.  The ID column and author could be set in one table while the other two tables could hold the comment and discussion specific content respectively.  I would consider a merge to be a better solution than this if possible.  This is a backup suggestion.


Splitting a String and Returning Converted Data

First, please please please use Java naming conventions to aid readability. Methods and local variables like int Hours should be in camelCase and not CapitalCase which is for classes. Statements like this:

boolean AnalyzeData(String GpsData){

are especially confusing. Is GpsData referring to the local variable, or the class? That can get very nasty very quickly. Please fix this before you do anything else.

final class GpsData {

This does not do what I suspect you think it does. A final declaration for a class just means it can't be further extended. Its data can still be modified. To properly encapsulate the properties of GpsData you should declare each of those properties as private and provide public constructors, setters, and getters as appropriate.


About your HTML

Removing all the div elements that seem to be needed only for presentation, you have this markup:

Comments

username

 That Guy

  <time class="comment-date" datetime="16-12-2014 01:05"> Dec 16, 2014</time>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 reply

Element for all comments

The class name comment-list suggests that the section groups all comments (which would be the appropriate element for a list of comments). If that’s the case, the heading ("Comments") should be a child of this section.

Comments

Element for a single comment

For each comment, you should use the article element.

Comments

Element for CSS icons

Using the i element for CSS/font icons is not appropriate. Use span instead.

datetime format

Your time element’s datetime value is not in the correct format.

In your case it probably should be

<time datetime="2014-12-16T01:05">Dec 16, 2014</time>

Username / avatar

I don’t understand why you seem to reference two usernames ("username" in figure, "That Guy" in header), but using figure for the avatar doesn’t seem to be the best choice to me (not saying that it would necessarily be wrong).
Is the username really the caption of the avatar image? I’d rather think that these two, the avatar and the username, stand on their own. But if you think it make sense, keep it like that.


Refactoring a function to return all scores above a certain threshold

My 2 cents:

var output should probably be highScores or some such, since it never contains what is returned, nor does it get outputted
nums = scoresArg, threshold = thresholdArg; makes little sense, just use the arguments
function scoresAbove(scoresArg, thresholdArg) , I am not sure what the value is of postpending 'Arg' to the argument names, I would go for simply function scoresAbove(scores, threshold)
The check for Array should really be a separate function, it is completely re-usable
Ditto for Number
For the actual filtering , I would use the built-in filter :

highScores = scores.filter( function(v){ return v > threshold });
Since output is an array, I would not compare with ""
Why the double concatenation here: return "No scores were above the " + " threshold you set as " + threshold;
Arguments of the wrong type should be rare enough that you can throw an exception since something is clearly wrong with the program.

You could try

function scoresAbove( scores, threshold )
{
  "use strict";
  var highScores;

  if( notArray( scores ) )
    throw "scores is not an array";
  if( notNumber( treshold ) )
    throw "treshold is not a number"

  highScores = scores.filter( function(v){ return v > threshold });

  if( !highScores || !highScores.length )
    return "No scores were above the threshold you set as " + threshold;

  return "The following scores were above the threshold: " + output.join(", ");
}

You would have to write the notNumber and notArray function of course.
JSLint migh complain about missing curly braces, to each his own ;)


Using Data.Memocombinators

Have a look at Data.Memocombinators module. It offers combinators for memoizing functions which is essentially what you are doing with the Map.

Here is the example from the documentation on how to use it to create a memoizing fibonacci function:

import Data.MemoCombinators

fib = Memo.integral fib'
   where
     fib' 0 = 0
     fib' 1 = 1
     fib' x = fib (x-1) + fib (x-2)
              ^^^         ^^^

Things to note:

fib is the memoized version of fib' which is just a helper function
fib' calls fib for any recursive calls

The other thing which will help is to keep in mind that the type Memo a represents a a combinator which is able to memoize a function whose argument type is a.

So:

integral is a combinator which can memoize functions taking an Int
pair integral integral is a combinator which memoize functions taking an (Int,Int)

And thus to memoize the Ackerman function:

ack = (pair integral integral) ack'
  where ack' (0,n) = n+1
        ack' (m,0) = ack (m-1,1)
        ack' (m,n) = ack (m-1, ack (m, n-1))

Again, note how ack is defined as the memoized version of ack' and ack' calls ack for recursive cases.

Using Array memoization

Faster results can be obtained by using arrays to memoize the functions ack(1,.), ack(2,.) and ack(3,.):

import Data.Array
import Data.Ix

-- memoize the function f using arrays
arrayMemo bnds f = g
  where g i = arr ! i
        arr = array bnds [ (i,f arr i) | i <- range bnds ]

a0 n = n+1

a1 = arrayMemo (0,530000) f
  where f arr 0 = a0 1
        f arr n = a0 (arr ! (n-1))

a2 = arrayMemo (0,270000) f
  where f arr 0 = a1 1
        f arr n = a1 (arr ! (n-1))

a3 = arrayMemo (0,16) f
  where f arr 0 = a2 1
        f arr n = a2 (arr ! (n-1))

The only drawback is that explicit bounds have to be determined for each level function. This approach computes a3 16 in about half a second.


Define a range based on passed arguments

First, kudos for teaching yourself VBA - I was once in your shoes and how I wish I could have had Code Review to help me back then!

Let's start with the function's signature:

Function defineRange(mySheet As Object, startRow As Long, firstColumn As Long, Optional endRow As Long, Optional secondColumn As Long) As Object

It's not clear whether the function's implicit public accessibility is intended or not. If it means to be accessible from outside the module it's declared in, then it should be explicitly Public. Otherwise, it should be Private - a private procedure/function/method can only be invoked from within the module it belongs to. I'm thinking the intent is for it to be Public here.

You probably noticed pretty much everything in VBA type libraries is PascalCase. From Range to Worksheet.Name - best practice is to "blend in" and write code that adheres to the naming standard. Hence, DefineRange would be better. I like how the name begins with a verb (as it should!), however "define" doesn't strike me as the best choice in this case. The function is getting, or rather acquiring a Range object. The Excel object model already provides an API for this, so reinventing-the-wheel is appropriate here :)

The parameters are all implicitly passed by reference (ByRef), which is an unfortunate default. Would this be expected/desired behavior?

Dim firstRow As Long
firstRow = 12

Dim lastRow as Long
lastRow = 0

Dim target As Range
Set target = defineRange(Sheet1, firstRow, 1, lastRow)

Debug.Print lastRow ' prints 12, not 0. is that expected?

By passing the parameters ByVal, instead of passing a pointer ("reference") to the value, you essentially pass a copy of that value, and the calling code's variables can't get modified by the function. In VB.NET and many other languages, the implicit default is to pass arguments by value: it's somewhat rare that a parameter needs to be passed by reference.

mySheet is declared as an Object, which means the function will happily take a Collection, some UserForm1, any Range, or even MyClass for this mySheet parameter... and then the mySheet.Range call will fail at run-time with error 438 "can't find property or method" (unless there's a method named Range on that UserForm1 or MyClass object, of course). By declaring it As Object, you made every member calls against that object late-bound, meaning the compiler can't help you, and will happily let you try to invoke mySheet.Rnge.

It's usually best to avoid deferring failures to run-time, and fail at compile-time instead, whenever possible. We do this with early binding, by declaring objects using a specialized interface we know we can work with - in this case, Excel.Worksheet, or just Worksheet. We can do this, because when VBA is hosted in Excel, the VBA project is guaranteed to have a reference to the Excel type library. If we were hosted in Word or PowerPoint, we would have to explicitly add that reference (through tools/references), or work late-bound and keep it As Object.

The parameter names are meant to be pairs, but they're inconsistent:

startRow, endRow
firstColumn, secondColumn

"Start/End" was a better, clearer idea than "First/Second" - I'd go and rename the parameters to have startColumn and endColumn, matching startRow and endRow.

Kudos for declaring an explicit return type - all Function procedures return something, whether you declare a return type or not. Then again, it would be better to return a Range rather than an Object.

So, that covers the function's signature :)

There are a number of possible bugs and edge cases that should be handled. The first thing any function should do, is validate its inputs.

VBA doesn't have unsigned integer types, so a Long could very well be a negative number, or it could be zero -- but Excel's object model isn't going to like you trying to get the cell at row 0 and column -728.

There are several ways to deal with this. The simplest is to use Debug.Assert at the very top of the function, i.e. halt program execution if assumptions aren't validated:

'Debug.Assert TypeOf mySheet Is Excel.Worksheet
Debug.Assert startRow > 0
Debug.Assert firstColumn > 0

Another way is to have a guard clause, again at the very top of the function, that explicitly throws an error given invalid arguments:

If startRow > 0 Then Err.Raise 5, "defineRange", "Argument 'startRow' must be greater than zero."
If firstColumn > 0 Then Err.Raise 5, "defineRange", "Argument 'firstColumn' must be greater than zero."

One advantage of using guard clauses, is that if a function is given arguments it cannot possibly work with, then we fail early. This makes it easier to debug if something goes wrong later: instead of dealing with a cryptic and rather useless "Method 'Range' of class 'Worksheet' failed" error, the code that tried to invoke our function now knows exactly what went wrong, and how to fix it.

The return value assignment will fail if mySheet isn't the ActiveSheet:

mySheet.Range(Cells(startRow, firstColumn).Address, Cells(endRow, secondColumn).Address)

That's because the unqualified Cells calls are context-dependent.

If the function is written in a worksheet module's code-behind, then it's implicitly Me.Cells.

If the function is written anywhere else, then it's implicitly [_Global].Cells, which ultimately resolves to ActiveSheet.Cells. That isn't a problem if mySheet is active, but then if it isn't...

Sheet1.Range(Sheet2.Cells(...), Sheet2.Cells(...))

That's guaranteed to throw the dreaded run-time error 1004 "application-defined error", because only Schrödinger's Range can belong to two worksheets at the same time.

You can fix this with a With block:

With mySheet
    Set defineRange = .Range(.Cells(startRow, firstColumn).Address, .Cells(endRow, secondColumn).Address)
End With

Note the . dereferencing operators qualifying the Cells member calls with the object reference held by the With block. It's equivalent to this:

Set defineRange = mySheet.Range(mySheet.Cells(startRow, firstColumn).Address, mySheet.Cells(endRow, secondColumn).Address)

That said, you don't need to work off the .Address string: Range is more than happy to work with the Range references returned by Cells(...):

Set defineRange = mySheet.Range(mySheet.Cells(startRow, firstColumn), mySheet.Cells(endRow, secondColumn))

While that works, I find it quite a mouthful, and as shown above, it has too many reasons to fail to my taste - I'd probably split it up:

Dim startCell As Range
Set startCell = mySheet.Cells(startRow, firstColumn)

Dim endCell As Range
Set endCell = mySheet.Cells(endRow, secondColumn)

Making the return assignment rather trivial:

Set defineRange = mySheet.Range(startCell, endCell)


Your code has a massive bug.

What do you expect the output of the following to be?

import time
clock = time.clock # Reduce errors introduced by me
start = clock()
for i in range(100):
    print(clock() - start)
    time.sleep(0.1)

So 100 * 0.1 = 10, so it should be about 10 seconds.
I ran this and the last print was 10.616061702852994.
This means that you get 6% more time using your program than you would otherwise.

This is a problem.
To fix it you should change the amount to sleep by subtracting from it the time it took to run the print.
And so you may get:

start = next_t = clock()
for _ in r:
    yield clock() - start
    next_t += d
    delay_t = next_t - clock()
    if delay_t < 0:
        continue
    sleep(delay_t)

This is better, as the print shouldn't exceed the delay it's good enough.
But it's not as accurate as I'd like.
While 1.101270229875297 may seem pretty accurate you can change it so that it is instead 1.100000042666685 accurate.
By changing sleep to only do say 90% of the delay, and you create a while loop to do the rest you can get much more accuracy.
This may not be needed, but knowing that the code is pretty accurate is nice.

And so I'd use:

def delay(d, total_time):
    r = range(int(total_time * (1 / d)))
    clock = time.clock
    sleep = time.sleep

    t = start = next_t = clock()
    for _ in r:
        yield t - start
        next_t += d
        t = clock()
        delay_t = (next_t - t) * 0.9
        if delay_t < 0:
            continue

        sleep(delay_t)
        while True:
            if t >= next_t:
                break
            t = clock()

This means that you'll have to change your for loop slightly.
You will need to remove the time.sleep,
and the output is the equivalent of using range(secs + graceperiod).
And so if you put i = int(round(sec - i)) at the beginning of your for loop, it's almost identical.

And so to improve your code further I'd:

Remove the brackets around your if statements.
Use str.format, and change i = -i in your else.
Stop using os.system('clear'), and instead use \r and print '...',.
Change your four print '\a''s to be in a for loop.
Change cl to Color.
Add a main. And use the if __name__ == '__main__': guard.

resulting in:

import os
import time

class Color:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def delay(d, total_time):
    r = range(int(total_time * (1 / d)))
    clock = time.clock
    sleep = time.sleep

    t = start = next_t = clock()
    for _ in r:
        yield next_t - start
        next_t += d
        t = clock()
        delay_t = (next_t - t) * 0.9
        if delay_t < 0:
            continue

        sleep(delay_t)
        while True:
            if t >= next_t:
                break
            t = clock()

def countdown(secs, grace):
    prev = ''
    for diff in delay(1, secs + grace):
        i = int(round(secs - diff))
        if i > 0:
            message = '{0.BOLD}{0.UNDERLINE}{1}:{2:>02}{0.ENDC}'
        elif i == 0:
            message = 'STARTING GRACE PERIOD'
        else:
            message = 'EXTRA TIME: {1}:{2:>02}'
            i = -i
        this = message.format(Color, i / 60, i % 60)
        print prev + '\r' + this,
        prev = '\r' + ' ' * len(this)

    for diff in delay(0.25, 1):
        print '\a',
    print '\a\nTime up!'

    os.system('say "Time up! Put down your pencil!"')

def main(secs, grace):
    try:
        raw_input('Ready? Press [Enter] to start. ')
        countdown(secs, grace)
    except EOFError:
        pass
    except KeyboardInterrupt:
        print Color.BOLD + Color.FAIL + '\nExiting Countdown' + Color.ENDC

if __name__ == '__main__':
    main(10, 10)


Maximum sum of non-consecutive elements of an array

The algorithm is conceptually fine: it's simple and it works.

I don't like the use of iter() and next(), though.  When you write for x in amounts, that will already treat amounts as an iterator.  The only benefit you get from an explicit amount = iter(amounts), then, is the ability to write next(amounts, 0).  And the only reason for writing next(amounts, 0) is to handle the special case where the input is an empty list.  You could just as well handle that by pretending that there is always another leading house with 0 money.

def robbery(amounts):
    prev, total = 0, 0
    for amount in amounts:
        prev, total = total, max(total, prev + amount)
    return total

The for loop would be better written with the conventional indentation.


Set same color as prev row if data matches otherwise different color

As previously mentioned, #tblExport body should probably be #tblExport > tbody, and you should trim() text before comparing.

It is possible to reduce the five calls to SetGroupingDetails().  If you don't try to set a background-color manually, then it's a simple matter of adding either a "zebra-even" class or a "zebra-odd" class.  Simply toggle between them whenever the text doesn't match its predecessor.

var c = 0;
$("#tblExport tbody tr").each(function() {
    var $item = $("td:first", this);
    var $prev = $(this).prev().find('td:first');

    if ($prev.length && $prev.text().trim() != $item.text().trim()) {
        c = 1 - c;
    }
    $(this).addClass(['zebra-even', 'zebra-odd'][c]);
});
#tblExport > tbody {
  font: normal medium/1.4 sans-serif;
}
#tblExport {
  border-collapse: collapse;
  width: 100%;
}
#tblExport th,
td {
  padding: 0.25rem;
  text-align: left;
  border: 1px solid #ccc;
}
#tblExport th {
  background: #bfbfbf;
}
#tblExport > tbody > tr.zebra-even {
  background-color: #093;
}
#tblExport > tbody > tr.zebra-odd {
  background-color: #c90;
}

        Item No.

        Item Name

        10178601

        X

        10178601

        X

          40062595

          Y

          40062595

          Y

          80214549

          Z

          80214549

          Z


Amending code to make it list some files in a directory, rather than all

You can utilize the .Take() method in LINQ which:

  Returns a specified number of contiguous elements from the start of a sequence

Using this, your code would look as follows:

string sDir = "c:\\windows";

foreach (string f in Directory.GetFiles(sDir).Take(10))
{
    Console.WriteLine(f);
}


Objects
Java is, by definition, an Object-oriented language... but, that does not mean every program needs to follow those rules. This is an example program where there are no new objects that are relevant, and as a result, there's no real need to go beyond just procedural routines. You have Scanner, and String, and those are objects enough.
Consequently, you can do everything as static methods/functions, and no need to create anything using new.
Functions
Good code practices recommend a number of aspects to functions that would help here.
First up, functions should do one thing, and do that one thing well. By making functions simple, it makes it easier to reuse them, and combine them. Consider a simple function that gets the initial letter of any String:
public static String getInitial(String phrase) {
    return phrase.substring(0, 1);
}

That function has a useful name, I have made it static because it does not rely on any instance data/fields, and it is a simple stateless function.
Now, we can reuse that in the main method. All we need to do is separate the first and last names..... and a simple enough way to do that is your lastIndexOf(" ") call.
int lastspace = name.lastIndexOf(" ");
System.out.println(getInitial(name) + " " + getInitial(name.substring(lastspace + 1));

Now, there are a number of defensive problems in that code - what if the user does not input any space in their name, or the name is an empty string?
These things need to be fixed, and it makes the code more complicated. A common way to do these things is to split the data on multiple spaces, and output multiple initials, or an empty string if there are none....


CRTP helpers

When using CRTP, it is common to write derived methods in the base class to avoid having to deal with the this pointer and to use reference semantics instead:

Derived& derived() {
    return static_cast<Derived&>(*this);
}

Derived const& derived() const {
    return static_cast<const Derived&>(*this);
}

Thanks to these functions, your update method becomes:

void update() {
    UpdateFuncPtr p = currentState.updateFunc;
    Func newPtr = (derived().*p)();
    if(newPtr.updateFunc)
        currentState = newPtr;
    }

And it is now easier to have the base class call methods from the derived type without having to deal with the this pointer.

Improving Func

If you want to impose more responsibility on Func and less on StateMachine itself, you can still add operator UpdateFuncPtr() const to Func to allow easy conversions to and from the class:

operator UpdateFuncPtr() const {
    return updateFunc;
}

That will allow you simply again the method update:

void update() {
    UpdateFuncPtr p = currentState;
    Func newPtr = (derived().*p)();
    if(newPtr)
        currentState = newPtr;
    }

The implicit conversion to `UpdateFuncPtr` is also used for the boolean conversion needed to check whether `newPtr` is `NULL` or not. Be careful though, implicit conversions are often the source of many hidden errors. Implementing `operator()` in `Func` would be quite difficult since it would mean that `Func` must know the instance of `StateMachine` on which you wish to call the methods. All in all, it is easier to keep the `this` pointer out of `Func`.

Access modifiers

There are several parts of the base class that you do not need in the derived class. You could make them private:

UpdateFuncPtr
currentState
The derived methods if you choose to use them

Moreover, there are even more things that the final users of the state machine don't need to know. Actually, the only need to know about update, so almost everything else could be made protected.

Stylistic tidbits

There are a few more details that can be improved with your code:

Try to always use constructor initialization lists when you can (you may have forgotten it in this particular case because it's only an example):

DemoSM() :
    Base( &Self::update1 ),
    check( 42 )
{ }

Your brace indentation in update is really misleading. When modifying the code, I found it hard to read since the last brace seems to match the if while it actually closes the function block. To reflect that, this last brace should be aligned with the function signature, like every other function in your code.
If possible, try to avoid if blocks without braces. While it may be easier to write when there is only one line, your code proves that it can hide subtle bugs: at first, I thought that the last closing brace closed the if and I tried to add lines to it (to perform some checks) while I wasn't actually adding to the if. Had you used braces for the if, I wouldn't have had this problem.
You don't seem to be very consistent with regard to parenthesis and spaces. You might want to choose some guideline and apply it everywhere.


To answer your question, this is a fine way to do what you're attempting to do. OS vendors will often do something similar where they ship the release versions of their frameworks to end users, and developers can sometimes download debug versions that do more bounds checking and output more verbose messages when given bogus inputs. This allows developers to run additional tests of their own apps to ensure they aren't giving bad values to the OS when calling it.

I also appreciate that now the code can be written inline without a bunch of #ifdef BLAH statements around it or even if (debug) {} statements. I would definitely make sure that calling the release versions which do nothing doesn't slow down any critical inner loops in your processing, though. It's not real likely, but can happen on occasion.

As for a review, I did notice a few really minor things:

You have this line of code in testFuncs():

std::cout << "funci() returned " << test() << std::endl;

What is funci()? Shouldn't the displayed text be "test() returned "? As I say, it's minor, but I was confused while reading it.

I'd also avoid putting an if statement on the same line as its body like you do here:

if(status) { return status; }

When debugging, you'd hit that line, and if status is non-zero the app will suddenly quit when you step over the line. I know if that happened to me, I wouldn't immediately know what had just happened the first time I saw it. Having it on the next line would cause me to step into the body and see that the value is bad. I could then examine what it was before the app quit and the state went away. As I said, very minor, but just thought I'd mention them.


Better Design Pattern For Terminal-Like GUI

Maybe something like this? Note: may add textField as a member of State0 and State1

public interface State
{
    boolean hasNext();
    State next();
}

public final class State0
    implements State
{
    private boolean okToContinue = false;
    private int number;

    @Override
    public boolean hasNext()
    {
        try {
            textArea.append("Enter a number");
            number = Integer.parseInt(textField.getText());
            okToContinue = true;
        } catch (NumberFormatException ignored) {
            textArea.append("Input is not a number");
        }
        return true;
    }

    @Override
    public State next()
    {
        return okToContinue ? new State1(number) : this;
    }
}

The State1 implementation is then obvious. In the main loop you can just do:

State state = new State0();

while (state.hasNext())
    state = state.next();


There really isn't all that much to see here when it comes to cryptography. Basically this is a wrapper class that tries to wrap the knowledge of the person that wrote it (that's you I suppose) rather than to implement security for a specific use case. In such a sense, it is only useful for practice purposes.

Never ever create such a class and make it the center of your security strategy (I've been there, steered there by "professionals", took me weeks to recover from it a couple of years later).

I'll just focus on the security parts:

a string is not a key, if you want to use a password, use a Password Based Key Derivation Mechanism such as PBKDF2 (and keep in mind that most passwords are insecure even if you do take that measure - a number is certainly not a great password);
just "AES" will default to the insecure ECB mode for most if not all Java / provider implementations - it is OK for the key creation, but not for the "transformation" parameter in Cipher.getInstance(String transformation): Cipher;
all other modes require an IV for generic messages, as otherwise identical messages (or parts of messages) may leak data - and even all data in the case of counter mode encryption;
nowadays authenticated ciphers such as GCM should be used; this makes sure that an adversary cannot alter the ciphertext undetected by the receiver - such alterations may even threaten the confidentiality of the message (see plaintext / padding oracle attacks);
using pValue.getBytes() is dangerous as getBytes will default to platform encoding, and the platform encoding may differ per platform (Windows uses Windows-1252 and Linux / Android uses UTF-8, to name just one such difference) - try e.g. pValue.getBytes(StandardCharsets.UTF_8) instead;
just throwing security exceptions doesn't make sense, as it doesn't distinguish between runtime issues (algorithm not available) and input / output issues - see here how to handle security exceptions;

The first thing I do in my IDE is to change e.printStackTrace() to new IllegalStateException("No exception yet specified", e);, usually with a // TODO change exception comment in front of it (picked up by the task system in Eclipse).

The problems with just printing the stack trace is that it is easily forgotten, it keeps running the code even after an exception is turned up and finally, it messes up the compilers detection of dead code.

CRY_ALGO of course is a cry-out for a better name.


You could combine the calls:

if ($(this).closest('div.login-box')
           .slideToggle("400")
           .attr('id'))

However, I do not recommend this.
Although it will work, it's unnecessarily confusing.


Devise an algorithm of complexity O(N) finding No of 1's from a 2 dimensional matrix[N][N] containing 1's and 0's

I think your main loop should be something more along the lines of

row = n-1;      // start at bottom row
for (col=0; col<n; col++) {   // read columns from left to right
    while ((row >= 0) && (map[row,col] == 0)) {   // while not out of rows, and on a 0
        sum += col;  //add count of 1s to total
        row--;       //move to next row up
    }
    // do nothing if we're on a 1, just move to next column.
}
if (row >= 0) sum += (row+1)*col; // add in any leftover rows of all 1s
printf("sum is %d\n",sum);


Is this predicate valid to delete single shared_ptr's?

The copy of the pointer is completely unnecessary: as long as the code is not sharing shared_ptrs among threads (which is really, really silly), taking a shared_ptr argument by reference ensures it lives at least until the function finishes executing.
Even if the copy was necessary, passing by reference to immediately make a copy is a pessimisation as it forbids moves. Don't pass shared_ptr by reference if you're going to copy it.
The pointer in the vector will be destroyed by erase, there's no need to manually reset anything.
A predicate that mutates its argument is bound to raise eyebrows. Depending on the semantics of setParent it may or may not be problematic, but it is something I'd avoid if I could.


Generating probability table of 2-character combinations from text file in Java

I have looked through your code. Here are a few things I notice

StringBuilder instead of using += on String, for more efficient string concatenation.

Creating a new instance of StringBuilder and using that would work better than using the + operator on Strings. Something like this:

StringBuilder builder = new StringBuilder();
// inside the loop call the following
builder.append("some string to append");
// ...
// later on when you need the string
builder.toString();

More descriptive variable names

Try to explain what your variable represents instead of just calling it wholeString. To you, you may very well remember the significance of each variable and what it represents, but this is a good coding practice to get into because code will be read more than written and it would be easier for anyone else reading your code to immediately tell what it's doing without having to in many cases even read comments. This is called "self-documenting code".

JDK 8+ Files API

After JDK 8 you can call lines() using the Files API. Although your approach is correct using BufferedReader and FileReader, you may want to consider switching to using the lines() method and operating on the Stream returned because it is a bit less verbose which makes reading it easier.

Succinct method chaining using Stream over iterative approach

If you switch to using Stream for the file, you can easily adopt a more functional approach of calling filter or other stream related functions on it. This is a bit cleaner to read than the iternative while loop to remove the newlines in my view.

Multiline comments using multiline comment syntax

For in-depth explanations and long comments that span to multiple lines, you can use the following notation:

/*

This comment

spans

multiple lines

*/

However, with that being said - I think the comments in this code are a bit much. Using self documenting variables as mentioned above, comments can be lessened and the code would be more readable too.

Hope that helps, let me know if you have any questions on the feedback I've given.


The name of the method is mergeLists, not mergeNodes. Even though you may think your method is simpler, using Nodes as parameters is misleading for the current method name. One way to address this issue is to rename the method as mergeListsUsingTheirHeads or, to be specific to the problem of merging sorted lists, mergeSortedListsUsingTheirHeads.

I have to ask: what made you think your code is simpler than that of the post you mentioned?


You are right that slicing and dicing the string representation of a date is not the right way. Parsing a local time string without a specific locale is even worse, and asking for trouble.

A Date object in JavaScript has getHours() and getMinutes() methods.
The result will be in 24-hour format. If you need, you can convert that to am-pm format based on the hour. The resulting code will be more efficient and more predictable than parsing the string representation.

For example:

var timestamp = new Date();
var hours = timestamp.getHours();
var ampm;
if (hours < 12) {
    ampm = 'AM';
} else {
    ampm = 'PM';
    if (hours > 12) {
        hours -= 12;
    }
}

For the record, this code to get the time part in rawTime is very poor:

var timeArray = time.split(":");
var spaceDeliTime = timeArray.join(" ");
var rawTime = spaceDeliTime.split(" ");
var extrTime = rawTime.splice(2,1);

For one thing, the sequence of split by colons -> join by spaces -> split by spaces is really silly. Probably you could have achieved the same thing by simply taking a substring.

The most disturbing part is the splice at the end: the result is stored in extrTime but never used. On closer look it turns out the main purpose of that splice was its side effect of mutating the rawTime array. The logic would have been much more clear if you used array indexes to get the segments that you want rather than slicing and dicing an array.

If parsing the string representation, this would have been a simpler, more efficient, less confusing solution:

function makeTime () {
    var timesStamp = new Date();
    var time = timesStamp.toLocaleTimeString();
    var timePart = time.substr(0, time.indexOf(":", 2))
    var spaceAndAmPmPart = time.substr(time.lastIndexOf(' '))

    return timePart + spaceAndAmPmPart;
}

But I still recommend the different approach using getHours and getMinutes.


Copying a huge vector by mistake
The reason your program is so slow is because of this line:

int sameSet(int i, int j, vector<node*> v)

This function makes a copy of the vector every time you want to do a simple check on two nodes.  If you simply change that line to this:
int sameSet(int i, int j, vector<node*> &v)

then your program will avoid the copy.  In my testing, the program ran in 1-2 seconds instead of over a minute with a large n.
Also, that function could be simplified from this:

int sameSet(int i, int j, vector<node*> &v)
{
    if (find(v.at(i - 1))->data == find(v.at(j - 1))->data)
        return 1;
    return 0;
}

to this:
bool sameSet(int i, int j, vector<node*> &v)
{
    return find(v[i-1]) == find(v[j-1]);
}


The variable names in change_char_at are terrible. s for the string, ch for the char? i for the start? j for the end.

Seriously just write out names.

def change_char_at(string: str, change: str, start: int, end: int = None):
    return string[:start] + change + string[end or start+1:]

Your code isn't fully typed:

change_char_at has no return type.
end in change_char_at and wait in loader_with_wait are assumed to be Optional but not specified to be optional.
loader and loader_with_wait have no return types should they be None or NoReturn?

The functionallity of change_char_at can be eclipsed by the format mini-language.

You have a standard structure where the bar is surrounded by [] and filled with the contents.

bar = '[{}]'

The content of your bar is left aligned by width.

bar = '[{: <{width}}]'

Each iteration you increase the left hand space by 1.

bar.format(' ' * i + '=' * bar_width, width=width)

bar_width doesn't actually change the size of the bar.
I would prefer the progress bar to be a generator function or list, so the rest of your code is simpler.

import itertools

def progress_bar(width: int = 20, bar_width: int = 3):
    bar = f'[{{: <{width}}}]'
    for i in itertools.chain(
        range(0, width - bar_width + 1),
        reversed(range(0, width - bar_width)),
    ):
        yield bar.format(' ' * i + '=' * bar_width)


Possibly not the best solution, but here's one that uses F# more extensively:

let rec processProgram (i: int) (ops: int list) =
    match ops with
    | opCode :: aPos :: bPos :: outPos :: rest  when opCode = 1 -> // add op code
        let a = ops |> List.item aPos
        let b = ops |> List.item bPos
        let complete = [opCode; aPos; bPos; outPos] @ processProgram (i + 4) rest
        let (left, right) = complete |> List.splitAt outPos
        left @ [a + b] @ (right |> List.skip 1)
    | opCode :: aPos :: bPos :: outPos :: rest when opCode = 2 -> // multiple op code
        let a = ops |> List.item aPos
        let b = ops |> List.item bPos
        let complete = [opCode; aPos; bPos; outPos] @ processProgram (i + 4) rest
        let (left, right) = complete |> List.splitAt outPos
        left @ [a * b] @ (right |> List.skip 1)
    | head :: rest  when head = 99 -> // terminate
        ops
    | _ ->
        failwith "Unsported opcode"

I've turned the function into a recursive function with let rec so that it can be called from within itself, I'll generally use this rather than a loop.

Next I'm using list rather than array so that I can pattern match on the operations. Let's look at that:

match ops with
| opCode :: aPos :: bPos :: outPos :: rest  when opCode = 1 -> // add op cod

This expects the list to have at least 4 elements, and I'm destructing it into the pieces we care about, opCode (what we're doing), aPos and bPos (where in the instruction set the values we want are) and outPos (where to put the output in the instruction list). It's then got a when test on the end to check the value of the opCode so we can hit the right op code branch.

When the match is hit we grab the values from their current pos and then process the rest of the instruction set, generating a new list with:

let complete = [opCode; aPos; bPos; outPos] @ processProgram (i + 4) rest

The @ operator concats two list's together.

Then we'll split it on the outPos:

let (left, right) = complete |> List.splitAt outPos

This gives us a tuple of int list * int list that we deconstruct into two variables and lastly we rebuild the list through concatinations:

left @ [a + b] @ (right |> List.skip 1)

We use the left part to start with, as it is all up until the outPos, then insert the result of the op-code (add in this place) and then concat-ing the right but skipping outPos which is the head of the list.

Side note: it's not stated in the requirements that you can update positions beyond the current op stack, so I didn't implement that, it'll only do reverse-updates.


Since "the chars set length could be up to hundreds", it can easily contain enough letters to form any word in an English dictionary. In such a case prune_words would not prune any words. This makes me think the pruning is an example of premature optimization.
Instead of using Counter to check a match, I believe it would be faster to compare sorted lists of characters, i.e. compare sorted("".join(comb)) to a pre-computed sorted(char_set).
Copying a Counter by Counter(char_count) is faster than by copy.deepcopy.
To check if all counts are zeros you don't need the list comprehension as you can simply use if not any(temp_count.itervalues())
You check lots of combinations that are the wrong length. Even though the length check is the first thing inside the loop, it would be better to generate the combinations in a way that allows you to back off when the combined length exceeds the length of char_set. I would use recursion to explore the combinations.
A more clever approach might be found from representing the dictionary as a prefix tree.


Refactoring code structure

As of right now, you have:

A struct named Object.
A global std::vector<Object> of Objects.
A function named attraction, which (I assume) calculates the attraction between two separate Objects.
A function named render which (I assume) renders all of the objects in bodies.

While this structure works fine, it's somewhat rigid and will probably cause you issues in the future if you ever try to expand this project by any significant amount. Instead of having this structure, I'd recommend that you design something more akin to the following:

A struct (or class) named Object which represents a gravitational body, with the following member functions:

CalculateAttraction(), for calculating object attractions.
Update(), for updating anything related to the object, like position, etc.
Render(), for rendering the object.

A struct (or class) named ObjectManager which is used to store and manage objects, with the following member functions:

AddBody(), for adding a new gravitational body.
Update(), for updating the object manager and its stored Objects.
Render(), for rendering the object manager and its stored Objects.

A top-level Update() function for GLUT to use.
A top-level Render() function for GLUT to use.

While you don't have to follow this exact structure (you may also need additional behaviors included with the ones I provided), it will make managing and expanding this project much easier.

Using const instead of #define

In C++ (and even later versions of C), it's always better to use const (or constexpr in some special cases) for defining constant values rather than a macro. Using macros can often lead to obscure and confusing issues popping up, especially if you're overzealous in your use of them. The macros in your code (excluding GLEW_STATIC) should be declared as:

const int WIDTH = 800;
const int HEIGHT = 800;
const float AU = 149.6e6 * 1000;
const float SCALE = 250 / AU;
const float G = 6.67428e-11;

Instead of:

#define WIDTH   800
#define HEIGHT  640
#define AU      (149.6e6 * 1000)
#define SCALE   (250 / AU)
#define G       6.67428e-11

Nitpicks

You have a small bug in your code where you #define GLEW_STATIC. In order to use GLEW properly as a static library, GLEW_STATIC must be declared before you include glew.h. You'll also likely have to change "glew32.lib" to "glew32s.lib". Example:

#pragma comment(lib, "glew32s.lib")

...

#define GLEW_STATIC
#include "glew.h"

Please don't ever use using namespace std; in your C++ code. It's a very bad idea. See this Stack Overflow post for the reason why.
The variable bodyIndex is poorly named and unnecessary. std::vector<T> already has a size() function which returns the number of elements in the vector.
While you mentioned that you know you used the fixed function pipeline, I'm going to recommend against it anyways. It's deprecated in a lot of graphics hardware and sometimes requires some special workarounds to get working. It's also much less flexible than the programmable function pipeline.
The various #includes and #defines at the beginning of your code are are grouped together in one big cluster, which isn't very visually appealing. I'd highly recommend separating them into distinct groups, like so:

#pragma comment(lib, "glew32.lib")
...

#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
...

#define GLEW_STATIC
#include "GL/glew.h"
#include <glut.h>
...

#define WIDTH   800
#define HEIGHT  640
#define AU      (149.6e6 * 1000)
#define SCALE   (250 / AU)
#define G       6.67428e-11
...

As you can see, there are four distinct groups here, #pragmas, standard #includes, 3rd-party #includes and #defines.