Why do you need the actual list of Fibonacci numbers? That just requires space, and time.

Believe it or not, you have over-thought this problem. Additionally, your code style is off.

C# Code conventions always use braces for single-statement blocks, and the brace should open at the start of a new line. Code like:

foreach (int i in fiboNums) { if (i % 2 == 0) sumEvenFibos += i; }

should be:

foreach (int i in fiboNums)
{
    if (i % 2 == 0)
    {
        sumEvenFibos += i;
    }
}

As for the list, you don't need it:

int current = 1;
int previous = 0;
int sum = 0;
while (current <= 4000000)
{
    if ((current % 2) == 0)
    {
        sum += current;
    }
    int tmp = current + previous;
    previous = current;
    current = tmp;
}

Now, that whole thing should be put in its own function, and your main method with a parameter for the upper limit (4,000,000) and it becomes:

static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    int sumEvenFibos = GetFiboSum(4000000);

    s.Stop();

    Console.WriteLine(sumEvenFibos);
    Console.WriteLine(s.ElapsedMilliseconds);
}


Project Euler #10 in C++ (sum of all primes below two million)

Here are a number of things that may help you improve your program.

Use a better algorithm

As already mentioned in the comments, a Sieve of Eratosthenes is going to be much, much faster than the current method.  Generally speaking, doing division is a computationally expensive operation.  For example, a simple Sieve program to solve this same problem takes 0.7 seconds on my machine, while your existing program takes almost 5 minutes (4:58.4).  However, we can still make considerable improvements without changing the basic algorithm you've already implemented.  The rest of the review concentrates on helping you improve your existing code and algorithm.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Consider improving names

I think divideByAnyPrime is not a terrible function name (although I'd probably call it isComposite), but X and lst are very poor variable names.  A good name should suggest something about what it contains.  For example, I've renamed X to MAXNUM in the next suggestion.

Prefer constexpr to old-style #define

Rather than using a #define for X the code could use a constexpr:

constexpr long long MAXNUM{2000000};

The advantage is that the value has an associated type.

Eliminate global variables where practical

The code declares a global variable to contain the list of primes.  Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult.  It also makes the code harder to reuse.  For all of these reasons, it's generally far preferable to eliminate global variables.  For MAXNUM, simply put it at the top of main.  For the list of primes, use the next suggestion.

Encapsulate functions and data within a class

Since you're writing in C++, I'd suggest making a class.  Here's the class declaration:

class Primes final : public std::list <long long>
{
public:
    Primes()
        : std::list<long long>{2,3}
    {
        for (auto n = back()+2; n <= MAXNUM; n+=2) {
            if (isPrime(n)) {
                push_back(n);
            }
        }
    }
private:
    static constexpr long long MAXNUM{2000000};
    bool isPrime(long long a) const;
};

Notice that MAXNUM is now a member of the Primes class and that the function isPrime is used instead of divideByAnyPrime.  Its sense is also inverted such that it only returns true if the passed number is prime.

Think carefully about the mathematics

Within the routine that check for divisibility by any existing prime, there's no need to go all the way to the end of the array.  If a number \$N\$is composite, its smallest factor must be \$\le \sqrt{N}\$.  This suggests that one way to write an isPrime function would be this:

bool Primes::isPrime(long long a) const
{
    long long sqrta = std::sqrt(a);
    for (auto it = ++begin(); *it <= sqrta; ++it)
        if( a % (*it) == 0 )
            return false;
    return true;
}

Note that this also skips the first item in the list, which we know is 2.

Use standard functions

Calculating the sum is actually easily done using a standard generic algorithm:

int main()
{
    Primes primes;
    long long sum = std::accumulate(primes.begin(), primes.end(), 0ll);
    std::cout << "Sum is " << sum << "\n";
}

Results

With all of these changes, the time drops to 1.14 seconds on my machine, which is a considerable improvement over the original 5 minutes.


Generating 2 comma-separated lists from list of key value pairs

Performance here will only matter if the input List is large. There are two things that can be done to make the output loop faster:

initialize the starting capacity of the StringBuilder to match your expectations of what size it will need to be.

In this case, you know the GUUID's are 36 characters long, with a comma, makes it 37. You should initialize that StringBuilder to ... new StringBuilder(37 * kvps.Count);. Similarly, if you have an approximate size of the average length for the other Stringbuilder, then double-it, and use it as the initial capacity constructor.
If the loop happens (very) often, you can get a very slight performance improvement by doing the following (removing the if condition from inside the loop):

foreach (KeyValuePair kv in kvps)
{
    a.Append(kv.Key);
    a.Append(",");
    b.Append(kv.Value);
    b.Append(",");
}
// remove the trailing comma.
if (kvps.Count > 0) {
    a.Length = a.Length - 1;
    b.Length = b.Length - 1;
}

It should go without saying that the names a and b are bad names for the StringBuilder instances ....


JavaScript functions and global variables

Yes, you are right, decimal, a, b and c are not accessible by other functions because they are local to getValue(). To make them global, you need to declare them outside of your function, like this:

Solution #1

var decimal;
var a;
var b;
var c;

function getValue(){
 decimal = // assign decimal
 a = // assign a
 // assign rest of the variables
}

function useVariables(){
   return a + b + c;
}

Using global variables, however, is considered a bad practice so I would move onto another solution.

Solution #2

Have 'getter functions' for each of your variables. Instead of having getValue(), have getDecimal(), getA(), getB() and getC() functions (you might consider giving these variables more meaningful names). Your code would turn into something like this:

function getA(){
  return parseFloat(parent.document.getElementById('CF_9814331').value);
}

// functions for getB() and getC()

function useVariables(){
  return getA() + getB() + getC();
}

This is a more acceptable solution because you delay getting the variables until you need them and you also do not have global variables. If the values change you get the updated values as well without having to call getValue() again to 'refresh' your data.


Try to refrain from using using namespace std, especially in a program like this.  If you were to put it in the header, you could introduce bugs due to issues such as name-clashing.
Your comments next to <cmath> suggests that you're using it, but I don't see these functions used anywhere.  No need to include this library.
#include headers before libraries to prevent unwanted dependency:

#include "Craps.h" // header won't be forced to use <iostream>
#include <iostream>

Naming convention states that functions should start lowercase:

thisIsAFunction();
this_is_also_a_function();

DisplayInstruction() is a needless function as it only displays one line of text.  Functions shouldn't be created just for that.  In general, functions that don't do anything with the data members are best as free functions (non-member functions).
The dice functionality should have its own class, allowing the Craps class to maintain object(s) of it as needed.  This will also ensure separation of concerns.  You may refer to my implementation to get an idea for this.
You didn't seed std::rand() with std::srand().  This will cause rand() to produce the same random numbers each time.  Put this at the top of main() only:

// this requires <cstdlib> and <ctime>
// use nullptr instead if using C++11
std::srand(static_cast<unsigned int>(std::time(NULL)));

However, if you're using C++11, you should no longer use rand.  I'll quote one of my answers:

  You should refrain from using rand altogether in C++11 as it is considered harmful.  Instead, utilize C++11's <random>
  library.

  You also no longer need <ctime> and should use C++11's
  <chrono>.  From this library, you can obtain a seed for a PRNG
  with this:

auto chrono_seed = std::chrono::system_clock::now().time_since_epoch().count();

The switch in Play() could be its own function, specifically of type bool.  As it isn't working with a data member, it can be a free function.  If you go this route, then each case will need a return true or return false.  The default will also need to handle errors resulting from an invalid case value, such as by throwing an exception.
You never use anyKey anywhere, so remove it.
Tested conditions could be shortened like this:

if (condition)  // if (condition == true)
if (!condition) // if (condition == false)

Tested streams can be shortened like this:

if (!(cin >> choice)) // cin >> choice;
                      // if (!cin)


Are there any problems with this memcpy() implementation?

There's a number of issues with this code:

int* wordDist = (int*)dst;
int* wordSrc = (int*)src;

Even if this works on a given platform, it is definitely not portable. int* can often have more strict alignment requirements than char* - this is technically undefined behaviour.

Further, (int*)src; is casting away constness - always dangerous if you then modify the value somewhere in the rest of the function.

int numWords = numBytes >> 2;

This assumes that an int is 32 bit, which is again non-portable, and will of course be wrong on any platform where this isn't the case. This could be fixed by using:

int numWords = numBytes / sizeof(int);

However, the alignment issues mentioned previously still remain.

This code:

int whatisleft = numBytes >> 2 - (numWords);

is completely wrong, as thanks to operator precedence, it is equivalent to numBytes >> (2 - numWords) which is likely to be negative, causing undefined behaviour. Also, one has to be careful regardless, and keep in mind the differences between an arithmetic right shift and a logical right shift. Again, technically, right shifts for signed values are implementation defined, and could potentially be either.


First off:

bool isPermute(char*, char*);
char* sort(char*);

You could just move the function implementation over the main method, avoiding to have these declarations; however, that isn't really a big deal.

The convention for int main isn't:

int main(int argv, char **argc)

It normally is the opposite: argc is for the arg count and argv is for the arguments passed to the program.

So it really should be:

int main(int argc, char **argv)

Next:

printf("%s and %s are %spermutations of each other. \n", argc[1], argc[2],
    isPermute(argc[1], argc[2]) ? "" : "not ");

You never checked if the program was actually passed two parameters, and so instead it should be (argc is the arg count from now on, and argv is the arguments)

if(argc == 3)
{
    printf("%s and %s are %spermutations of each other. \n", argv[1], argv[2],
        isPermute(argv[1], argv[2]) ? "" : "not ");
}
else
{
    printf("Incorrect amount of parameters passed!\n");
    return -1;
}

The following:

if(strcmp(sort(s1), sort(s2)))
    return false;
else
    return true;

can be trimmed down to be just:

return !strcmp(sort(s1), sort(s2));

The following:

char *result = (char *)malloc(size);

You don't need to have the explicit cast (char *) as malloc returns a void*, so it can just be

char *result = malloc(size);

Which doesn't detract from clarity in any real way.

Also, I've noticed that you are declaring variables for the for loops outside the loop, even though that isn't necessary (unless you are using C89, in which case, ignore this)

So this:

for ( character = 'a' ; character <= 'z' ; character++ )
{
     ...
}

would become

for (char character = 'a'; character <= 'z'; character++)
{
    ...
}

The same thing essentially applies for the other for loop.

for ( i = 0 ; i < size ; i++ )
{
    ...
}

would become

for (int i = 0; i < size; i++)
{
    ...
}


Toggling dropdowns using jQuery, with binding and unbinding

First, regarding readability, I suggest changing the following names:

$dropdown -> $content
.toggle (class) -> .togglable
.toggle (namespace) -> .toggling
.isOpen -> isToggleOpen

On the other hand this can be achieved with reduced code (and less internal working impact), with only one event binded:

var $togglables = $('.togglable-content');
$(document).on('click.toggling', function (event) {
  var $target = $(event.target),
  $content = $target.siblings('.togglable-content');
  if (!$target.hasClass('isTogglableOpen')) {
    $togglables.not($content).removeClass('isTogglableOpen');
    $content.toggleClass('isTogglableOpen');
    return false;
  }
});

Here is the modified fiddle.


I second @Caridorc's recommendation. In general anytime you find repetitive code it's a sign to extract the common parts into a routine.

Use escape characters

Additionally, rather than subsequent calls to println use escape characters and concatenate the designated strings. You also want to use an escape to specify the Unicode for the pound symbol to ensure it works across platforms.

With these suggestions your two primary calls would become:

System.out.println(
    "Welcome to the simple VAT Calculator"
    + "\nTo Calculate VAT Payable and the ex-VAT Cost type the total cost below:"
    + "\n----------"
);

and

System.out.println(
    "The VAT payable is " + vatStr
    + "\n" + "The ex-VAT Cost is \u00A3" + exVatStr
);

\u00A3 is the Java Unicode specification for the pound symbol.

Declare and instantiate in one step

For exVat and vat you declare the type, and then set the value on another line. Might as well just combine steps since there's no reason to separate them in this case. I'm sure you understand this since you've done so for your Scanner and totalCost variable.

Make a habit of using try-with-resources

On topic of your scanner, good job closing it. It's something oft missed even with non-beginners. For future reference, it's ideal to use try-with-resources to ensure that is handled, and is also an example of where you may want to separate declaration and instantiation.

 double totalCost;
 try (Scanner cost = new Scanner(System.in)) {
    totalCost = cost.nextDouble();
 }

When formatting is the goal

If formatting regardless of input is your goal, you should use String's static format method and/or rather than calling print use printf

The way to use it is to add in a reference to what you're calling in the string, and the references themselves afterwards, in order.

e.g. for your purposes,

System.out.printf(
  "----------%nThe VAT payable is %10.2f%nThe ex-VAT Cost is %10.2f\u00A3", vat, exVat
);

Here the % is used for the references that follow, the .2 specifies the number of decimal places, and the 10 reserves up to 10 spaces for alignment. Read more about this here.

One benefit of using printf directly is that you don't need to use the previous routine and your entire program becomes:

import java.util.Scanner;

public class Calculator {
  public static void main(String[] args) {
    System.out.println(
      "Welcome to the simple VAT Calculator"
      + "\nTo Calculate VAT Payable and the ex-VAT Cost type the total cost below:"
      + "\n----------"
    );

    double totalCost;

    try (Scanner cost = new Scanner(System.in)) {
      totalCost = cost.nextDouble();
    }

    double exVat = (totalCost * 0.8);
    double vat = totalCost - exVat;

    System.out.printf(
      "----------%nThe VAT payable is %10.2f%nThe ex-VAT Cost is %10.2f\u00A3", vat, exVat
    );
  }
}


I will focus on..

  Creating custom objects with custom properties using generics

Which you do in this method..

public static KeyValuePair<TCity, IEnumerable<TBuilding>> GetData<TCity, TBuilding>()
    where TCity : City, new()
    where TBuilding : Building, new()
{
    TCity city = new TCity();
    IEnumerable<TBuilding> buildings = new List<TBuilding>();
    return new KeyValuePair<TCity, IEnumerable<TBuilding>>(city, buildings);
}

A KeyValuePair is archaic, you can use a ValueTuple nowadays
TBuilding does not require the new() constraint in this method
The choice for IEnumerable over IList is questionable, since you retrieve the items later on and have no way of adding them to an IEnumerable. So why create the IEnumerable in this method?
The name should reflect what you are doing. CreateCity seems more appropriate.

I would refactor this method..

public static (TCity city, IList<TBuilding> buildings) CreateCity<TCity, TBuilding>()
    where TCity : City, new()
    where TBuilding : Building
{
    var city = new TCity();
    var buildings = new List<TBuilding>();
    return (city, buildings);
}

EDIT:

Thinking about the refactored method. This doesn't even need to be a method anymore. It doesn't do anything but create objects for the types you specify.

What I would really do is throw out this ancient way of ORM, and use an existing API (EF, NHibernate, Dapper).


Instead of using mutable variables, it is possible to apply the fold:

let equalsDifference minUnit difference l =
    l
    |> List.fold
        (fun (acc,xs) element ->
               if acc <> 0m then
                  if difference < 0m then
                     if element >= minUnit then
                         acc + minUnit, (element - minUnit)::xs
                     else
                         acc, element::xs
                  else
                     acc - minUnit, (element + minUnit)::xs
               else
                  acc, element::xs)
        (difference, [])
    |> snd
    |> List.rev


Consistency
Always use the same technique when doing the same thing. Do use multiple ways to do the same thing.
You use nullptr in half your code and NULL in the other half. Be consistent and move to the modern nullptr.
Design
Not sure I agree with creating a container by using a smart pointer. These are both types of memory management. Using one to implement the other seems a bit counterproductive. But others have done it so why not.
Design Semantics
Your design does not do what I would expect on a copy.
Queue<int>  q1;
q1.add(1);
Queue<int>  q2(q1);
q1.add(2);

// In the case I would expect q2 to be a copy of q1 before we add 2.
// I would expect the two lists to be independent (If I wanted the
// to represent the same queue I would have used a reference).
// Your class both objects refer to the same underlying list. Thus
// at the end both lists have two elements in them.

Note: You basically relied on the rule of zero. When you need to implement the rule of five (three).
Rule of Zero: You don't do resource management because that is done by a resource class you use (in your case std::shared_ptr). The default constructors/assignment/destructors use the members versions automatically and thus save you from doing work.
Rule of Five: You override the default constructor/assignment/destructors to handle resource management and define the copy/move semantics of your class.
Leading Underscore.
Your use of leading underscore is technically fine. BUT the rules for using a leading underscore are more complex than most people know so prefer to avoid its use.
Also it looks ugly as hell. If you are trying to separate local variables from member variables a better technique is to give the variables obvious descriptive names.
Error:
const T Queue<T>::remove()
{
    if (_first == nullptr) return NULL;

This only works if the type T can be constructed by passing NULL (since NULL can be converted to 0 anything that takes an integer can also be constructed).
If you there is nothing to remove from the Queue then your code (that calls the Queue) has an error in it so in this case you should be throwing an exception of something along these lines.
Overkill
This is a lot of extra work:
T val = ptr->_data;
ptr.reset();
--_size;
return val;

You can replace this with:
--_size;
return ptr->_data;
// The destructor of ptr (which is a smart  pointer) will be called
// and tidy up the data and resources).


Write a function named isSuper that returns 1 if its array argument is a isSuper array, otherwise it returns 0

It's easier to use the enhanced for loop like this:

    for(int value : a) {
        if(value <= sum)
            return 0;
        sum += value;
    }
    return 1;

This also clears up some unnecessary lines like checking if the function should break and return. When you return a value, it immediately leaves the function. Therefore, you don't need to break then return. If all value pass the for loop, then it will return 1.

Also, you might want to return boolean instead of int in your method because it's just true or false.


This is a classic interview question.  At this point, I think it measures more whether you've been to many interviews than whether you can think creatively algorithmically while on a job interview.  Anyway,

public class Node {
  public Node next = null;
  public Node() {}
  public Node(Node n) { next = n; }
  public boolean hasNext() { return next != null; }
  public boolean hasLoop() {
    Node n = this, n2 = this;
    while (n.hasNext()) {
      n = n.next;
      if (n == n2) return true;
      if (!n.hasNext()) return false;
      n = n.next;
      if (n == n2) return true;
      n2 = n2.next;
    }
    return false;
  }
}

(Not compiled, but you get the idea.  I think getters/setters for next is overkill, given that the whole point is to manipulate the field at a low level, given this data structure.)

This uses constant space; since n travels twice as fast as n2, if there is a loop, both n and n2 will get caught at it and n will overtake n2 from behind (after a maximum number of steps equal to twice (lead-in plus loop length)).  Otherwise, n will reach the end and we're done.


Project Euler 21: Sum of amicable numbers optimisation

Integer Division

Python comes with a built-in integer division operator.  So instead of writing int(c / 2) + 1, you could simply write c // 2 + 1.  It is slightly faster.

Unnecessary List Creation

Creating a list of factors just to sum(factors) afterwards is unnecessary busy work, which takes time.  Simply add up the factors as you find them:

def factor(c):
    total = 0
    for d in range(1, c // 2 + 1):
        if c % d == 0:
            total += d
    return total

Or, use a generator expression with sum():

def factor(c):
    return sum(d for d in range(1, c // 2 + 1) if c % d == 0)

There is no need to store the factors you found.

Move Invariants out of Loops

Consider:

def sum_ammicable(x):
    ...
    for a in range(1, x):
        for b in range(1, x):
            if a != b:
                if factor(a) == b and ...:
                    ...
    ...

How many times is factor(a) computed when a==1?  If x == 10000, it gets computed 10000 times ... once for each b value.  How many times when a==2?  It'll get computed 10000 times as well.  But does factor(a) depend on the value of b?  No.  Each time you compute factor(a), for the same value of a, the same result is produced.

Can you calculate this value once per a loop?  Sure!  Move it out of the b loop!

def sum_ammicable(x):
    ...
    for a in range(1, x):
        factor_a = factor(a)
        for b in range(1, x):
            if a != b:
                if factor_a == b and ...:
                    ...
    ...

Instead of computing factor(a) 100,000,000 times, you now only compute it 10,000 times, which should be a significant improvement in speed.

Finally, considering that:

        for b in range(1, x):
            ...
                if factor_a == b and ...:
                    ...

will only execute the rest of the if statement (and perhaps the body of the if) for exactly one value of b, do you really need to loop over all 10,000 possible b values?  With a little thought, and a little reworking of the code, you can remove the b loop altogether!

Group Related Code Together

You start with

start = time.time()

n = int(input("Enter a number"))

then 2 function definitions, and then you continue with mainline code:

print(sum_ammicable(n))

end = time.time()
print(end -start)

Move the code together, after the function declarations.  Even better, place it inside a if __name__ == '__main__': guard, so you can import factor(c) and sum_ammicable(x) functions into other code:

if __name__ == '__main__':

    start = time.time()

    n = int(input("Enter a number"))

    print(sum_ammicable(n))

    end = time.time()
    print(end - start)

Now that this code isn't separated by 2 functions, it becomes apparent you are timing how long the user takes to "Enter a number" in addition to the time it takes to compute sum_ammicable(n).  Is the user's reaction & typing speed really being profiled here?  Perhaps you want to move start = time.time() after the input statement.

Pro tip: use time.perf_counter() instead of time.time() for higher accuracy profiling.

Algorithmic improvements are covered on the Project Euler site itself.  Read the problem overview after successfully completing the problem for some additional dramatic improvements.  There is no need to reproduce their analysis here.


Scheme/Racket: idiomatic infix math evaluator

Here are my review comments on the tokeniser:

It's unusual to prefix symbols with -. The indentation should be enough to tell you the "nesting level" of the inner functions, without having to put -s in front.
Your inner -tokenize could be hoisted into a named let, so that your tokenize function looked like this (I will make other changes to the function later, but for now I try to keep as close to your original code as possible):

(define (tokenize)
  ;; other internal definitions

  (let recur ([first (read-char)]
              [endchar #\newline])
    (if (equal? first endchar)
        '()
        (let ([operator (-tokenize-operator first)]
              [number (-tokenize-number first)]
              [openparen (-tokenize-openparen first)])
          (cond
            ([pair? operator] (cons (car operator) (recur (cadr operator) endchar)))
            ([pair? number] (cons (car number) (recur (cadr number) endchar)))
            ([pair? openparen] (list (recur (cadr openparen) #\))))
            (else (recur (read-char) #\newline)))))))

Character comparisons can use eqv? instead of equal?. Not really a biggie, but usually I reserve equal? for deep comparisons.
Use #f for false/null values, not '(). In Scheme, #f is the only false value there is; '() is a true value (like everything else). Though, instead of all those different tokenising helpers, and calling them all and then only using one of the return values, it would be nicer to test directly in the cond.
Instead of all the repeated (read-char)s, you might consider using a port stream instead. Create one using sequence->stream, then you can call stream-first and stream-rest on it.

With all that in mind, I'd write the tokeniser like so:

(define (tokenize [port (current-input-port)])
  (let recur ([str (sequence->stream (in-input-port-chars port))])
    (cond [(stream-empty? str) '()]
          [(char-numeric? (stream-first str))
           (let loop [(str str)
                      (digits '())]
             (if (and (not (stream-empty? str))
                      (char-numeric? (stream-first str)))
                 (loop (stream-rest str) (cons (stream-first str) digits))
                 (cons (string->number (list->string (reverse digits)))
                       (recur str))))]
          [(char-whitespace? (stream-first str))
           (recur (stream-rest str))]
          [else (cons (stream-first str) (recur (stream-rest str)))])))

(Comments on the evaluator to come later.)


Major remark of the code as whole: for some reason you write the unreadable version of array access *(arr+i) all over the place. Don't do that! This makes your code look needlessly obscure and hard to read. Instead use the much more readable arr[i].

Your compare is just a naive implementation of strchr. It would be much more efficient to use strchr.

Don't write while loops when you can write for loops, the latter is easier to read and often optimizes better too.

There is no point in const qualifying parameters passed by value - it only confuses the caller. Though this is a bit subjective and coding style.

The "correct naive" implementation of strchr would rather look like this:
  static const char* compare (char value, const char *parse)
  {
    for(size_t i=0; parse[i] != '\0'; i++)
    {
      if(parse[i] == value)
      {
        return &parse[i];
      }
    }
    return NULL;
  }

Since you don't use the above version but just return 1 or 0, you end up calling compare over and over on the same data, which is inefficient. If you had a version returning a pointer or index, you could continue searching from that location at next iteration, instead of starting over.

You can get rid of the "on error goto" pattern and leave all clean-up to a wrapper function. It's a bit more readable and you don't have to suffer the old "goto considered harmful" debate yet again:
  size_t parse_string (/* params */)  // wrapper function
  {
    // declare all resources potentially needing clean-up here:
    char **temp_matrix = NULL;
    ...

    bool ok;
    ok = actual_function (/* params */); // the algorithm, private static inline

    if(!ok)
    {
      if(temp_matrix != NULL)  // the clean-up code from your FAIL0 label here
      ...
    }
  }

Upon failure, "actual_function" just return false; and then the wrapper function can worry about clean-up.
(For more intricate scenarios like some opaque struct allocated by your lib, you can move the whole clean-up code into yet another public "destructor" function.)

Generally, more than 2 levels of indirection is bad practice, but your scenario here is one of the very few cases where three *** is actually motivated. However, char *** const means that the outer-most pointer is const-qualified, which is just weird. The caller doesn't care if you change that local variable internally or not, it just serves to confuse the user. Again, just drop const of parameters passed by value. In this case the char*** passed by value.

Don't name your variables with identifiers used by C++ keywords, functions, libraries etc. Like string. Even if you never intend to use the code with C++, many IDE use same code formatting and color coding for C and C++, like this site for example.


I can totally understand the frustration of your colleague that will need to maintain this code.

But would have been more constructive to tell that this code is considered a "mess" mainly because:

Logic of fetching order status is mixed in the middle of table rendering;
"Dirty" formatting: inconsistent indentation and trailing spaces;

The exact same thing could be better expressed like that:

<?php
function getOrderTrackingStatus($orderId) {
    $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
    $url.= "?awb=awbnumber&order=$orderId&username=admin&password=admin123";

    $ch = curl_init();
    // some curl code
    $res = explode("\n", $output);

    $status = isset($res[13]) ? $res[13] : null;
    return $status;
}
?>

    <button type="button" class="call">Show Status</button>

            ORDERID
            Status

    <?php $tabindex = 1; ?>
    <?php foreach($orderrecords as $record): ?>

        <tr class="table-row"
            id="table-row-<?php echo $record['id']; ?>"
            tabindex="<?php echo $tabindex++; ?>">

                <input type="checkbox"
                       name="assigneeid"
                       id="assigneeid-<?php echo $record['order_id']; ?>"
                       value="<?php echo $record['order_id']; ?>"
                       onclick="assignorderids('<?php echo $record['order_id']; ?>')">

            <?php echo $orderId; ?>
            <?php echo getOrderTrackingStatus($orderId); ?>

    <?php endforeach; ?>

Ideally this getOrderTrackingStatus function would be moved somewhere else, instead of living inside the same file that handles data visualisation.

Hope it helps you, and depending on your project you should consider using a templating engine as a way to force yourself to move logic code away from the views.


FileSystemWatcher firing multiple events

I copied your code into a new console application. Your constructor is "eating" the base default constructor, and now I can't pass a path parameter, I have to trust that filename will work if I give it a folder path. Let's see..

public ModifiedFileSystemWatcher(string filename="", string filter="*.*"):base(filename,filter)
{
    /* constructor */
}

This would be easier to read on two lines:

public ModifiedFileSystemWatcher(string filename="", string filter="*.*")
    : base(filename,filter)
{
    /* constructor */
}

Changing the names of constructor arguments is confusing. In this case you're passing filename as the base constructor's path parameter, but filter is passed as filter. I would rename filename to path to avoid confusion.

The optional parameters are surprising, too - a FileSystemWatcher exposes a parameterless constructor, one with only a path, and one with both a path and a filter. Your optional parameters add a constructor for a filter without a path.

This is a rather unusual way of assigning a value in a dictionary:

BooleanWrapper w = new BooleanWrapper() { value = true };
BooleanWrapper t;
if (raiseEvent.TryGetValue(e.FullPath, out t))
{
    t.value = false;
    t = w; //store current reference in dictionary
}

This might work, but I find raiseEvent[e.FullPath] = w; makes the intent much more explicit.


Combine similar methods with different text?

I can't say that it's going to be more efficient, or better designed, but one option is to take advantage of polymorphism by creating a set of classes for this.

public abstract class GuessBase
{
   protected abstract string GuessMessage { get; }
   protected abstract string WrongMessage { get; }
   protected abstract string RightMessage { get; }

   protected abstract int GetGuess();

   public void DoGuessing()
   {
        Console.WriteLine(GuessMessage);
        while (guess != number)
        {
            if (GetGuess() != number)
                Console.WriteLine(WrongMessage, guess);
            tries++;
        }
        Console.WriteLine(RightMessage, number, tries);
        Console.ReadLine();
    }
}
public class AIGuess : GuessBase
{
   protected override string GuessMessage
   {
      get
      {
         return "You generated a number between 1 and 100. Let me try";
      }
   }
   // Similar for WrongMessage and RightMessage

   protected override int GetGuess()
   {
      return Pick(number, ref guess);
   }
   // Put Pick() method here.
}
public class UserGuess : GuessBase
{
   protected override string GuessMessage
   {
      get
      {
         return "I generated a number between 1 and 100. Can you guess it?";
      }
   }
   // Similar for WrongMessage and RightMessage

   protected override int GetGuess()
   {
      int guess;
      int.TryParse(Console.ReadLine(), out guess); // This won't do what you want if the user doesn't provide a valid number.
      return guess;
   }
}

Then, in your main code, do this:

GuessBase guess;
if (/* AI */) guess = new AIGuess();
else guess = new UserGuess();
guess.DoGuessing();


Your date format is unconventional, because the minutes are not zero-padded.  You could use %02d instead of %s, but an even better solution would be to use now.strftime('%d/%m/%Y %H:%M') or '{:%d/%m/%Y %H:%M}'.format(now).

PEP 8 says that you should put import statements at the top, for maintainability.

Calling open() in the context of a with block, as you have done, is good practice, as it means it will be automatically closed when exiting the block.  Therefore, you should eliminate the myFile.close() calls.

The three output blocks should be combined into one.

from datetime import datetime

now = datetime.now().strftime('%d/%m/%Y %H:%M')
class_number = input('Please enter your class number: ')

if class_number in ['1', '2', '3']:
    with open('class{}.txt'.format(class_number), 'a') as f:
        f.writelines((user_name, ' ', str(total_score), ' ', now, '  '))

Contrary to its name, writelines() does not actually add line termination characters to the output.  If you intend to append multiple records to a file, it would be better to put each record on a separate line.  In that case, consider using a csv.writer with delimiter=' ' to output tabular data.

import csv

…

if class_number in ['1', '2', '3']:
    with open('class{}.txt'.format(class_number), 'a') as f:
        writer = csv.writer(f, delimiter=' ')
        csv.writerow((user_name, total_score, now))


Before thinking about making it efficient, I would worry more about making it clear, natural, intuitive. In your description you mention the notions "travel plan" and "travel event", and it's not easy to find the correspondence in the code. It would be easier to understand the overall design if the connection was more clear, for example if you had classes like TravelPlan and TravelEvent.

There are some other minor problems too with the code.

Drop this comment:

# Create your models here.

(I know it's automatically generated by Django, you're supposed to delete it after you created some models, which you already did.)

These imports are unused, so it's better to delete them:

import datetime

from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.utils import timezone

According to PEP8, you should put 2 blank lines before each class definition.

Also, classes in Python should be named CamelCase without underscores,
which is violated by Post_Entry.

It's good to declare closely related fields next to one another.
For example here:

    created_by = models.ForeignKey(auth_user_model, verbose_name=_("created by"))
    categories = models.ManyToManyField("Category", verbose_name=_("categories"), blank=True)
    created_on = models.DateTimeField(auto_now_add = True)

It would be better to move categories out from between created_by and created_on.


Sidebar menu to hide or expand parts of a form

I think, your improved code looks okay temporarily until you try to add new functionalities.

A function should do only one thing.

Trying to add a custom functionality to your improved code would result in clutter and more if else statements.


Welcome to Code Review and coding in general:

Code according to PEP8 – In your case this means using snake_case for variable and function names, add spaces after commas and between operators. Your code does look rather nice in general, some minor nitpicks here and there, but read through the guidelines and try to adhere to them.
Feature: incorrect_possibilities = possible_answers invalidates possible_answers – When you later on do incorrect_possiblities.remove(correct_answer) this also changes possible_answers. To get a copy you need either to use a better variant of copy, or simply incorrect_possibilities = possible_answers[:]. The latter one uses slicing to denote the entire array, and makes a copy of the sliced area.
Use ternary related to chosen_strategy - Based on the chosen strategy you choose either of two choices, this can be coded as final_answer = correct_answer if chosen_strategy == 1 else your_answer, and similar in the other cases.
Use ternary related to print output also – This can also be used in print out as well:

print("Which means it is either your answer: {}, or the only other remaining option, {}.".format(
      correct_answer if your_answer == correct_answer else  your_answer,
      other_remaining if your_answer == correct_answer else correct_answer))

Use the newer print('You chose {}'.format(final_answer) syntax – This is the preferred version for new code in Python 2 and for code in Python 3. See Format specification mini language for examples and specification.
Use docstrings, """ ... """, and not comments, # ..., when describing modules, functions, classes and methods. – If you use docstrings they can be used by your IDE or documentation tools, and it is according to the Pythonic way. :-)
Avoid one-time temporary variables – The playagain can be dropped if you use while True: to keep the game going, and change the end to something like if int(raw_input("Play again (0 = no)?")) == 0: break. (Preferrably with a newline before the break, which does break out of the while loop)
Possibly add a loop or validation on the main loop – If you enter something when choosing between playing one game at a time, or play a chosen number of games, you can enter something wrong and the script terminates. This could possibly be enhanced by adding a while loop around it.

Do also note that if you enter non-numeric text your code breaks very easily...  Look into making a general int input function which uses try ... except around the input function.
Introducing the if __name__ == '__main__': idiom – The previous code is often used to make the code reusable as a module, and to have as little code as possible at the top level. Combined with a main() function your code easily be reused and extended.

In your case you could use (possibly extended with the while loop):

def main():
    game_choice = int(raw_input("Play one game at a time (1) or play your chosen number of games with one strategy (2)? > "))
    play_chosen_game(game_choice)

if __name__ == '__main__':
    break

Consider shortening the text length – Your texts are rather worthy, and could benefit from being shortened a little.

Conclusion

Your code does look good for a beginner, and naming is good (with the exception of not using underscores in between words). You could benefit from learning to use the ternary operator (a if b else c), and a slight justification on using functions related to top level code and text lengths.


Is this C++11 seqlock implementation correct?

My guideline on memory orders is "Just say no"; I guarantee that if you're using them, you're using them wrong. :)  So I won't attempt to find the exact bug, I'll just assume they all say seq_cst. The only thing I'll say about your memory orders is, when you write

    seq_.store(seq0 + 1, std::memory_order_relaxed);
    std::atomic_thread_fence(std::memory_order_release);

can you explain how that's different from

    seq_.store(seq0 + 1, std::memory_order_release);

?

Seqlock(T value = T())

This constructor should be explicit; otherwise you're accidentally permitting

Seqlock<int> s = 42;

and in fact because of C++17 CTAD you're also permitting

Seqlock s = 42;

Rule of thumb: make all constructors explicit except for those you want the compiler to be able to call implicitly (i.e., copy and move constructors).

In T load() const, you load seq1 at the bottom of the loop, and then go around again and immediately load seq0 from the same location. You could just have set seq0 = seq1; i.e.

T load() const {
    int seq1 = seq_.load(std::memory_order_relaxed);
    while (true) {
        int seq0 = seq1;
        if (seq0 & 1) {
            // cpu_relax();
        } else {
            std::atomic_thread_fence(std::memory_order_acquire);
            T ret = val_;
            std::atomic_thread_fence(std::memory_order_acquire);
            seq1 = seq_.load(std::memory_order_relaxed);
            if (seq0 == seq1) {
                return ret;
            }
        }
    }
}


Would my implementation of this enum pass?

Why are you giving seperate implementations for each enum value? All getTitle() and getFragmentToAdd() implementations are the same.

enum class ImageHolderEnum(
    val titleId: Int,
    val qFragment: BaseFragment,
    val fragment: BaseFragment
) : IPageHolder {
    PAGE1(R.string.tab_shop_baby, BabyTwoFragment(), BabyThreeFragment()),
    PAGE2(R.string.tab_shop_mom, MomThreeFragment(), MomTwoFragment()),
    PAGE3(R.string.tab_shop_dad, DadTwoFragment(), DadThreeFragment()),
    ;

    override fun getTitle(): Int = titleId
    override fun getFragmentToAdd(): BaseFragment = if (isFeatureAllowed()) qFragment else fragment

    fun isFeatureAllowed(): Boolean  {
        val qSlideConfig: QSlideConfig by remoteFeatureFlag() // Kind of dependency injection here
        return qSlideConfig.isQSlideEnabled()
    }
}

Interfaces can also have properties, so there's no need to have getTitle() as a function, when it can just be a value.

interface IPageHolder {
    val titleId: Int
    fun getFragmentToAdd(): BaseFragment
}

And you can then use it like this in the enum class:

enum class ImageHolderEnum(
    override val titleId: Int,
    ...


Your code looks pretty good to me, only that it's very imperative. I know it's not for everybody's taste, but a functional approach on text processing is also feasible.

My take: you start by defining an object (which may be a hash) to store the state (needed for in intermediate iterations and the final result), and then fold (reduce/inject) over the input lines, returning the next state on each step.

There are some edge cases (lines with multiple or nested comment) which I won't consider, let's keep it simple. I'd write:

initial_state = {lines: 0, comments: 0, in_multiline_comment: false}
final_state = open("test.txt").lines.inject(initial_state) do |state, line|
  state_update = if state[:in_multiline_comment]
    {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\*\//)}
  else
    case line
    when /\/\*/
      {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\*\//)}
    when /\/\//
      {comments: state[:comments] + 1}
    else
      {lines: state[:lines] + (line.strip.empty? ? 0 : 1)}
    end
  end
  state.merge(state_update)
end

Notice that you don't worry about stateful variables anymore, we just think "if I have this input and this current state, what output would I want?". Once you've covered all scenarios, the algorithm is done (hopefully leaving behind a declarative and maintainable code).


Repetitive controller with all methods nearly identical

Some notes:

I don't know if there is an agreement on the community on that, but I would definitely use the de-facto language of the computer industry (translating the API routes if needed, of course).
I'd write parens on "normal" (non-DSL) method calls.
That's a lot of actions. Why don't you refactor it to have a unique action with a param?

I'd write:

class API::V1::ReceptionController < API::V1::APIController
  before_filter :ensure_document_exists
  WorkerClasses = {:produto => ProdutoWorker, ....}

  def process
    worker_class = WorkerClasses[params[:key].to_sym]
    if worker_class
      jid = worker_class.perform_async(params[:document])
      render(json: {jid: jid}, :status => 200)
    else
      render(json: {errors: "Unknown key: #{params[:key]}"}, :status => 400)
    end
  end

(and change the routes accordingly, of course)


Good work!
Do not polute the global namespace in headers
using std::unordered_map;
...

Anyone who #includes your file will have these imported in their global namespace. You should should migrate these to your .cpp file, and just use std:: for the two instances in the header.
list<> vs vector<>
There is nothing in your code that suggests list<> is preferable to vector<>. Unless you need fast insertion/removal in the middle of the structure, vector<> is preferable here.
For each ( in ) is not a thing
for each (auto elem in adjList) is not standard C++, but a MSVC extension, use range-based for instead. Furthermore, by using auto instead of auto &, you are working on copies of the adjacency list, not references.
You want this:
for(auto const& elem : adjList) {

Don't use for_each when a range-based for works.
for_each is not best practice unless you are already manipulating a predicate. range-based-for is preferable:
Like so:
for(auto const& val : elem.second) {
    cout << val.second << "(" << val.first << "), ";
}

Emplace into containers
You want to use emplace_back() instead of push_back() in containers where possible:
Like So:
list<edge> C;
C.push_back(make_pair(1, 'A')); // bad
C.emplace_back(1, 'A'); // much better

Move containers if you know you are done with them.
When you do this:
adjList['A'] = A;

You create a copy of A, when you know you are done with it. You should promote A to a RValue:
adjList['A'] = std::move(A);

You are mixing your functionality with your test harness
createGraph(); and test(); have no business being members of this class, and should be free-floating functions.
Once you do this, you will realize that there is a lot of stuff missing from your class as it does not expose the interface required to implement these simple cases.


Refactoring ViewModel and mapping from multiple sources

When you have multiple sources of data you can still combine them into a single ViewModel in the Controller.  If you have really "heavy" ViewModels that's an indication that you're displaying a lot of data at once, maybe you can find a way to break that up.  Sometimes you can't due to requirements, but if you can that'd make both your life and your user's life easier (they wouldn't have to see/think about as much either).

In this case, your ViewModel doesn't look like it has that many properties: PlacesList, ServicesList, ContractorsList, StatusList, TaskEvent, and BKQContact.  ViewModels for standard contact forms can have more properties.  For example: FirstName, LastName, MiddleInitial, AddressLine1, AddressLine2, City, State, ZipCode, PhoneNumber.  I don't think anyone would bat an eye over those properties in a ViewModel.

The first thing I'd do is reverse the if condition and move it right under the first line, where you're initializing BKQEventData.  var cutomData... relies on BKQCustomData, but it's using it before the null check; if BKQEventData is null it looks like you'll get a Null Pointer Exception (NPE).  Reversing the conditional is a matter of preference, but it prevents some indentation in some cases.  So:

BKQEventCustomData BKQEventData = BKQHelper.ParseBase64EventData(Server.UrlDecode(Request.Url.Query));

if (BKQEventData == null)
{
    return RedirectToActionPermanent("Login", "Login");
}

The next big thing I see is how many lines you have dedicated to setting up the TaskEvent.  I'm guessing the TaskEvent is something you've defined in your project.  With the exception of the Title property, all thirteen properties are derived from BKQEventData.  You could add a method (or maybe a constructor) to TaskEvent that accepts a BKQEventCustomData and returns a TaskEvent.  Or, if you don't have access to TaskEvent, you could make an extension method:

public static class TaskEventExtensions
{
    public static void InitalizeWithBKQEventCustomData(this TaskEvent taskEvent, BKQEventCustomData customData)
    {
        taskEvent.BKQCustomData = customData.custom.data.ToString();
        taskEvent.BKQCustomDataType = customData.custom.type.ToString();
        taskEvent.BKQClientId = customData.xcm.clid;
        taskEvent.BKQOperatorId = customData.xcm.opid;
        taskEvent.BKQInfProductId = customData.xcm.iprodid;
        taskEvent.BKQEventHistoryId = customData.xcm.evnhid;
        taskEvent.BKQEventTypeId = customData.xcm.evntype;
        taskEvent.BKQEventCaseId = customData.xcm.caseid;
        taskEvent.BKQQuota = customData.xcm.quotaid;
        taskEvent.BKQLangId = customData.xcm.langid;
        taskEvent.BKQContactId = customData.xcm.contid;
        taskEvent.CreatedBy = customData.xcm.opid;
        taskEvent.ModifiedBy = customData.xcm.opid;
    }
}

Going by this snippet I don't think that cutomData is used anywhere; if you're not using it, get rid of it.  Dead code is a little messy and can make things confusing.

You could also use object initialization notiation to set up the majority of the ViewModel.  It's a bit of a matter of preference, but I like it.  Something along the lines of:

var model = new TaskEventViewModel {
    BKQContact = BKQFramework.Contact.GetById(BKQEventData.xcm.contid),
    ContractorsList = new SelectList(_contractorService.GetContractorsByClientId(BKQProfile.ClientId), "ContractorId", "BKQFullName"),
    PlacesList = new SelectList(_placesService.GetPlacesByClientId(BKQProfile.ClientId).Where(p => p.Active), "PlaceId", "Name"),
    ServicesList = new SelectList(_serviceService.GetServicesByClientId(BKQProfile.ClientId).Where(s => s.Active), "ServiceId", "Name"),
    StatusList = new SelectList(_statusService.GetStatusByClientId(BKQProfile.ClientId), "StatusId", "Name"),
    TaskEvent = new TaskEvent {
        Title = string.Empty
    }
};

model.TaskEvent.InitalizeWithBKQEventCustomData(BKQEventData);

Although I would probably pull the SelectLists out into their own variables.  They're a little long, but you'd have to figure out how to best name/break them up.

Something else that I'd look at offhand is what happens when AuthenticateRequest fails?  I have no way to tell in this snippet, but it doesn't look like it's handled.

So taking a pass at this using the extension method I mentioned earlier, this is what I got.  It's a bit of a readability improvement to me.  Again, the biggest thing that still stands out at me is how long those new SelectList lines are; I'd definitely break those into their own lines with a variable describing what exactly they are.  Maybe something like:

BKQEventCustomData BKQEventData = BKQHelper.ParseBase64EventData(Server.UrlDecode(Request.Url.Query));

if (BKQEventData == null)
{
    return RedirectToActionPermanent("Login", "Login");
}

AuthenticateRequest(BKQEventData.xcm.clid, BKQEventData.xcm.opid);

var clientsContractors = new SelectList(_contractorService.GetContractorsByClientId(BKQProfile.ClientId), "ContractorId", "BKQFullName");
var activePlaces = new SelectList(_placesService.GetPlacesByClientId(BKQProfile.ClientId).Where(p => p.Active), "PlaceId", "Name");
var activeServices = new SelectList(_serviceService.GetServicesByClientId(BKQProfile.ClientId).Where(s => s.Active), "ServiceId", "Name");
var clientStatuses = new SelectList(_statusService.GetStatusByClientId(BKQProfile.ClientId), "StatusId", "Name");

var model = new TaskEventViewModel {
    BKQContact = BKQFramework.Contact.GetById(BKQEventData.xcm.contid),
    ContractorsList = clientsContractors,
    PlacesList = activePlaces,
    ServicesList = activeServices,
    StatusList = clientStatuses,
    TaskEvent = new TaskEvent {
        Title = string.Empty
    }
};

model.TaskEvent.InitalizeWithBKQEventCustomData(BKQEventData);


Multiplication table using a list comprehension

Your function could be simplified a little, and I find it helpful to define functions using declarations, since type signatures are really helpful (although admittedly your example is simple enough that it doesn't matter):

timesTable :: Int -> Int -> [[Int]]
timesTable n u = [[y * x | x <- [1 .. u]] | y <- [1 .. n]]

The key thing I noticed was that you were using n-y: it should be obvious that this part of the expression becomes the following values in each iteration of y: [n-(n-1), n-(n-2), ... n-0], which is just [1 .. n].


Your function returns error, but actually you don't return it and exit in the function body when opening the file:
func getFileContent(filename string) (records[][] string, err error) {
        fd, err := os.Open(filename)

        if err != nil {
                exit("Problem with opening the file")
        }

        reader := csv.NewReader(fd)
        return reader.ReadAll()
}

From the point of error handling it will be more consistent to return error:
fd, err := os.Open(filename)
if err != nil {
   return nil, err
}

The file was open, but not closed: defer fd.Close().
I don't remember flag package, but if it is not ensure the presence of parameter you need to check filename != nil:
records, err := getFileContent(*fileName)

Here you have created new goroutine, but returns the result via global variable correctAnswers:
done := make(chan bool)
go provideQuestions(records, done)

It stops working if you decide to improve your game and allow more than one person to play on the same time. You will have race condition on this variable. Much better return the value from goroutine using channel.
You already have such channel - done, just change its type to channel of int and return the number of correct answers using it.


(Ruby version) Rotate linked list to the right by k places

My ruby is a little rusty, but I can give you some general pointers.

First off, this isn't really a linked list. You use an array in LinkedList. That is not how a linked list works. A linked list does not maintain an array of all of its nodes. If it is singly linked (usually the forward direction, which is what you're doing with next_node) then LinkedList should only hold the head of the list. So, first thing's first let's fix that. You also shouldn't expose Node. Your constructor is also a little strange. I'd expect it to work like the builtin Array. Namely, you don't pass nodes. You pass a size and a value or a size and a block to Array.new or through a separate method (Array()) something that is  to_ary or to_a-able.

Again my ruby is rusty, but that would probably look something like this:

class LinkedList
  attr_reader :length
  alias_method :count, :length

  def initialize(length: 0, value: nil)
    @length = length

    (0..@length).reduce(Node.new) do |last_node, i|
        node = Node.new(if block_given? yield i else value end)
        last_node.next = node
        @head = node if i == 0
        node
    end
  end

  def first
    @head.?value
  end

  # Technically incomplete
  # if !block_given?, then it should return an enumerator
  def each
    node = @head
    while !node.nil?
        yield node.value
        node = node.next
    end
  end

  def to_a
    values = []
    each { |v| values << v }
    values
  end
end

def LinkedList(values)
    values = values.to_ary if values.respond_to?(:to_ary) else values.to_a end
    LinkedList.new(values.length) { |i| values[i] }
end

There may be a more elegant way to build the list from an arrayable (without needing to first construct the array), but it's not coming to me now. For completeness's sake, you probably want to also define the usual Enumerable methods (particularly each) so that you can test this. I provided first and each as examples of following the Enumerable convention.

Differentiating between rotate and rotate! is good. And your code reuse there is pretty nice (although given my qualms with the use of the array, I'm not a fan of rotate_nodes, more on that in a second). However, I'd recommend some further refactoring. It's unclear to me whether rotate is left or right. How about making it explicit: rotate_left, rotate_left!, rotate_right, and rotate_right!? And why not accept 0 or negative rotations? Let's say we defined right rotation. We could then define left rotation like this:

class LinkedList
  # ...

  def rotate_left(delta)
    rotate_right(-delta)
  end

  def rotate_left!(delta)
    rotate_right!(-delta)
  end

That feels much cleaner to me. I also wouldn't put the restriction that delta must be less than the length of your list (something you should definitely store by the way, don't rely on storing all the nodes in an array!). Instead, modulo the delta by the list length. So if the list has 5 elements and you rotate right by 7, that's the same as rotating right by 2. And if it isn't clear, rotating left by a negative amount should rotate right and vice versa.

Now, onto a more core problem. We'll start with your map in rotate_nodes:

def rotate_nodes(k)
  # ...

  @nodes.map do |node|
    n = @nodes.find_index(node)
    # ...
  end

find_index is O(n). There's no reason to do this. This ends up being O(n^2). Instead use @nodes.each_with_index.map { |node, index| # ... }. But, like I've mentioned before, you shouldn't have @nodes in the first place. Without it, you have some concerns to deal with regarding the differences between your bang rotate methods and non-bang rotate methods. Namely this:

Let's say you added a first= method so you could change the value of the first element in the list:

  def first=(value)
    if @head.nil?
      @head = Node.new(value)
      @length = 1
    else
      @head.value = value
    end
  end

This could be used like so:

> a = LinkedList([1, 2, 3])
> a.head = 4
> a.to_a
[4, 2, 3]

Now, what do you expect when we do the following:

> a = LinkedList([1, 2, 3])
> a.rotate_right(1).rotate_left(1).head = 4
> a.to_a

rotate_left and rotate_right aren't bang methods, so we don't expect to be able to change the underlying linked list. You demonstrate this understanding in how you initialize and return a new linked list for those methods. But, returning a new linked list isn't enough. rotate_right(1) is the equivalent of taking the tail of the linked list and placing it at the head. This can be done fairly trivially by moving some of the nexts around and then setting @head. But, if you share Nodes between LinkedLists, then that .head = 4 will modify the original list. I'm not sure that's the behavior you want. You'll have to think about the semantics you desire. It's clear that the bang methods should modify the existing LinkedList in place. But, it's less clear what an example like the one above should do. On the one hand, you could copy all of the nodes so that each Node belongs to only one LinkedList. However, this incurs a high memory penalty, especially if you didn't actually need the copy (say for some reason you just did a.rotate_right(10).head, you don't actually need the copy, this is equivalent to just getting the 11th element in the list). On the other hand, you could have Nodes belong to multiple LinkedLists. In this way a LinkedList behaves much more like a view than an independent collection. What I mean by this is my_list.rotate_right(10) isn't a new LinkedList really, it's just a different way of looking at my_link. Specifically, it's looking at my_list as if it started 11 elements in instead of where it's head currently is. I feel like the first approach doesn't make the copying obvious enough. You may want to avoid it entirely for something more explicit like requiring something like:

new_list = my_list.copy
new_list.rotate_right!(10)

If you prefer the second approach, I'd recommend making the Node's value immutable and severely limiting mutation on the lists. This is a space that functional programming languages have explored extensively. Mutation and multiple aliases often lead to disaster. It's best to pick one or the other.


Using a single validation handler for all controllers in a form

Just a few random observations:

foreach (TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))

tb is a bad name; without the explicit TextBox type one would have to read the entire part after the in, to figure out that we're talking about a TextBox. And it's not uncommon for loops to use implicit types, like this:

foreach (var tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))

Now in this part:

.Where(x => x.CausesValidation == true)

You're comparing a bool to true - that's a no-no. Write it like this instead:

.Where(x => x.CausesValidation)

It's probably also more readable to iterate over an identifier instead of an expression; I'd split it like this:

var textBoxes = Controls.OfType<TextBox>()
                        .Where(textBox => textBox.CausesValidation);

foreach (var textBox in textBoxes)
{
    // ...
}

Kudos for IsNullOrWhiteSpace:

if (string.IsNullOrWhiteSpace(currenttb.Text))

However, currenttb should be camelCase, and would be more readable as currentTextBox.

Careful with extra spaces:

string.Format("Empty field {0 }"

I don't think this is legal, should be "Empty field {0}".


You should be using function such as:

localStorage.setItem('points', JSON.stringify(points));
localStorage.getItem('points');

If you can use es6:

// instead of
var coords = e.get('target').geometry.getCoordinates();

var pointLat = coords[0],
    pointLng = coords[1];

// Could write
const [pointLat, pointLng] = e.get('target').geometry.getCoordinates();

// Why save points as variable if it's only used once
var points = getPoints(),
    newPoints = [];

newPoints = points.filter((point) => point.lat != pointLat && point.lng != pointLng);
// Could just do
var newPoints = getPoints().filter(point => point.lat != pointLat && point.lng != pointLng);


Some improvements:

var toStageCoord = map.stageXYToCoordinates(toStage.x + selection.x1, toStage.y + selection.y1);

var element1 = document.elementFromPoint(toStage.x + selection.x1, toStage.y + selection.y1);
var element2 = document.elementFromPoint(toStage.x + selection.x2, toStage.y + selection.y2);
var element3 = document.elementFromPoint(toStage.x + selection.x2, toStage.y + selection.y1);
var element4 = document.elementFromPoint(toStage.x + selection.x1, toStage.y + selection.y2);

if(element1.localName == "image" || element2.localName == "image" || element3.localName == "image" || element4.localName == "image") {
  console.log("foundfirst"); // 4
}
else { // 2
  var maxy = toStage.y + selection.y2; // 1
  var maxx = toStage.x + selection.x2;

  outerloop: // 2
  for(var y = toStage.y + selection.y1; y < maxy; y+=4) { // 1, 3

    for(var x = toStage.x + selection.x1; x < maxx; x+=4) { // 1, 3
      var element = document.elementFromPoint(x,y);

      if(element.localName == "image") { // 4
        console.log("found");
        break outerloop; // 2
      }
    }
  }
}

Comments:

These calculations were performed at every iteration of the loops, while they never changed. So, let's move them outside the loops.
Using a label, like this outerloop: one can direct break to which block/loop to exit. So, the variable found is not needed.
Depending on the images' sizes, you don't need to check every pixel. Try a larger gap, like 4 or even 10 pixels, as this would reduce the number of iterations.
In the first check the operator == is used, while in the loop === is used. As === checks the type of the value, too, it would be slower. If == yields the correct answer, too, then it should be used instead.


The customary name for what you called splitter would be delimiter or sep (the letter is used e.g. in split, the former for example in numpy). Regardless of what you choose, you should be consistent, right now you use both splitter and then later separator.

When using the with..as construct (as you should), you don't need to manually close the file. This is one of the reasons of why you should use it in the first place.

In your function write_score, you should use str.join.

In read_scores you can directly iterate over the lines of the file, which is a lot more memory-efficient. You can also use tuple assignment to make it clearer what is what.

In sort_scores, you can use sorted directly on zip, there is no need to cast it to a list first. You can also return the result right away.

In has_better_score you can just return the result of the comparisons.

In print_scores you can use str.join again.

#!/usr/bin/env python3

def write_score(score, name, scores, filename, splitter=','):
    """writes a score with a name to a file, in a specified format"""
    scores.append((score, name))
    with open(filename,'w') as f:
        for s in scores:
            f.write(splitter.join(map(str, s)) + '\n')

def read_scores(filename, splitter=','):
    """reads scores and names from a file, and returns a list of each"""
    scores = []
    names = []

    with open(filename) as f:
        for score in f:
            score, name = score.strip().split(splitter)
            scores.append(int(score))
            names.append(name)
    return scores, names

def sort_scores(scores, names, reverse_bool=True):
    """sorts the scores from greatest to least and returns in a list of tuples format"""
    return sorted(zip(scores,names), reverse=reverse_bool)

def print_scores(score_list, splitter=' ', top_amount=5):
    """prints the number of leaderboard scores stated"""
    for score_tuple in score_list[:top_amount]:
        print(splitter.join(map(str, score_tuple)))

def has_better_score(score, scores, leaderboard_len=5):
    """returns if the score should be written to a file"""
    return (len(scores) > leaderboard_len and score >= scores[leaderboard_len - 1][0]) or len(scores) <= leaderboard_len:

In your "small program", catching KeyboardException and then just exiting is not really different from letting the exception rise all the way to the top. Also, exit() should only be used in the interactive session, use sys.exit() in a script instead (because it allows passing of a return value).


Use NULL for null pointers

NULL conveys your intention to use a pointer better than 0:

if (file == NULL) { ... }

As a bonus, in C the macro NULL typically expands to something like (void*)0; if you have warnings for potentially unsafe type conversions enabled (-Wconversion for GCC), the compiler will notify you, if you try to assign 0 to a pointer or NULL to an integer, which helps to find potential errors.

Use puts when you don't use string formatting

printf("Error: Could not open source file\n");

could just as well be

puts("Error: Could not open source file");

While printf is great for formatted output, the look for formatting specifiers carries a computational overhead that puts doesn't have. Some compilers (like GCC) will perform that optimization automatically for you, if you use a format string literal without format specifiers.

Checking whether a characters is in a set of characters

In isInstruction(char), instead of using a series of disjoint (joint with the || operator) equality comparisons, you could much better express your intent and the source character set with strchr:

return strchr("+-><[].,", c) != NULL;

A possible improvements might be:

const static char brainfuck_alphabet[] = {'+', '-', '>', '<', '[', ']', '.', ','};
return memchr(brainfuck_alphabet, c, sizeof(brainfuck_alphabet));

The improvements lies in the fact that the algorithm of memchr can make an assumption about the size of the memory region to check while strchr cannot. This could lead to a performance improvement.

Use bool for boolean values

The header <stdbool.h> declares boolean-like types. You can use them to express your intention for a boolean return value of isInstruction():

bool isInstruction(char c) { ... }

Don't repeat yourself

While you generally did will to adhere to that principle, I want to point out one small spot that could use improvement:

printf("Error: cannot read more than 30000 instructions\n");

could be

printf("Error: cannot read more than %d instructions\n", MEMSIZE);

That way the error message would reflect the actual buffer size in case MEMSIZE was redefined. Since the argument list of printf is variadic and doesn't carry type information, it would be better yet to not make assumptions on the width of the integer type of MEMSIZE. What if someone defined MEMSIZE to be larger than MAX_INT? The best course of action would be to force MEMSIZE into the type size_t (more about that later).

printf("Error: cannot read more than %zu instructions\n", (size_t)(MEMSIZE));

Data types

You only ever store chars in instructions, so its type could just as well be:

char instructions[…];

On all 32- and 64-bit platforms you just saved 3*MEMSIZE bytes (which you could use to increase MEMSIZE again if that is a concern).
memptr, insptr and i are indexes of plain arrays. Therefore they should have type size_t, which is the type meant to reflect the size or position of things in memory.

Make the code flow of branches based on mutually exclusive conditions mutually exclusive

In the above code the conditions c == '[' and c == ']' cannot both be true since c isn't altered between them. To make this obvious to the reader and the compiler (though a good one should find that optimization itself), you should use mutually exclusive if … else if … statements:

        if (c == '[')
            balance++;
        else if (c == ']')
            balance--;

Exit with an error status in case of an error

Programs may convey information in their exit status. By convention the status 0 means “no error, everything performed according to your instructions”. Every other status value usually refers to an error condition but there is no general convention on what each value means. One attempt to conventionalize them can be found in the sysexits.h header. You could use it like this in your program:

if (file == NULL) {
    // ...
    return EX_NOINPUT;
}

if (balance < 0) {
    // ...
    return EX_DATAERR;
}

if (c != EOF && i >= MEMSIZE) {
    // ...
    return EX_SOFTWARE;
}

In a similar fashion you could return an error from runInstruction(), but we already know that we didn't accept any illegal instructions.

Print error messages on stderr

printf and puts write their data to stdout, the standard output stream, but you're also writing program output to stdout via putchar. To avoid mixing program output and error messages, you should write the latter to stderr instead:

fprintf(stderr, ...);
fputs(..., stderr);

Be aware that fputs doesn't append a new-line character like puts.

Print operating system error messages to provide hints to the user

Like many library functions relying on system calls, fopen sets the global errno variable to report the type of error. You can use functions like strerror or perror to decode the value of errno into a human-readable, localized(!) error message:

if (file == NULL) {
    perror("Could not open source file");
    // ...
}

Respect the principle of locality, avoid global variables

Global variables clutter the name space and make it more difficult to follow the flow of the program. They also prevent a method or set of methods from being reentrant, a property that allows them to be executed concurrently. (This matters not just for multi-threaded programs, but also if you wanted to, say, interpret multiple Brainfuck programs one instructions at a time in a round-robin fashion to see which program terminates first.)

One way to achieve this is to move more data and logic into the method:

int main(int argc, char *argv[])
{
    // ...
    char instructions[MEMSIZE];
    // ...
    runInstructions(instructions, i);

    return EX_OK;
}

void runInstructions(const char *const instructions, size_t instruction_count)
{
    size_t memptr = 0;
    size_t insptr = 0;
    int memory[MEMSIZE];

    while (insptr < instruction_count) {
        switch(instructions[insptr]) {
            // ...
        }
    }
}

You could also use an instruction pointer instead of an instruction index:

void runInstructions(const char *const instructions, size_t instruction_count)
{
    size_t memptr = 0;
    const char *insptr = instructions;
    const char *const instructions_end = instructions + instruction_count;
    int memory[MEMSIZE];

    while (insptr < instructions_end) {
        switch(*insptr) {
        // ...
        case '[':
            if (memory[memptr] == 0)
                // seek `]` forward
                while (*insptr != ']')
                    insptr++;
            break;

        case ']':
            if (memory[memptr] != 0)
                    // seek `[` backward
                    while(*insptr != '[')
                        insptr--;
            break;
        // ...
        }
    }
}

Use library functions where possible

Library functions unburden you from writing your own code. They're (usually) less likely to contain errors than hand-rolled solutions and the library authors may have included arcane, platform-specific performance optimizations in them.

To find the next closing bracket instruction you could write:

    case '[':
        if (memory[memptr] == 0) {
            // seek `]` forward
            insptr = memchr(insptr + 1, ']', (size_t)(instructions_end - insptr - 1));
        }
        break;

To find the last opening bracket you could write:

    case ']':
        if (memory[memptr] != 0) {
            // seek `[` backward
            insptr = memrchr(instructions, '[', (size_t)(insptr - instructions - 1));
        }
        break;

Avoid undefined behaviour

You can't be sure that argv[1] is defined. If it isn't its value may have NULL or garbage content. Check the value of argc first and print an appropriate error message if it's too small:

if (argc < 2) {
    fputs("Error: No source file specified.\n", stderr);
    return EX_USAGE;
}

If the Brainfuck program happens to have a branch depth greater than INT_MAX, the balance variable would overflow. It typically overflows to the value -1, which would be caught with a subsequent balance < 0 check, but in C signed integer overflow results in undefined behaviour. That means the compiler may assume that overflow never happens and optimize the negative balance check to always be false, which would leave your program in a weird state.

If you decide to care about that (INT_MAX+1 is 2^31 which would require a program of at least 2 GiB, all [, to trigger the bug on modern architectures after all), there are basically two approaches:

Use ssize_t instead of int. ssize_t covers a branching depth of almost (half) as many levels as the address space has bytes. It's quasi-impossible to generate and load a program of that size into the memory of your interpreter anyway, so you could consider your bases covered.
Check for overflow before increasing balance:

    if (c == '[') {
        if (balance == INT_MAX) {
            fprintf(stderr, "Error: Cannot handle branches deeper than %d levels.\n", INT_MAX);
            return EX_DATAERR;
        }
        balance++;
    }

Provide some debugging info to the programmer using your interpreter

It might be helpful for the user to know where in the program a parser error occurred, so you should keep track of the amount of bytes read so far:

size_t i = 0;
while (i < MEMSIZE && (c = fgetc(file)) != EOF) {
    read++;
    if(isInstruction(c)) { ... }
}

You can now report that value in parser error messages like so:

fprintf(stderr, "Error:%zu: Cannot handle branches deeper than %d levels.\n", read, INT_MAX);
fprintf(stderr, "Error:%zu: Encountered `]` before matching `[`\n", read);
fprintf(stderr, "Error:%zu: cannot read more than %zu instructions\n", (size_t)(MEMSIZE), read + 1);


Custom route for writing friendly URLs in ASP.NET MVC 3

Personally I think you are over thinking it. Why not just create a string extension method called FriendlyString or PrepareForUrl and then use the original route

@Html.ActionLink(Model.BlogPost.Title, "Index", "Post", new
{
   id = Model.BlogPost.Id,
   title = Model.BlogPost.Title.FriendlyString()
}, null)


Tree-view of Active Directory group memberships using recursion

Separating Presentation From Logic

You're mixing interface code with code that retrieves the group membership information and provides the logic of the script.

Consider separating these. Ideally, you would have a function that accepts as a parameter a user or group object, and returns some kind of object that contains all of that user's memberships (even if it's just a nested [hashtable]).

The object returned from this would be passed to another function to format it for display (creating the tree view).

A separate function or set of functions is responsible for getting the information from the user (prompting, validating, etc.).

This separation allows you to take the object with the actual data, and make other functions that use it (to display it graphically, to write it as structured data to an XML file or to a database, to gather statistics on it, whatever), or to use it in quick one-liners to test some logic.

Similarly, you can change the way the interface operates without worrying about breaking the logic. You can change the way the object is displayed without introducing errors in the other parts.

The way it is now, these are all intertwined in such a way that you can't easily change one thing without changing another.

Actual Code Stuff

Option 2

$continue = $false
while ($continue -eq $false) {
    $csv = read-host "CSV Filepath (no quotes!)"
    if ((test-path $csv) -eq $true) {
        $continue = $true
    }
    elseif ((test-path $csv) -eq $false) {
        write-host "Location $csv does not exist.  Please try again..."
    }
}

There are several things to note here:

if ((test-path $csv) -eq $true) {}

You don't need -eq $true:

if (test-path $csv) {}

Similarly with the elseif:

elseif ((test-path $csv) -eq $false) {}

vs.

elseif (!(test-path $csv)) {}

or:

elseif (-not (test-path $csv)) {}

But actually, you don't need elseif at all here. You're testing for the existence of this file twice. You already checked for it in the if so, just else would do:

if (test-path $csv) {
    break
} else {
    Write-Host "Location $csv does not exist.  Please try again..."
}

By the way, it's good that you're checking user input and figuring out if the file exists. But the user could just press enter (on purpose or by accident) with an empty string. If that happens, Test-Path will throw an exception, so you need to check for this case too:

if ($csv -and (Test-Path $csv)) { break }

It's also a bit strange that you're looping while a variable named $continue is $false but breaking once it's $true (seems backwards). But more than that, you could just use the break keyword instead:

while ($true) {
    $csv = read-host "CSV Filepath (no quotes!)"
    if (test-path $csv) {
        break
    }
}

But going further, you don't need to use an infinite loop and then check a conditional to figure out when to break. It seems that way because you're using a while loop which checks the conditional at the beginning, but you need to execute the loop body at least once before checking the conditional.

That's where do {} while() or do {} until() comes in. Given that, your entire loop can be reduced to:

do {
    $csv = read-host "CSV Filepath (no quotes!)"
} until ($c -and (Test-Path $c))

This is missing the message to the user about the CSV not existing, but frankly I think they'll get it if it keeps prompting. If you really want to do that part, then you can still shorten it:

while ($true) {
    $csv = read-host "CSV Filepath (no quotes!)"
    if ($csv -and (test-path $csv)) {
        break
    } else {
        Write-Host "Location $csv does not exist.  Please try again..."
    }
}

One last thing, if the users are constantly wrapping the file name in quotes, you might consider just stripping them off instead of trying to get them to enter it another way:

$csv = $csv.TrimStart('"').TrimEnd('"')

Or replace all the quotes:

$csv = $csv -replace '"',''

getNextGroupmembers:

There isn't too much to say here other than the big changes that would be made by refactoring everything like I described at the beginning.

But a simple step you could take toward that goal is to remove the call to Get-ADPrincipalGroupMembership from the menu, and make this function do the lookups from the beginning. In other words, you give it the user or group you want the memberships for, not the first set of groups. It's already a recursive function; it can figure out how to get the initial memberships.

Important note about $maxLevelInt: you're reading it one function, then referring to it in another, without passing it along.

Frankly, I don't think that even works. I hesitated to even say this, but you could make that work by explicitly referring to it as global in both places:

$Global:maxLevelInt = read-host "# depth of levels"

and

if ( $level -eq $Global:maxLevelInt ) { break }

Please don't do this.

If you want to use this value, then make it a parameter of this function:

function getNextGroupMembers ($currentLevel, $groupIn, $maxLevel) {
        if ( $level -eq $maxLevel ) { break }
}

You just need to make sure to include it whenever you call the function (including the recursive calls to itself).

I'm assuming this check is to protect against circular nested groups. This will prevent your code from looping infinitely, but you might not get the output you need.

You might consider passing a list of all the groups checked so far so that you can skip a recursive call for those, and never get caught in the infinite loop, while still being able to enumerate the rest of the groups. If that were implemented, you could safely ignore a level limit.

The code for that is a bit outside the scope of a code review, but it's something you could work on.

outputFormat:

Fairly simple function here. I would say you could replace your if () elseif () elseif() with switch () as it seems to be a good use case for it.

Along the lines of separation, ideally this would return the formatted data which the caller can then decide whether to write it to the screen, or to a file, or multiple files, or whatever, but meh.

If you really wanted to go further with this, and you've gotten your functions refactored to a point where you can get a single object that contains all the nested membership data (as objects, not formatted), then you could start looking at using Format-Custom along with a PowerShell formatting file. This is a very advanced option that no one has ever used. Ever. But it would be pretty cool.

Required reading for this:

Format-Custom
Formatting File Overview
And basically all the sub-topics of the above link (concepts, examples, Schema XML reference, etc.).

writeToFile:

This function accepts a line, and then writes to a pre-determined file. You're again using a global variable here (don't do this please), and I don't know how it's working (in my tests I can't get it to work).

You should pass the file name into it and reference it that way.

But going further, I'm not sure why you need this function at all. Why not just use Out-File directly?

checkFilePath:

There's no need to assign the result of Test-Path to a variable just to return it from the function. You could just return Test-Path $path or omit return:

Test-Path $path

But then of course I have to ask (rhetorically), why would you use this function at all?

And then I see that in fact you aren't using it at all. So I recommend deleting it!

Parameterizing the script itself

You can make the script itself take parameters the way a function would. At the very top, put a param() block:

param($UserOrCsv)

Why do this? Because you could give the user the option of skipping the interactive menu altogether and just running the process. Then the script could be called on a schedule, or by some other automated process.

Of course the above param block is rather annoying, because you would need to determine whether the user intended to pass a user name or a CSV file.

A better way is to use advanced function semantics so that you use advanced parameter sets. So at the top you could do something like this:

[CmdletBinding(DefaultParameterSetName='ByUser')]
param(
    [Parameter(
        ParameterSetName='ByCSV',
        Mandatory=$true
    )]
    [String]
    $CSV ,

    [Parameter(
        ParameterSetName='ByUser',
        Mandatory=$true
    )]
    [String[]]
    $User
)

Why do this? Because now they can call:

.\MyScript.ps1 -CSV C:\whatever\stuff.csv
.\MyScript.ps1 -User ThisGuy
.\MyScript.ps1 -User ThisGuy,ThatOne,SomeUser

You can do a lot more than that with advanced function syntax, like validating the existence of the CSV in the parameter declaration, accepting users via the pipeline, etc.

I won't get too much further into it because you may not even want it.


Determining Pythagorean triples based on the hypotenuse

First, let's write this with a little style, and go from there:

import math

def is_triple(hypotenuse):
    """return (a, b, c) if Pythagrean Triple, else None"""
    if hypotenuse < 4:
        return None

    c = hypotenuse ** 2

    for a in xrange(3, hypotenuse):
        b = math.sqrt(c - (a ** 2))
        if b == int(b):
            return a, int(b), hypotenuse

    return None

Now, I'll walk you through it, line by line, and show you how I got this.

I have no idea if this is more efficient, but it is written in better style, which is an important thing to consider.

import math

Always put your imports at the top of the module.

def is_triple(hypotenuse):

Here is say 'let's define some functionality, and encase a repeatable, reusable pattern of logic within it. The rest of my answer revolves around this, and is a major first step to programming in Python.

def is_triple(hypotenuse):
    """return (a, b, c) if Pythagrean Triple, else None"""

Note the """ triple quotes. That's your docstring, something that reminds you later what you were thinking when you wrote something. Try to keep it under 65 characters or so.

if hypotenuse < 4:
    return None

In the first line, def is_triple(hypotenuse):, I ask the user to give me something; a variable that I can use later. If I later call this function in the manner is_triple(5), I am basically telling the function that my hypotenuse is 5, and for the rest of the time here, we'll call it hypotenuse.

c = hypotenuse ** 2

That's really all you need for this calculation right now.

for a in xrange(3, hypotenuse):
        b = math.sqrt(c - (a ** 2))
        if b == int(b):
            return a, int(b), hypotenuse

for a in xrange(3, hypotenuse) basically says for each whole number between 3 and the hypotenuse, do the stuff I'm about to write.

Following the previous example,

>>> range(3, hypotenuse) #hypotenuse is == 5
[3, 4]

Nevermind that I call xrange(), it functions the same as far as we're concerned here, and importantly, is more efficient.

So now that we've made a loop, a will act as though it is each number in [3, 4], so first, it's 3:

b = math.sqrt(c -  (a ** 2))
b = math.sqrt(25 - (3 ** 2))
b = math.sqrt(25 - (9))
b = math.sqrt(16)
b = 4.0

Just like you would on pencil and paper. Notice I put a .0 after, the four. That's important here:

if b == int(b):

Basically, int puts the number b from a decimal to a whole number. We just check if they're the same.

>>> int(4.0)
4
>>> int(4.0) == 4
True

So, if the number we got for b is the same as the whole number representation of b, do the next part:

return a, int(b), hypotenuse

Which maps a value back to whatever you called as an assignment for the function call.

>>> values = is_triple(5)
>>> values
(3, 4, 5)
>>> wrong = is_triple(7)
>>> wrong
>>> #it didn't print anything, because it gave me back None

Finally, at the bottom:

return None

That's the last thing to catch, in case nothing else happens. Obviously, if you've gone through this loop and you haven't gotten an answer? Well, looks like you don't have a match. Give back a None to denote this.

To see this work in action, try this:

>>> import pprint
>>> pprint.pprint([{x: is_triple(x)} for x in xrange(101)])


Python script that alerts me when specific file gets created

The variable file_does_not_exist is simply used as loop control, but we don't need it:

while not os.path.isfile(file_to_check):
    pass

However, this loop is very inefficient.  It's what we call a busy loop; that is, it never pauses, but continually polls for its condition.  This is harmful, as it monopolises a processor and wastes energy.  Sensible operating systems will de-prioritise busy tasks like this (to reduce its impact on other processes), which will reduce the UI responsiveness when you exit the loop, until the scheduler catches up with the change in the program's behaviour.

Instead, we should use operating system features (preferably abstracted in a platform-independent Python library) to wait for a change, allowing your process to sleep until it's notified.  I don't know of a platform-independent library, but there are some possibilities for Linux (inotify) and Windows (watchdog) at least.  Using one of these will yield processor time to other processes and make your program into a "good citizen" on a shared system.


Bugs

You may think this code works, but it probably doesn't.

Example 1:

beforeSend: function () {
    return (checkAll());
    return (passwordCheck());
},

The passwordCheck function will never be called. Most probably you wanted this:

return checkAll() && passwordCheck();

Example 2:

for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
    if (arr[i].trim() == '') {
        alert('Please Enter All Fields');
        return false;
    } else {
        return true;
    }
}

This for statement doesn't loop: it returns after checking the first value in arr, it won't check the others. Most probably you wanted this:

for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
    if (arr[i].trim() == '') {
        alert('Please Enter All Fields');
        return false;
    }
}
return true;

Also, a sligthly simpler way to check for blank value:

if (!arr[i].trim()) {

Efficiency

In passwordCheck you lookup $('#password') and $('#password') twice. It would be better to lookup only once and cache in a local variable, for example:

function passwordCheck() {
    var $password = $('#password');
    var $password_check = $('#password-check');
    var pass1 = $password.val();
    var pass2 = $password_check.val();
    if (pass1 != pass2) {
        $password.addClass('highlight');
        $password_check.addClass('highlight');
        alert("Passwords don't match");
        return false;
    } else {
        $password.removeClass('highlight');
        $password_check.removeClass('highlight');
        return true;
    }
}


Not sure about the usage of nameOfTree , nameOfParent and same for the value. But one thing to simplify your mapping and provide a representation for your enum is:

public String toString(){
    return  this.name() + "=" + this.value()
}

// and mapping cna be written as.
String mapping = UserEnum.TreeUser.toString() +  "," + UserEnum.ParentUser.toString();
String mapping = UserEnum.TreeUser +  "," + UserEnum.ParentUser; // toString() is called implictly.


I asked about this in the Rust beginner's IRC channel and someone helpfully pointed out that another approach might be to use trait objects and Box.

By way of illustration:

use std::fmt::Display;

pub trait Item: Display {}

impl Item for String {}
impl Item for bool {}
impl Item for char {}
impl Item for f64 {}
impl Item for u64 {}

pub struct PersistentList<T = Box<Item>> {
    first: Option<T>,
    rest: Option<Box<PersistentList<T>>>,
    count: usize,
}

impl<T> PersistentList<T> {
    pub fn new() -> PersistentList<T> {
        PersistentList {
            first: None,
            rest: None,
            count: 0,
        }
    }

    pub fn first(&self) -> Option<&T> {
        self.first.as_ref()
    }

    pub fn next(self) -> Option<Box<PersistentList<T>>> {
        self.rest
    }

    pub fn cons(self, item: T) -> PersistentList<T> {
        let count = &self.count + 1;
        PersistentList {
            first: Some(item),
            rest: Some(Box::new(self)),
            count,
        }
    }

    pub fn count(&self) -> usize {
        self.count
    }
}

The advantage here is that we can simply implement Item for any given type and our collection will be capable of handling it. Here's a Playground link.

Now I think it's only fair to leave this question open for a while: I'm new to Rust and still learning and I'm unsure of the best practices and idioms--that said, this seems to be a pretty decent approach.


Caesar cipher using ASCII character codes

Good things

String building: the new string is built step by step using a list, this is more efficient than concatenating char by char.

To improve

Bug: caesar('a',500) returns Ȼ. You likely want to use the operator % to stay in the range a-z.
PEP 8: variable names should be lowercase, with words separated by underscores. More info.


jQuery animation procedural approach, suggestions need

Looks good, though I prefer to keep the $(document).ready() as clean as possible, by only making calls and not definitions. Makes DOM management a bit easier.