Your solution has a main problem: you treat a list almost like an array, by using list-ref to get the n-th element of the list, to rebuild the list by consing all the elements from the last to the first.

This is a problem for two reasons:

it makes your procedure of order of complexity n², instead of n, as we can obtain with other algorithms, since the list-ref has a cost of the order of n, the length of the list, and you call it a number of times which is equal to n;
if you use lists instead of arrays, you should try to use as much as possible the primitive operators on them, like car, cdr, cons, that can be considered as more “natural” for this kind of data structure, having a constant cost, and resort to operators like len and list-ref only when strictly necessary (otherwise you can use directly arrays, also availables in lisp languages).

So the question is: how can we implement an efficient list reverse operator by using the primitive operators on lists?

A solution can be found if we generalize a little bit the reverse function, and instead of defining a function that reverses a list, we define a function that takes two lists as parameters, and build a new list by reversing the elements of the first one consing them on the second. This can be done in this way:

(define reverse1
  (lambda (first-list second-list)
    (if (null? first-list)
        second-list
        (reverse1 (cdr first-list) (cons (car first-list) second-list)))))

The efficiency is given by the fact that we are using only the operators cons, car and cdr, and we scan only the first list, and only once, by adding each element to the second list.

And to obtain the reverse function, we need simply to call the previous function with a second list as the empty list, as this will produce as result the reverse of the first list:

(define reverse
  (lambda (ls)
    (reverse1 ls '())))

Actually, this technique is more commonly note as resorting to an accumulator to produce a result, and a solution like the above is more usually written in a single function in Racket:

(define reverse
  (lambda (ls [accumulator '()])
    (if (null? ls)
        accumulator
        (reverse (cdr ls) (cons (car ls) accumulator)))))

Here we use the possibility of defining a default value for a parameter, so that the first time we call the function with the list to be reversed, and the second parameter is automatically assigned the empty list, while in the recursive call it is passed explicitly by building the (partial) result.

A final important note: the recursion in this function is called “tail recursion”, since the last operation of the function is just a call to the function itself, and the result of this call is the result of the function. In Scheme, and Racket, as well as in other similar languages with good compilers, this kind of recursion is compiled as iteration, making the function more efficient in terms of space used.


You've got a spelling mistake; it's "Alphabetize".

Private Sub AlphebetizeSheets(ByVal myBook As Workbook)
    Dim i As Long
    Dim j As Long

    For i = 1 To myBook.Worksheets.Count
        For j = i To myBook.Worksheets.Count
            If UCase(myBook.Sheets(j).Name) < UCase(myBook.Sheets(i).Name) Then
                  myBook.Sheets(j).Move before:=Sheets(i)
             End If
        Next
    Next
    Application.ScreenUpdating = True
    Application.GetSaveAsFilename
End Sub

I thought this is the sort of thing that has been made before...

https://msdn.microsoft.com/en-us/library/office/ff195025.aspx

And it has. But they do it the same way, with two small differences:

They don't compare the sheets with themselves via starting the second for loop at i+1
They don't check the last sheet by stopping i at myBook.Worksheets.Count - 1

Which I guess saves a few comparisons. You've got a weird sorting algorithm here too, a version of selection and insertion sort... which seems to have some flaws, in my opinion.

  8 3 2 6 4 5 1 7
  checks 8, 3, moves 3
  3 8 2 6 4 5 1 7
  checks 2, moves 2
  2 3 8 6 4 5 1 7
  checks 6, 4, 5, 1 moves 1
  1 2 3 8 6 4 5 7
  checks 7, next iteration
  compares 2 to 3, 8, 6, 4, 5, 7, next iteration
  compares 3 to 8, 6, 4, 5, 7, next iteration
  compares 8 to 6, moves 6
  1 2 3 6 8 4 5 7
  compares 6 to 8, 4 moves 4
  1 2 3 4 6 8 5 7
  compares 4 to 5, 7, next iteration
  compares 6 to 8, 5 moves 5
  1 2 3 4 5 6 8 7
  compares 5 to 7, next iteration
  compares 6 to 8, 7, next iteration
  compares 8 to 7, moves 7
  1 2 3 4 5 6 7 8, next iteration and end.

The problem with this sort is that it compares items[i] with items[i+1] even although on the previous iteration, multiple shifts happened. Take a look at the start:

  8 3 2 6 4 5 1 7
  checks 8, 3, moves 3
  3 8 2 6 4 5 1 7
  checks 2, moves 2
  2 3 8 6 4 5 1 7
  checks 6, 4, 5, 1 moves 1
  1 2 3 8 6 4 5 7
  checks 7, next iteration

After that, it should know that 2 > 1, 3 > 2, and 8 > 3 so it should skip those.

So instead of

  compares 2 to 3, 8, 6, 4, 5, 7, next iteration

it should be

  compares 2 to 6, 4, 5, 7, next iteration.

and

  compares 3 to 6, 4, 5, 7, next iteration.

You could do this by incrementing another variable for every move operation, and decrementing this variable after the j-for loop (with a minimum of 0). Start j at i + this other variable. Like that, it would, after the 3 moves in the first iteration, start the second iteration off at index 4 (i = 2, move counter = 3 - 1 iteration passed = 2).

Alternatively, accept that sorting sheets is likely to be fast already, and don't spend time on this beyond adding the two simple improvements. Maybe store UCase(myBook.Sheets(j).Name) and UCase(myBook.Sheets(i).Name) in temporary variables.


Finding the sub-array with maximum sum - my slow approach

You code :

private static int[] buildRandom(int size, int min, int max) {
    return new Random().ints(size, min, max).toArray();
}

I think that doing new Random several times, will reduce the "randomness" of the output. You can read that Stack Overflow question for more information. The idea is to remove the new Random() and use the same instance to produce several output. I would suggest to have an instance of Random in your class FindMaximumSubArraySumProblem but then does it make sense to have it ? Not really. So this method look kind of odd in your class. You could move it in his own helper class where it would make more sense, and then extract an instance of Random to increase randomness.


A synchronized method will block execution of other methods in the class, you better use a seperate thread to store the logsentries to write.

This could be a simple write-only-thread.

.error and .critical are the same, this is violating DRY.


There hasn't been any standard for how to define getters and setters in Javascript until recently, so the implementations have various custom syntaxes, and not much seems to work in Internet Explorer... The defineGetter method is marked as non-standard and deprecated.

The thing that works reliably right now is to not use setters and getters at all, but methods that are named to indicate what they do (just as how it's done in Java).

(Of course, if you only need it to work in a specific browser, you can use whatever syntax works there. There are some syntax examples in the test code that I linked to above.)

To use prototypal interface, you put the methods in the prototype rather than in the object instance:

function GameObject(sprite) {
    this.xVelocity = 0;
    this.yVelocity = 0;
    this.x = 0;
    this.y = 0;
    this.sprite = sprite;
}

GameObject.prototype = {

    get_width: function() {
        return sprite.width;
    },
    get_height: function() {
        return sprite.height;
    },
    get_rect: function() {
        return {
            left   :this.x,
            top    :this.y,
            right  :this.x + this.width,
            bottom :this.y + this.height
        };
    }

};


Simple Rock, Paper, Scissors Python Game

You ask the player to enter 1, 2 or 3 for Rock, Paper or Scissors.  When you tell the player what the AI choose, you say it was a 1, 2 or a 3.  It would be friendlier if you said what they choose.  You could do this with a dictionary that translates the abbreviated choice into the actual item.

choices = { '1': 'Rock', '2': 'Paper', '3': 'Scissors' }

def round_winner(choice):
    ai_chosen = ...
    print(f'AI chose {choice[ai_chosen]}')
    ...

Also, you could use that dictionary to print out the menu for the player, instead of hard-coding it:

    print('Please choose one of the following:')
    for choice, item in choices:
        print(f'{choice}: {item}')

You are using “ai”, “player”, and “tie” as keys for your counter dictionary, and always printing out winner.upper() when you print out a winner.  You could just use “AI”, “PLAYER” and “TIE” as the dictionary keys, avoiding the need for the .upper() calls.

score_checker is an odd name.  Perhaps one of the hardest things about programming is coming up with good names.  check_for_game_winner might be better.

Using global is almost always bad.  You just need to pass a true/false value back to the caller to indicate if the game is over.   Use a return statement.  Ie, inside if value == 2:, add a return True statement.

initializer is another terrible name.  play_round would be better.

Checking for the overall winner inside play_round is confusing responsibilities.  The play_round function doesn’t know it is being called in a loop, if at all.  It should be removed from here.

global counter is again a bad idea.  You could simply pass the counter in as an argument.

Instead of having the game code run directly, you should add a play_games function, and move the counter initialization code and loop inside that.  With other changes, above, it might look like:

def play_games():
    counter = { 'PLAYER': 0, 'AI':0, 'TIE': 0}
    while True:
        play_round(counter)
        if check_for_game_winner(counter):
            break

The file should only execute code if the file is the main program.  If the file is imported into another file, you wouldn’t want the code to automatically run.  The following guard is usually used for this:

if __name__ == '__main__':
    play_game()

Your model of storing the player’s & AI’s moves as strings is perhaps not the best.  If you used integers, you could perform the rock beats scissors beats paper beats rock test with modulo arithmetic:

if ai_choice % 3  == (choice + 1) % 3:
    # the AI won


Find string in sorted array with interspersed empty strings

Bugs

To demonstrate some corner cases,
I will assume we have this convenient wrapper method (which I recommend to add anyway):

public static int findString(String[] array, String target) {
    return findString(array, target, 0, array.length - 1);
}

Given the input {"", "", "a"}, "0",
this code will result in ArrayIndexOutOfBoundsException:

  while (array[left].equals("") && left >= low) left--;

Because array[left] will be accessed after left becomes -1.
A quick remedy is to flip the operands of &&:

  while (left >= low && array[left].equals("")) left--;

But then, this line will fail too for the same reason:

  if (array[left].compareTo(target) >= 0) return findString(array, target, low, left);

To prevent that, you would need to add the left >= low condition here too,
before accessing array[left]:

  if (left >= low && array[left].compareTo(target) >= 0) return findString(array, target, low, left);

Follow the same argument and fix for right too.

But actually this is still not enough.
In the above example input,
high will reach 0, low stays at 0,
and an infinite recursion occurs until a StackOverflowError.
so early in the function you need to add a condition on high == 0 too:

// ...

if (array[middle].equals(target)) return middle;
if (high == 0) return -1;

// ...

Unnecessary elements

This condition is unnecessary:

if (high < low) return -1;

The rest of the implementation automatically handles this case.

The last part of the function can be simplified:

else{
  if (array[middle].compareTo(target) >= 0) return findString(array, target, low, middle);
  else if (array[middle].compareTo(target) <= 0) return findString(array, target, middle, high);
  else  return -1;
}

This way is exactly the same, but simpler:

if (array[middle].compareTo(target) >= 0) return findString(array, target, low, middle);
return findString(array, target, middle, high);

Notice also that the >= 0 condition can be just > 0

Unit testing

To verify that your implementation works in the different cases,
especially the corner cases, it's good to have some unit tests, for example:

@Test
public void test_0x() {
    assertEquals(-1, findString(new String[]{"", "", "a"}, "0"));
}

@Test
public void test_0() {
    assertEquals(-1, findString(new String[]{"", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "a"));
}

@Test
public void test_z() {
    assertEquals(-1, findString(new String[]{"", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "z"));
}

@Test
public void test_a() {
    assertEquals(-1, findString(new String[]{"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "a"));
}

@Test
public void test_ball() {
    assertEquals(4, findString(new String[]{"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "ball"));
}

@Test
public void test_at() {
    assertEquals(0, findString(new String[]{"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "at"));
}

@Test
public void test_car() {
    assertEquals(7, findString(new String[]{"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "car"));
}

@Test
public void test_dad() {
    assertEquals(10, findString(new String[]{"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "dad"));
}

@Test
public void test_core() {
    assertEquals(-1, findString(new String[]{"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}, "core"));
}

Coding style

It's recommended to use braces with even single-statement if, for and while statements too. So instead of:

if (array[middle].equals(target)) return middle;
if (high == 0) return -1;

This is better:

if (array[middle].equals(target)) {
    return middle;
}
if (high == 0) {
    return -1;
}

It's recommended to declare and initialize variables close to where they are actually used. So instead of:

int left = middle;
int right = middle;

while (left >= low && array[left].equals("")) left--;
while (right <= high && array[right].equals("")) right++;

if (left >= low && array[left].compareTo(target) >= 0) return findString(array, target, low, left);
else if (right <= high && array[right].compareTo(target) <= 0) return findString(array, target, right, high);
return -1;

This is better:

int left = middle;
while (left >= low && array[left].equals("")) left--;
if (left >= low && array[left].compareTo(target) >= 0) return findString(array, target, low, left);

int right = middle;
while (right <= high && array[right].equals("")) right++;
if (right <= high && array[right].compareTo(target) <= 0) return findString(array, target, right, high);
return -1;

And this is equivalent, but more efficient:

int left = middle;
while (left >= low && array[left].equals("")) left--;
if (left < low) return -1;
if (array[left].compareTo(target) >= 0) return findString(array, target, low, left);

int right = middle;
while (right <= high && array[right].equals("")) right++;
if (right > high) return -1;
if (array[right].compareTo(target) <= 0) return findString(array, target, right, high);

Instead of .equals(""), it's better to use .isEmpty().


Alignment
unsigned int *dst = destination; fails when destination is not aligned for unsigned.  Same for src. (OP seems be somewhat aware of this given "unaligned address not handled")
Aliasing
Possible strict aliasing violation.  See What is the strict aliasing rule?
Fails when buffers overlap
Without restrict, buffer may overlap and code does not well handle overlaps in both directions.
Recommend to use restrict like memcpy().
void *memcpy(void * restrict s1, const void * restrict s2, size_t n);

CPU WORD size
"I know int will always be CPU WORD size" discounts 8-bits CPUs (common in embedded code).  On those, an int is at least 16-bit, not 8-bit.
The low-level copy size is typically related to the CPU word size, but much of this is implementation dependent.
Usually unsigned is good or best, but one would need to profile the implementation to know for sure.
Minor: Unneeded code
Test of left not unneeded as later while(left--) does the job.
// if (left)

NULL Testing
Common to not test for null-ness.  memcpy() is not require to do so, nor is it required to not test NULL.  What should be done depends on overall coding goals, so it is up to you.


You might prefer to use namedtuple for the attributes, and the property decorator for mean. Note that mean is now computed every time it's accessed - maybe you don't want this, or maybe it makes sense since max and min are mutable.

from collections import namedtuple

class Uniform(namedtuple('Uniform', ('min', 'max'))):

    def logp(self, x):
        return 1/(self.max - self.min) * between(x, self.min, self.max)

    @property
    def mean(self):
        return 0.5*(self.min + self.max)


Finding all delivery orders with multiple purchase orders

The subquery calculates a distinct count using two step, of course this can be simplified to:

SELECT *
FROM GR_data
WHERE doNo IN
 (
   SELECT doNo
   FROM GR_data
   WHERE DATALENGTH(Mat_No)<=0
   GROUP BY doNo
   HAVING COUNT(DISTINCT po_number)>1
 )
ORDER BY doNo, po_number

Depending on your actual data it might be more efficient to apply a Windowed Aggregate Function:

COUNT(DISTINCT po_number) OVER (PARTITION BY doNo)

Unfortunately using DISTINCT in Analytical Functions is not supported  by SQL Server.

But assuming that there are no NULLs in po_number COUNT DISTINCT OVER can be emulated using different ways, probably most efficient by applying two DENSE_RANKS:

SELECT *  -- if you don't want to show "dense_cnt" you  must list all other columns besides
FROM
 (
   SELECT *,
      DENSE_RANK() OVER (PARTITION BY doNo ORDER BY po_number)
     +DENSE_RANK() OVER (PARTITION BY doNo ORDER BY po_number DESC) - 1 AS dense_count
   FROM GR_data
   WHERE DATALENGTH(Mat_No)<=0
 ) AS dt
WHERE dense_count > 1
ORDER BY doNo, po_number

Check actual resource usage if those rewrites are more efficient.


Comparing phone numbers across CSVs Python

Here's my 5 cents as non-python guy
Naming:
As soon as you begin numbering variable names, there should be alarm bells ringing... multiple loud alarm bells.
rename your out, out2, and the corresponding writers. Instead use descriptive names (maybe similar to your "filenames"): first_list, second_list, and so on. The same applies for your writers.
Also seen2 is not a good name.. What do you store in that variable? Name it after that: second_seen is definitely better, than seen2


Project Euler problem 86 taking a long time

Given: 1 ≤ a ≤ b ≤ c = M,

then, min(a*b, b*c, a*c) == a*b

This means, you can remove 2 multiplications and the min operation from shortest-cuboid-dist-has-int-length? as long as you pass your room’s length, width, and height in the proper order.


The main issue I see is inconsistent style. Sometimes you put spaces around certain operators, sometimes you don't. You want your code to be consistently formatted.

Generally, it's best to always put a space before and after an operator, especially the assignment operator. It's even more strange to put a space before an operator, but not after (or vice versa).

This line, for example:

age= float(raw_input("How old are you %s?   >   " %name))

would look much better like this:

age = float(raw_input("How old are you %s?   >   " % name))

You also switch between putting a space after commas in lists, and not doing so. I would change these lines:

male=["male","m"]

female=["female", "f"]

to look like this (notice the space after the first comma):

male = ["male", "m"]

female = ["female", "f"]

Variables should always begin with a lowercase letter. Classes and constants can and should be capitalized, but not normal variables. So the Gender variable should be renamed to gender.

You should consider not asking for the user's gender and age unless you actually do something with that data, or at least don't assign it to variables because it'll go unused.

I would also rename bmi_q, bmi_c, and consent_q to something more clear, so other people reading your code can immediately know what those function are supposed to do. bmi_c could definitely be renamed to something like calculate_bmi, or even calc_bmi.

And lastly, I'd always make sure your indention doesn't get messed up when pasting your code into a site like this. There's a few problems with invalid indention, but I'd imaging that happened when you put it in this question. (the indention in the question has been fixed now though)

But overall, good job on writing your first program! Congrats, keep it up, and remember this quote from Phil Karlton:

  There are only two hard things in Computer Science: cache invalidation and naming things.


Sanitize the user input, but first and foremost: make sure there actually is any user input to sanitize:

$foo = $_POST['bar'];

might issue a notice, if that post variable doesn't exist, that's why it's considered good practice to use isset:

if (!isset($_POST['email']))
    exit('No email address provided');//don't use exit, redirect or something
$email = $_POST['email'];

Next, you sanitize and validate the input. For email addresses, that's easily done:

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    exit('Invalid email address given');//again, use redirect here

But all the other stuff has to be processed to avoid something you are wide open to:

Mail injection attacks

I've reviewed a couple of code snippets, in detail. Instead of copy-pasting my existing answers here, or typing them a second, third or fourth time, I'll just list a couple of links to some of these answers:

Critique sanitized user email PHP Script (Has most on mail injection, check the links in that answer, too)
Security of a "contact us" form Focusses more on email address validation
How can I make this code safer against XSS attacks? more general on XSS attacks, but make sure to check the links at the bottom.

Side-notes:
If a script contains nothing but PHP code, then the closing ?> tag is best omitted. This advice is given everywhere, including the official php.net site. Google as to why (whitespacing, parser tokens, ...)

I have the feeling you're not showing us the full code, because you have an opening and closing {} around everything, except the first statement.
If this code is the actual code, then please remove those redundant brackets: PHP isn't block-scoped, so they serve no purpouse, other than to confuse anyone else who might ever gaze at your code.


PowerShell - fast remove a directory with 10,000+ files

May be try this:
#solution 1 - Remove content of dir
remove-item "C:\temp\tmp2\*" -Recurse -Force

#Solution 2 - Remove dir and recreate dir
remove-item "C:\temp\tmp2\" -Recurse -Force
New-Item "C:\temp\tmp2\" -ItemType Directory

#Solution 3 - Loop into dir and remove all with intercept error
Get-ChildItem "C:\temp\tmp2\" -Recurse | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue


Your code looks very nice indeed, I only have some minor observations you code use to improve this code:

Naming
Use the imperative form of the verb (convert instead of converts)

Implementation Hiding
Use defp for methods which are not intended for external use. You might consider also renaming them to start with underscore _ to further differentiate them as internal.

Multiple assignment in method signature
To make you code more succinct, you can use multiple assignment - meaning that instead of:

def converts(number, roman_value, [[decimal, roman] | numerals]) when number >= decimal do
  converts(number - decimal, roman_value ++ roman, [[decimal, roman] | numerals])
end

you can write:

def converts(number, roman_value, [[decimal, roman] | _] = numerals)
  when number >= decimal do
  converts(number - decimal, roman_value ++ roman, numerals)
end

to the same effect. This form assigns the first item in the list to [decimal, roman], as well as assigning the whole list (including the first element) to numerals, so you don't have to re-build it inside the method body.

Implementing the above suggestions, your code will look like this:

defmodule RomanNumeral do

  @decimal_roman_numerals [[5, 'V'], [4, 'IV'], [1, 'I']]

  def convert(number) do
    _convert(number, [], @decimal_roman_numerals)
  end

  defp _convert(number, roman_value, _) when number < 1 do
    roman_value
  end

  defp _convert(number, roman_value, [[decimal, roman] | _] = numerals)
    when number >= decimal do
    _convert(number - decimal, roman_value ++ roman, numerals)
  end

  defp _convert(number, roman_value, [_ | numerals]) do
    _convert(number, roman_value, numerals)
  end
end


Organizing page functions and page state using the Module pattern

You have multiple anonymous functions when you could do one and on the last line return your ui.* object.

var ui = (function($) {
    // local ui ref
    var ui = {};

    // other namespaces .. etc
    ui.tabs = {};

    return ui;
})(jQuery));


Comparing version numbers contained in a text string

a_int = a_arr.map(function (value) {
    val = parseInt(value, 10)
    return val ? val : 0
})

b_int = b_arr.map(function (value) {
    val = parseInt(value, 10)
    return val ? val : 0
})

This part can be extracted into its own function.

// insure that there are enough decimal points
a += ".0.0.0"
b += ".0.0.0"

Instead of appending an arbitrary number of segments, try using array.map against an array of 3 zeroes instead. Then either copy the segment from a_int/b_int if present or retain the zero.

status = "equal"
i = 0

do {
    if (a_int[i] < b_int[i])
        status = "less"
    else if (a_int[i] > b_int[i])
        status = "greater"
    i++
}
while (status == "equal" && i < 3)

This whole operation can be done with a reduce. Carry an "equal" string as initial value. Then loop through the 3 items in the array, comparing each, and updating the carried value to "greater" or "less".

version(a,b){

We don't really know from this alone which one is the reference, and which one is being compared. If the function returned "greater", is a greater than b or is b greater than a. Name the function and the variables properly.

Lastly, you forgot to define variables with either a var, let or const. The problem with not doing so, particularly with browser JS, is that declaring variables without them will shoot the variables to the global scope, defining them there instead of within this function. That means your variable is open for clobbering or is clobbering other variables of the same name.

This is how I would have carried this one out:

// Used as filler value and for us to loop 3 times when using array methods.
const filler = [0, 0, 0];

// Splits, normalizes into 3 numbers, zeroes invalid values
function versionToArray(version){
  const versionArray = version.split('.');
  return filler.map((fill, index) => {
    const segment = parseInt(versionArray[index], 10);
    return Number.isNaN(segment) ? fill : segment;
  });
}

function compareVersion(subject, reference){
  const ref = versionToArray(reference);
  const sub = versionToArray(subject);

  // Static values into constants
  const EQUAL = 'equal';
  const GREATER = 'greater';
  const LESS = 'less';

  return filler.reduce((status, segment, index) => {
    // One nice thing about ternaries is that they can be written this way.
    // Acts like a switch statements that cascade, while looking like a
    // key-value pair of condition-value.
    return status !== EQUAL ? status  // A greater segment already decided
                : sub > ref ? GREATER
                : sub < ref ? LESS
                            : EQUAL;  // If not less or greater, well...
  }, EQUAL); // Assume equal unless proven otherwise
}

console.log(compareVersion('1', '2'));
console.log(compareVersion('1.2', '2'));
console.log(compareVersion('2.2', '2'));
console.log(compareVersion('2.2.2', '2'));
console.log(compareVersion('2.0.0', '2'));
console.log(compareVersion('4.0.0', '2'));
console.log(compareVersion('1.1.1.1', '2'));


Implemnting a Trie Data structures problem from HackerRank using Python3

You could run autopep8 for minor style corrections (e.g. whitespaces).
Naming variables correctly is always extremely important, especially in a dynamic language, without indications about object type:

Your trie is a Trie, not just a tree.
n sounds like an integer. It could be called lines.
i also sounds like an integer. It could be line or word.

Using for/else syntax, you can refactor your main method without any flag.

if __name__ == "__main__":
    trie = Trie()
    _header, *lines = stdin.readlines()
    for line in lines:
        word = line.strip()
        if trie.add(word):
            print("BAD SET")
            print(word)
            break
    else:
        print("GOOD SET")

If you wish, you could replace the 3 last lines of add by return fail or current.counter >= 2


Check if each element of my list param contains all data string passed as a parameter

Thanks for sharing your code.

Naming

Finding good names is the most important but also hardest part in programming. So always take your time to find good names that express your intention of what the code does.

The name of your method excludeAllInformationVariation is a lie. It implies that there is something changed either in the object itself (its state) or the passed parameter object. But this method does not alters neither the objects stat nor the parameter.
Therefore it should have a different name.
Since it returns a boolean this name should start with is or has.
eg.: isAllDataCovered(...)

Single Responsibility / Separation of Concerns

Your  classes Part and Logic look like  data transfer objects (DTOs), but the method isLabelNullOrEmpty() is some kind of business logic.

You should not mix DTOs with business logic. The method isLabelNullOrEmpty() should be in the same class as the method  excludeAllInformationVariation and have a parameter of type String on which it should work.


Here are some tips that may help. Note that these are collected from feedback on #racket on irc.freenode.net (which you may find helpful too).

The length of the bytestring is counted inside the loop, but it's a loop invariant that you can hoist out of the loop.
Folding over j may be faster than mutating it as you are doing. See Mutation and Performance in the Guide for more details.
Your for loops use generic sequences. Using specialized sequences like in-range would be faster.

You might also benefit from trying the Optimization Coach plugin for DrRacket. It's a tool that identifies performance pitfalls in your program along with possible solutions. For Typed Racket, it can also find when the type-driven optimizer was not able to optimize the program but could potentially do so with some changes.

Also try the Racket mailing list: http://www.racket-lang.org/community.html


You are holding on to some IDisposable resources that you shouldn't be, which will impact scalability, GC pressure and likely performance. Here's the augmented Listener class:

internal sealed class Listener : IDisposable
{
    private readonly int port;

    private readonly TcpListener tcpListener;

    private readonly IList<Client> clients = new List<Client>();

    public Listener(int port)
    {
        this.port = port;
        this.tcpListener = new TcpListener(IPAddress.Any, this.port);
        this.tcpListener.Start();
        Task.Factory.StartNew(this.ListenLoop);
    }

    public int Port
    {
        get
        {
            return this.port;
        }
    }

    public void Dispose()
    {
        foreach (var client in this.clients)
        {
            client.Dispose();
        }
    }

    private async void ListenLoop()
    {
        while (true)
        {
            var socket = await this.tcpListener.AcceptSocketAsync();

            if (socket == null)
            {
                break;
            }

            var client = new Client(socket, this.ClientDisconnected);

            this.clients.Add(client);
            await Task.Factory.StartNew(client.Do);
        }
    }

    private void ClientDisconnected(Client client)
    {
        if (client == null)
        {
            return;
        }

        client.Dispose();
        this.clients.Remove(client);
    }
}

Here's the augmented Client class:

internal delegate void ClientDisconnectedDelegate(Client client);

internal sealed class Client : IDisposable
{
    private readonly Socket socket;

    private readonly ClientDisconnectedDelegate doDisconnect;

    private readonly Stream networkStream;

    private readonly Stream memoryStream = new MemoryStream();

    private readonly TextReader streamReader;

    public Client(Socket socket, ClientDisconnectedDelegate doDisconnect)
    {
        this.socket = socket;
        this.doDisconnect = doDisconnect;
        Task.Factory.StartNew(this.CheckForConnection);
        this.networkStream = new NetworkStream(this.socket, true);
        this.streamReader = new StreamReader(this.memoryStream);
    }

    public void Dispose()
    {
        this.streamReader.Dispose();
        this.networkStream.Dispose();
        this.socket.Dispose();
        this.memoryStream.Dispose();
    }

    public async void Do()
    {
        var buffer = new byte[4096];
        var bytesRead = await this.networkStream.ReadAsync(buffer, 0, buffer.Length);

        Console.WriteLine("Doing some awesome work that takes 5 seconds.");
        Thread.Sleep(5000);
        Console.WriteLine("Finished doing work.");

        await this.networkStream.WriteAsync(buffer, 0, bytesRead);
        await this.networkStream.FlushAsync();
    }

    private void CheckForConnection()
    {
        while (true)
        {
            bool isDisconnected;

            try
            {
                isDisconnected = this.socket.Poll(1, SelectMode.SelectRead) && (this.socket.Available == 0);
            }
            catch (SocketException)
            {
                isDisconnected = true;
            }

            if (isDisconnected && (this.doDisconnect != null))
            {
                this.doDisconnect(this);
                return;
            }

            Thread.Sleep(100);
        }
    }
}

And here's the augmented Client program:

internal static class Program
{
    private static void Main()
    {
        Thread.Sleep(5000);

        Console.WriteLine("Connecting...");

        using (var client = new TcpClient("localhost", 6666))
        {
            Console.WriteLine("Connected.");

            using (var stream = client.GetStream())
            {
                var messageToSend = new byte[3];

                messageToSend[0] = 1;
                messageToSend[1] = 3;

                var messageReceived = new byte[3];

                stream.WriteAsync(messageToSend, 0, 3);

                stream.Flush();

                stream.Read(messageReceived, 0, 3);

                // Echo
                Console.WriteLine(messageReceived[0] + messageReceived[1]);
                Console.ReadLine();
            }
        }
    }
}


Escaping photo caption to avoid cross site script attack

Instead of a one size fits all approach, you can filter things based on what they are.

URLs and url parameters can be encoded with urlencode()
Output inside of html tags can be filtered with strip_tags()
Other more general output that you are using with HTML attributes such as 'alt' are less predictable, and can be filtered with htmlentities()


This FxCop warning is basically asking you to make sure ("Review") that that non-constant you are passing (directory) to the security permission does not change while the permission is in effect.  Basically, FxCop isn't sure if it is possible for the code (or some rogue module that a hacker has put in place) to do something like the following:

Set directory to "c:\Temp\"
.Demand()
<untrusted>Set directory to "c:\Windows\System32\"</untrusted>
Write something into a file contained in directory.

In this particular case, since directory is a non-ref parameter, it is not possible for another module outside your call-descendants to modify it.  Thus, what you need to check for:

Anything in this method assigning a value to directory
Anything in this method that passes directory by reference (ref/out/unsafe pointers)

Disclaimer: I am not a code security expert and have no formal training as such.  I may have missed entire classes of things to look for here. If you are dealing with code that has real-world security implications, I highly suggest you hire a consultant who does, rather than take what I wrote above as gospel.


Some mostly stylistic improvements you could apply:

There is no need to cast the return value of malloc(), unless you plan on compiling this code as C++. In C, void* converts implicitly to any other pointer type. So the cast is just boilerplate in this case.
Prefer using sizeof(variable) instead of sizeof(Type). Example:

Node *head = malloc(sizeof(*head));

This makes maintenance easier, since now if you introduce a new Node type, you only have to change one place, with no chance of updating one side of the expression and forgetting the other. Note that in this example, the dereference of head is valid because sizeof is a compile-time operation, so there is no actual pointer access taking place here, just type inference.
Consider giving more robust names to your functions. find(), insert(), etc, are very common names, which can apply to many things, not just lists. In C, you cannot overload function names, so in any major project, these names would be very likely to cause collisions with other global identifiers. Name prefixes are a common approach in C to solve this problem. Consider prefixing the function names with list_ or any other prefix you might prefer. I.e.:

void list_insert(Node *current, int data);
void list_delete(Node *current, int data);

Instead of returning an integer 0|1 to represent a boolean value, you can use the bool type, declared in the <stdbool.h> header, which is more idiomatic.
delete() function is a void function, so it doesn't need an explicit return statement at the end.
Looks like you are using printf() to log errors:

if(current->next == NULL) {
    printf("\nElement %d is not present in the list\n", data);
    return;
}

For error output, it is more correct to use fprintf and write to the stderr standard stream.
The list printing function print() could be made more flexible by receiving the output stream as a parameter. So you don't limit the caller to always printing to stdout, it can also be used to dump the list to a file (notice the use of fprintf()).

void print(Node *current, FILE *stream) {
    while(current != NULL) {
        fprintf(stream, "%d ", current->data);
        current = current->next;
    }
}

When you want to allocate and immediately zero-initialize data, such as in here:

Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
head->prev = NULL;

The standard function calloc() can be used to make code more concise:

Node *head = calloc(1, sizeof(*head));


Does this intersection algorithm work like it's supposed to?

Since there's no answer yet, I'll take a crack at it.

My first impression is that the nesting is somewhat deep and some of the variables could be moved closer to its site of usage. Here's one possible refactor:

float BoundingSphere::Intersects(Ray ray)
{
    D3DXVECTOR3 cToO = ray.Origin() - centre;
    float rSquared = radius * radius;
    if(D3DXVec3Dot(&cToO, &cToO) <= rSquared) return 0;

    D3DXVECTOR3 direction = ray.Direction();
    if(D3DXVec3Dot(&cToO, &direction) > 0) return -1;

    D3DXVECTOR3 vec = cToO - direction * D3DXVec3Dot(&cToO, &direction);
    float vSquared = D3DXVec3Dot(&vec, &vec);
    if(vSquared > rSquared) return -1;
    // ...
}

There should be someway to multiple a D3DXVECTOR3 with a scalar value at once. Even if that's not directly supported it's trivial to overload the operator *= yourself. The return is also getting rather long. I broken that long statement into more digestible pieces:

    float mul = sqrt(rSquared - vSquared);
    D3DXVECTOR3 normDir = *D3DXVec3Normalize(&direction, &direction);
    normDir *= mul;

    return D3DXVec3Length(&(ray.Origin() - centre - vec + normDir));
}

I haven't looked at the collision in too much detail, it seems ok from a glance.

  it should return -1 if there is no collision, 0 if the origin of the ray is inside the sphere...

It sounds like you have a clear idea of how this method is suppose to behave. Why not grab a unit testing framework, like google test, and write a unit test for each of those cases? Testing BoundingSphere::Intersects can be as simple as this:

TEST(BoundingSphereTest, testRayInsideSphere)
{
    BoundingSphere testSphere(D3DXVECTOR3(0, 0, 0), 42);
    Ray testRay(0, 0);

    EXPECT_EQ(-1, testSphere.Intersects(testRay));
}

Note, I'm just guessing on how those objects are constructed but this should give you the main idea. Fix them up as appropriate.


Determine Collatz sequence length for given starting values

You need functions.
The first one you can make is the collatz_conjecture.
First off I'd say make it recursive.
If you ignore the currCycleLength you should get:

def collatz_conjecture(curr_num):
    if curr_num == 1:
        return 1
    if curr_num % 2 == 0:
        curr_num = curr_num / 2
    else:
        curr_num = 3 * curr_num + 1
    collatz_conjecture(curr_num)

The best way to make this better is to use functools.lru_cache(None).
This is a wrapper, but it'll give you speed for just adding one line! (This is what Zack was talking about)
You also should add the depth too, this is just adding one onto the previous depth. The if's are actually pretty ugly, so you can change it to the turnery operator.

@functools.lru_cache(None)
def collatz_conjecture(curr_num):
    if curr_num == 1:
        return 1
    return collatz_conjecture(3 * curr_num + 1 if curr_num % 2 else curr_num / 2) + 1

Finally I don't like that if n == 1. I'd reimplement lru_cache and supply it with that at the beggining.

def memoize(cache=None):
    if cache is None:
        cache = {}
    def wrapper(fn):
        def inner(*args):
            try:
                return cache[args]
            except KeyError:
                r = fn(*args)
                cache[args] = r
                return r
        return inner
    return wrapper

@memoize({(1,): 1})
def collatz_conjecture(n):
    return collatz_conjecture(3 * n + 1 if n % 2 else n / 2) + 1

As for the rest of your code, I'd use input with map, I'd use a comprehension passed to max and I'd also add if __name__ == '__main__':

This should get you something like:

def main():
    while True:
        user_input = input()
        if not user_input:
            break
        start, end = map(int, user_input.split()[:2])
        print(start, end, max(collatz_conjecture(i) for i in range(start, end + 1)))

if __name__ == '__main__':
    main()


Search for a multiword string in a list of strings

Just use the continue keyword to force the advancement to evaluate the next string.
Code after the if statement will only execute if the previous statement was false.

import re
strings = ["abc zzz", "y", "#comment"]
for s in strings:
    match = re.search("(\S+) (\S+)", s)
    if match:
        print "Multiword: %s+%s" % (match.group(1), match.group(2))
        continue
    match = re.match("y$", s)
    if match:
        print "Positive"
        continue
    match = re.match("n$", s)
    if match:
        print "Negative"
        continue

    # a few more matches possible in real life script,
    # and then the last catch-all:
    print "No match found, line skipped"


Technical mistakes

echo void

echo $tpl->render($_GET['tpl']);

This echo will display empty string (null), because you've already output a string with echo within method and have void return type (implicit return null). Make render() method return a string, because you want to defer output as much as you can. You won't be able to do anything with it after that (including headers management). Eventually you might want to use psr-7 response object with stream and plug yourself into some framework - class with method that returns string can be left untouched (Open-closed Principle) and wrapped with an object that changes string into stream.

closing tag

?>

Simply don't use it at the end of file. It causes hard to debug problems with undesired output - more here.

Algorithm

Render method works on hardcoded strings, which rarely is a good idea. You can make it more generic, as the logical pattern is quite distinct. Append path & file extension to given name and get file contents if it exists. The only thing you need to be careful about is path traversal attack - if you allow only lowercase letters it won't be possible. Also some error handling will be required.

OOP

Api

First of all your class api is perfect. Giving only template name, without implying that file system is involved makes it encapsulated abstraction and that's what OOP is about - don't be fooled by magic tricks and utilities. It is really a hard part, that often goes into area of so called "unknown unknowns" if you get it wrong, and it is really easy to do so.

Naming

You can write a book about that, so I'll point a few things:

Avoid naming your classes with names ending with -or or -er. It fits interfaces pretty well - they're focused on delivering something specific (from client's perspective) in unspecified way.
On the other hand avoid mentioning IO gateway names in data focused interfaces. It fits class names - they're interface implementations delivering something by talking to concrete IO mechanism.
Your TemplateLoader is concrete kind of loader, but you should be able to switch it with implementation that delivers strings from database or memory (when testing the class that uses it). You won't see the point when global namespace is the client using it, but when additional layers wrap it up it won't require messing with code beside the place where object composition happens.
render() method usually implies that some data processing is involved - you are simply returning template contents.

Refactored

Since this class is small (as it should) I've written refactored version based on the things I've pointed out and type hints for php 7:

interface TemplateLoader
{
    /**
     * @param string $templateName
     *
     * @throws InvalidArgumentException|TemplateNotFoundException
     *
     * @return string
     */
    public function contents(string $templateName): string;
}

class TemplateFiles implements TemplateLoader
{
    private $templatesDirectory;

    public function __construct(string $templatesDirectory = '') {
        $this->templatesDirectory = $templatesDirectory;
    }

    public function contents(string $templateName): string
    {
        $filename = $this->templateFilename($templateName);
        return file_get_contents($this->existingFile($filename));
    }

    private function templateFilename(string $templateName): string
    {
        $file = $this->validName($templateName) . '.php';
        return rtrim($this->templatesDirectory, '/') . '/' . $file;
    }

    private function validName(string $template): string
    {
        if (preg_match('/[^a-z]/', $template)) {
            throw new InvalidArgumentException('...');
        }

        return $template;
    }

    private function existingFile(string $filename): string
    {
        if (!file_exists($filename)) {
            throw new TemplateNotFoundException('...');
        }

        return $filename;
    }
}

You would have to implement two exceptions and put method call into try-catch block. There are two of them, because one may come from potentially malicious request (you might want to log these), while the other may be dev error or bypassed UI by user (it's not control flow exception which should be avoided).


Check if a string has all unique characters

People are very eager to present their own solutions, so let me attempt an actual review of your code:

Your names could be clearer. Strings is not very descriptive, and neither are alphabetS/L. SIZE doesn't tell anyone what kind of size it is or what it relates to.
Anything not nested under private or public in a class is automatically private. So you might as well move those stray members into the private section to make things clearer.
If you're using C++11 or higher then you can use constexpr.
Why are you returning a value from your toLower function after you pass in a mutable reference? Might as well drop the return and use the reference.
Your toLower function does a lot of work. Assuming you don't want to use the STL for this you can still roll your own function. If you only want to check characters from A-z then you can simply get the lowercase by adding the difference to any number representation smaller than 97 (a). Look at the ASCII chart for reference.
You can simply initialize count with int count[SIZE]{};. Alternatively you could use memset.
Try to avoid performing more than one task in a function. E.g. factor out the toLower functionality of isAllUnique. It could then be const as it has no need to mutate class state.
For the actual algorithm I prefer Incomputable's approach over the one suggested by Ben Steffan which can be used without overly relying on the STL.
Prefer prefix over postfix for the increment operator.
Don't compare to true. Instead simply do if (a_bool_var), or if (!a_bool_var) for the negation.
This could probably be done with just free functions without needing a class object.


Inheritance or DI in Presenter classes in MVP

I would prefer the first one with constructor parameters primarily because of two reasons.

First, it's easier to test, you are able to pass mocked or dummy services directly to the constructor.

  Good design is testable, and design that isn't testable is bad.

(Source Michael C. Feathers: Working Effectively with Legacy Code)

The second reason is that it seems to me that the second snippet abuses inheritance. I don't see any reason why anyone would declare their variables with BasePresenter type (so it's useless) and using a base class only for sharing two lines of code also smells.

The third reasons is that the second version is harder to read, readers have to go back and forth to the parent class if they find an usage of dataService or permissionService and want to figure out what it is.


If possible, always whitelist acceptable sources instead of trying to blacklist harmful ones. Also, don't use try-catch for control flow, use it for what it's designed for: error handling.

All that being said, you aren't passing the promise out of the model, because you wait for the response with .then, so no you wouldn't have to make the controller methods promises as well, but why wouldn't you? JS is single-threaded, so always default to asynchronous operations to be non-blocking.


Success page + data entry for a store page

First and most important thing is to indent your code. Indenting provides an instant visual structure which makes it easy to read. More often than not, bugs and quirks can be easily avoided simply by good code indentation. PHP is especially susceptible to this because its code is mixed directly with the HTML output. There is actually an issue in your posted code where should there be an error, your code will still try to display the order details at the bottom.

Next thing you want to consider is creating your code in blocks. On a high level this is basic MVC code structure where the logic and the output are separated. You want to apply this as often as possible to make your code easier to read and maintain.

Make sure to close your database connection after opening it. I typically declare my database object outside the included class file in order to make it clearer what the variable is. This also helps your IDE out for providing popup advice, and code completion. If you're not using an IDE yet, try NetBeans or CodeLobster for PHP development.

Here's my take on your code. I obviously couldn't test it without your database details but it should give you some ideas.

<?php
class OrderDetails{
    private $Number;
    private $Amount;
    private $db;

    public function OrderDetails(){
        require 'databaseaccess.php';
        $this->db = $DBH;       //should probably declare $DBH outside the included file to make code easier to read, and to help the ide

        $this->ProcessOrder();

        //close database connection here
    }

    public function getNumber(){
        return $this->Number;
    }

    public function getAmount(){
        return $this->Amount;
    }

    private function ProcessOrder(){
        $total = 0;
        $soba_size = $_POST['soba_size'];
        switch($soba_size){
            case "small":
                $total = $total + 4;
                break;
            case "reg":
                $total = $total + 6;
                break;
            case "large":
                $total = $total + 8;
                break;
            default:break;      //always have a default even if you're confident it won't be needed
        }
        $soba_type = $_POST['soba_type'];
        $dbtoppings = '';
        if ($_POST['topping']){
            foreach($_POST['topping'] as $topping){
                switch($topping){
                    case "duck":
                        $total = $total + 1;
                        $dbtoppings = $dbtoppings.",".$topping;
                        break;
                    case "egg":
                        $total = $total + 2;
                        $dbtoppings = $dbtoppings.",".$topping;
                        break;
                    case "chicken":
                        $total = $total + 3;
                        $dbtoppings = $dbtoppings.",".$topping;
                        break;
                    case "teriyaki chicken":
                        $total = $total + 4;
                        $dbtoppings = $dbtoppings.",".$topping;
                        break;
                    default:break;      //always have a default even if you're confident it won't be needed
                }
            }
        }
        if($_POST['requests']){
            $request = $_POST['requests'];
        }
        else{
            $request = '';
        }

        //begin data entry
        $data1 = array('total' => $total);
        $STH = $this->db->prepare("INSERT INTO orderlist(total) values (:total)");
        $STH->execute($data1);
        $lastId = $this->db->lastInsertId();
        //dataentry2
        $data2 = array('orderid' => $lastId, 'soba_size' => $soba_size, 'soba_type' => $soba_type, 'topping' => $dbtoppings,'request' => $request);
        $STH = $this->db->prepare("INSERT INTO orderdetails(orderID,soba_size,soba_type,topping,request) values (:orderid,:soba_size,:soba_type,:topping,:request)");
        $STH->execute($data2);

        //set the class variables for grabbing by your other code
        $this->Amount = $total;
        $this->Number = $lastId;
    }
}
?><!DOCTYPE>

    <meta charset="utf-8">
    <title>Untitled Document</title>

    <?php
    //check order present
    if(!($_POST))
    {
        ?>
        error, order was not received!

        return to  order page
        <?php
    }
    else{
        $orderObj = new OrderDetails();
        ?>

                Thank you for ordering. Your order has been printed.

                Order Number: <?php echo $orderObj->getNumber();?>

                Amount: $ <?php echo $orderObj->getAmount();?>

                Please show this page at the cashier to confirm your order. Thank you!

        <?php
    }
    ?>


Implementing an inner product using pyspark

Since zipped RDD contains only two-element tuples using using reduce doesn't makes sense. You can safely replace

lambda x: reduce(op.mul, x)

with

lambda x: x[0] * x[1]

or standalone function:

def mul(xy):
    x, y = xy
    return x * y

Final reduce can be replaced with a simple sum. Putting these two pieces together:

def inner(xs, ys):
    return xs.zip(ys).map(lambda xy: xy[0] * xy[1]).sum()

The only part that remains is zip function. It requires both that both RDDs have the same number of partitions and elements per partition. While the first part is pretty easy to achieve keeping a correct order and balancing number of elements can be tricky. You can try to generalize your function using joins:

def inner(xs, ys):
    def swap(xi):
        x, i = xi
        return i, x

    # We use sortBy key to avoid shuffling during join
    xs_i = xs.zipWithIndex().map(swap).sortByKey()
    ys_i = ys.zipWithIndex().map(swap).sortByKey()

    return xs_i.join(ys_i, ).values().map(lambda xy: xy[0] * xy[1]).sum()

It will be less efficient than your current solution but more robust.


External variable in callback for chunk()

You managed to bypass the query builder, which could have implemented this as a trivial, single query on the backing database, and instead managed to emulate that query in an very inefficient manner yourself.

// get all leads
Lead::chunk(100, function($leads) use ($results, $param) {
    // search in name
    $results = array_merge($results, $this->repository->searchInName($leads, $param));

    // search in email
    $results = array_merge($results, $this->repository->searchInEmail($leads, $param));

    // and so on ...
}

This effectively causes 2 additional queries to the database for each 100 results in the Lead model. This might still work reasonably in your test environment where you have at most a few dozen leads registered, but will crawl to a halt in production as the number of leads increases with time.

Even worse, it requires you to stream all existing Lead instances through PHP, even if they are not even part of the final result set.


You can use the Tag property to store the card.  Its normal to store the context object in the Tag.

that way you can make the text whatever you like eg..

creditCardSubMenuItem.Text = string.Format("The card {0}", card);
creditCardSubMenuItem.Tag= card;


Finding a loop in a directed graph in Python

Lets first review your code, and then introduce you to one alternative on how to do unit tests in Python.

Adding comments or docstrings is good – In dfs(), not the best named function by the way, you use colors to mark something, but you don't explain what the different colors mean. I had to guess that:

white means unvisited vertex
grey means visited vertex
black means disconnected vertex

I should have to guess that, and it should be written in a docstring related to the function. This applies for all similar coded segments where it is not intuitive what the variable, function or variable values means.
Add blank lines to enhance readability – The common guidelines says two blank lines between functions, but I would like to extend that to have a blank line around most if, for and while blocks, and the occasional block of code.

You've done this to some extent, but there are two places I really would like to do this and that after the while and for loop where you do an immmediate return statement, which now seems connected to the inner loop code.
Avoid loose code at top level – In general only imports, constants, functions and classes are to be at the top level of your file. This makes it, amongst others, easy to use your file as a module, and it helps organise your code. In your code all of your tests are at the top level, and should have been within some test scope. I'll come back to this below.

In general you could/should put all this code within one or more functions, like main(), and call it from the following top level code at the end of your file:

if __name__ == '__main__':
    main()

Another nice options, when entering the world of unit tests, is to execute the unit tests when you execute the python file directly, and then otherwise use the exposed functions, i.e. cycle_exists() and dfs().
Remove the visited list in dfs() – It seems like you've forgotten to remove the visited list in dfs(), as it isn't currently used for anything besides being initialised and added to. You don't do any checks against it.
Similarily, remove black from the palette – In your current implementation you don't use the color black for anything, and as such it can be removed, which also would allow for a simpler dict, as the only thing you seem to be interested in is whether it has been visited or not. This can be achieved using a boolean.
Add more error handling – Your code doesn't do much error handling or validation of input, which some like and some don't like. I think I would have added at least a test that the graph exists at some level.
No need for the inner parentheses in dfs() when adding to stack – At least in my tests you can remove the inner set of parentheses, and no change happens.

Refactored code

Here is my refactored code, renaming dfs() to detect_cycle() and adding some comments and docstrings:

def detect_cycle(graph, start):
    """Traverse the graph, and see if we come back to a earlier visited vertex."""

    if graph is None:
        raise ValueError("We need a graph to detect cycles in")

    # Set all vertexes to None, as we don't know the status of it
    visited = {v : False for v in graph}

    stack = [start]

    # Traverse from start, adding connected nodes to the stack as we go
    while stack:
        vertex = stack.pop()

        # If we hit a vertex we've seen before, it is a cycle
        if visited[vertex]:
            return True

        # Mark this vertex as visited
        visited[vertex] = True

        # Add connected nodes to stack, if any
        stack.extend(graph[vertex])

    # If stack is empty, that means no cycle for this start vertex
    return False

def cycle_exists(graph):
    """Return whether the graph has cycles or not."""

    # Loop through each vertex, and check if it has cycles or not
    for vertex in graph:
         if detect_cycle(graph, vertex):
             return True

    return False

One thing I haven't addressed if whether this is the most effective way to check for cycles. In fact I know it isn't as for each vertex we traverse the graph over and over again.

This implies that the current algorithm has an \$O(n^2)\$ complexity, which most likely could be simplified utilising another list of visited vertexes, and instead of looping through all vertexes, one could visit only those not already visited. This is left as an exercise for the reader... :-)

Unit tests

Multiple options exists for doing unit tests in Python, and it comes down to personal preferences. Here I'll present you for the internal version, namely unittest, which suffices for this code.

A common pattern for a unit test is the following:

Arrange – Set up all needed variables, you need to execute the test
Act – Execute the actual test
Assert – Assert that the test result are as expected

In your case the tests are rather simple, so I've done some according to this scheme, and for some I've taken a few shortcuts. But even though the tests are simple, do remember to let one test method only test one thing. It is considered an anti-pattern to have multiple actions or asserts in one method.

Using unittest, I find that using a class name like test__function_to_test is a nice pattern, although not entirely according to guidelines. This should inherit from unittest.TestCase enabling us to easily run the tests using unittest.main(), which will run all tests functions starting with test_.

So here are your tests, and some more. The following code is added beneath the other code (with exception of import at top):

import unittest           # This line on the very top

class test__cycle_exits(unittest.TestCase):
    """ Helper class to test the cycle_exists function

    This class test the main method cycle_exists, which heavily
    depends on the detect_cycle method, to find whether cycles exists
    in the connected graphs.
    """

    def test_connected_graph_with_cycle(self):

        self.assertTrue(cycle_exists({
            0 : [1, 2],
            1 : [],
            2 : [3],
            3 : [4],
            4 : [2]
        }))

    def test_disconnected_graph_with_cycle(self):

        self.assertTrue(cycle_exists({
            0 : [],
            1 : [2],
            2 : [],
            3 : [4],
            4 : [5],
            5 : [3]
        }))

    def test_empty_graph_without_cycle(self):

        # Arrange
        graph = {
            0 : [],
            1 : [],
            2 : [],
            3 : []
        }

        # Act
        has_cycle = cycle_exists(graph)

        # Arrange
        self.assertFalse(has_cycle)

    def test_disconnected_graph_without_a_cycle(self):

        self.assertFalse(cycle_exists({
            0 : [1, 2],
            1 : [3, 4],
            2 : [],
            3 : [],
            4 : [],
            5 : [6, 7],
            6 : [],
            7 : []
        }))

    def test_confused_graph_result(self):

        # Arrange
        graph = {
            0: [1],
            1: [2],
            2: [0]
        }

        # Act
        has_cycle = cycle_exists(graph)

        # Arrange
        self.assertFalse(has_cycle, "Didn't expect cycles for this one! Or did I?") # Dead wrong!!!

class test__detect_cycle(unittest.TestCase):
    """Helper class to test the detect_cycle function.

    Using some simple graphs, test the various parts of this functions
    """

    def test_single_connected_graph(self):
        self.assertTrue(detect_cycle({ 0: [0]}, 0))

    def test_simple_connected_graph(self):
        self.assertTrue(detect_cycle({ 0: [1], 1 : [0]}, 0))

    def test_single_disconnected_graph(self):
        self.assertFalse(detect_cycle({ 0: []}, 0))

    def test_simple_disconnected_graph(self):
        self.assertFalse(detect_cycle({ 0: [1], 1 : []}, 0))

    def test_graph_multiple_connections(self):
        self.assertTrue(detect_cycle({
            0: [1, 2, 3],
            1: [],
            2: [],
            3: [0]
        }, 0))

    def test_multipaths(self):
        self.assertTrue(detect_cycle({
            0: [1, 2, 3],
            1: [2, 3],
            2: [3],
            3: [0]}, 0))

    def test_nonexistent_start(self):

        # Arrange
        graph = { 0: [1], 1: [0] }

        # Act and Assert an exception
        with self.assertRaises(KeyError):
            detect_cycle(graph, 2)

    def test_nonexistent_graph(self):
        # Arrange
        graph = None

        # Act and Assert an exception
        with self.assertRaises(ValueError):
            detect_cycle(graph, 0)

if __name__ == '__main__':
    unittest.main()

Notice how I tried to give meaningful names to each of the test methods so that it should be understandable what failed if/when they fail. If everything is OK the output would have been:

.............
----------------------------------------------------------------------
Ran 13 tests in 0.005s

OK

However I've deliberately added a fault, with an message, so the output if you run this code is:

F............
======================================================================
FAIL: test_confused_graph_result (__main__.test__cycle_exists)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<filename>", line 118, in test_confused_graph_result
    self.assertFalse(has_cycle, "Didn't expect cycles for this one! Or did I?") # Dead wrong!!!
AssertionError: Didn't expect cycles for this one! Or did I?

----------------------------------------------------------------------
Ran 13 tests in 0.005s

FAILED (failures=1)

Notice how the 'dots' have changed to include an F, and that the FAIL: line names that is was the test_confused_graph_result() in the test__cycle_exists class which has failed, and you get some details as to what failed.

If the test is well written you should now easily see why it failed, and hopefully understand what went wrong.


Please check if these two methods for inheritance and initialization are good or bad

I'm the author of Why Prototypal Inheritance Matters. It's good that you're taking an interest in prototypal inheritance. So let's review your code. I'll start with your use case and then discuss the implementation.
The Use Case
var Person = Class.extend({
    say: function () {
        console.log("Hello");
    },
    walk: function () {
        console.log("walk");
    }
});

var person = Person.create({
    name:'lee'
});

console.log(Person);
console.log(person);

This code looks good. It's very similar to what I wrote in my aforementioned article. I would like to point out one thing though: you don't need two separate methods extend and create. Object creation and extension may be combined into a single function. Hence you could do:
var Person = Class.extend({
    say: function () {
        console.log("Hello");
    },
    walk: function () {
        console.log("walk");
    }
});

var person = Person.extend({
    name: "lee"
});

console.log(Person);
console.log(person);

The Implementation
Since you only require one method for prototypal inheritance I'll primarily focus on your extend function. First, your Class.extend method is needlessly complicated. I would rewrite it as:
function Class() {}

var extend = Class.prototype.extend = function () {
    //...
};

Class.extend = function () {
    return extend.apply(new Class, arguments);
};

As you can see you don't need to call Array.prototype.slice on arguments. It may be directly passed to apply. In addition try keeping things in variables as much as possible. Avoid expressions like this.prototype.extend. Also be explicit: write new Class instead of new this().

Your Class.prototype.extend function is not only confusing but also wrongly implemented. It doesn't extend the given object this. Instead it extends ProtoClas.prototype which is actually just Object.create. I would implement Class as follows:
function Factory() {}

var CLASS = {
    extend: function () {
        Factory.prototype = this;
        var instance = new Factory;
        var length = arguments.length;
        var index = 0;

        while (index < length) {
            var prototype = arguments[index++];

            for (var property in prototype)
                if (instance[property] !== prototype[property])
                    Object.defineProperty(instance, property,
                        Object.getOwnPropertyDescriptor(prototype, property));
        }

        return instance;
    }
};

You may now use CLASS.extend as follows:
var PERSON = CLASS.extend({
    say: function () {
        console.log("Hello");
    },
    walk: function () {
        console.log("walk");
    }
});

var person = PERSON.extend({
    name: "lee"
});

console.log(PERSON);
console.log(person);

Note that instead of doing var instance = Object.create(this) I used a function called Factory instead. The reason for doing this is performance: Object.create creates a new constructor every time. Here I'm simply reusing a single Factory constructor.
In addition for each argument supplied to extend I copy all the properties of the argument to the instance only if it doesn't already exist. This check speeds up the process because every object inherits from Object.prototype and copying is a very expensive operation.
Also instead of copying the properties using instance[property] = prototype[property] I'm using Object.defineProperty and Object.getOwnPropertyDescriptor. The allows you to copy properties as is allowing you to use getters/setters, etc.
The Alternative
On a concluding note I would like to mention that true prototypal inheritance is slow in JavaScript because JavaScript favors the constructor pattern of prototypal inheritance instead. Hence if you wish to write fast code then I suggest you read the following article which describes prototype-class isomorphism: https://stackoverflow.com/a/17893663/783743


Searching repositories for files with forbidden strings

In general, it is a good code. However, I have a few remarks. Note: I am assuming that the code works perfectly as it should and will comment only on the style. Also, I assume that you are an experienced programmer and hence will not be explaining the basics, although if something is not clear please let me know.

Configuration

You might want to keep the real paths separate to a configuration script. I'd advice you to create a *.cfg file that would store all the configuration data. I can imagine this being used on different machines with different paths each. I don't think you would like to allow users to modify the code, it is better to give them config file.

In case you would like to keep the configuration as it is, I'd encourage to move the lists to config.py and name (as you mentioned) in UPPER_CASE. Additionally, you might also want to encapsulate them in a functions like this:

def get_ignored_dirs():
    return ignored_dirs

This allows to keep the API of config.py constant regardless on what you decide to do with inners of the configuration.

Lastly, you might consider moving your functions like ignore_dir to separate file (e.g. files_utils.py) and treat is as a proxy to your configuration.

Method naming

In general I tend do explicitly say that some function returns boolean value by sticking is at the beginning. For example, it is clear (from the code) that your function ignore_dir checks if the directory should be ignored. This is however, not clear from the name, one might think that this function ignores some directory. I'd suggest to change the name to is_ignored_dir or something similar. The same goes for ignore_file.

Separation of concerns and responsibilities

It seems for me that your sanitize function is not very SRP-like. Inside, you do many things including deciding whether to ignore a directory (or file), read the file and count time. I'd suggest dividing those responsibilities to more than one function. You might notice that if you try to do a unit test for this function, in reality it will be a e2e test.

Below, an example of what you can fix it.

def measured(func):
    def wrapper(path):
        start = time.perf_counter()
        func(path)
        end = time.perf_counter()
        elapsed = round(end - start,2)
        print(f"elapsed: {elapsed} sec")
    return wrapper

def searchable_files_from_list(filenames):
    for filename in filenames:
        if not is_ignore_file(filename):
            yield filename

def searchable_files_containing_forbidden_text(filenames):
    for filename in searchable_files_from_list(filenames):
        full_name = os.path.join(dirpath, filename)
        if contains_forbidden_text(full_name):
            yield full_name

def contains_forbidden_text(filename):
    with open(full_name, 'r', encoding="utf8", errors="ignore") as searchable:
    text = searchable.read()
    if config.re_forbidden.search(text):
        return True
    return False

def files_to_sanitize(path):
    for (dirpath,dirname,filenames) in os.walk(path):
        if is_ignored_dir(dirpath):
            continue
        for file in searchable_files_containing_forbidden_text(filenames):
            yield file

@measured
def print_files_to_sanitize(path):
    for file in files_to_sanitize(path):
        pprint(file)

Explanation:

Now, all of your methods can be separately unit tested and validated. Let's take look at each function at a time, starting with the last one.

print_files_to_sanitize
This is what is left from your sanitize function. After the refactoring it become apparent that the function does not sanitize anything, it just prints a file name. This fact wasn't so clear before because of many things happening.

I've added a decorator to the function - this is a very common practice for measuring time of the method (you might want to generalize this by using *args and **kw).

files_to_sanitize is a generator that should give you all of the files that should be sanitized. It iterates through your catalogs ignoring some directories and getting the files from a second generator.

searchable_files_containing_forbidden_text Given a list of files it iterates over those which have a good file name (given by searchable_files_from_list function) and if such file contains a forbidden text it bubbles it up.


First, I have to say that you are using good variable names.

Turn Option Strict On

This setting is important, it'll help you see errors and needed conversion.

You'll notice that this isn't possible

Dim LaLs = LinearAngleTextBox.Text * LinearStrengthTextBox.Text

But instead you need to convert it to integer.

Dim LaLs = Int32.Parse(LinearAngleTextBox.Text) * Int32.Parse(LinearStrengthTextBox.Text)

Don't repeat yourself

You'll then notice that some conversions are done often.

Int32.Parse(LinearStrengthTextBox.Text)

Put these in proper variable right at the begining.

Dim linearStrength As Integer = Int32.Parse(LinearStrengthTextBox.Text)

There are formula like the below that are done in the inner loop, which can be moved outside of the loop.

(x * Image.GetPixelFormatSize(bmpData.PixelFormat) / 8)


Billboards InterviewStreet - Code Optimization

Since we are on a code review forum I would suggest you to give more meaningful names to variables, avoid redundant assignments (e.g. initial array assigned to parts variable is not used), and split the logic into smaller methods that perform distinct functionality. Also you can use Max(IEnumerable<long>) extension method instead of writing your own.

But I guess that's not what you want to hear, so in terms of algorithms I suggest you to apply the A* algorithm to this problem instead of full search. If you find it difficult to understand and implement, I would recommend you to pass the Machine Learning course from Coursera or Introduction to Artificial Intelligence from Udacity


This is at least a start. I did not look very heavily in finding a better algorithm itself, just making small improvements of you algorithm. Nevertheless this resulted in a speed-up of about 30%.

For comparison (I changed the call to powers(50) so it does not take so long):

# Your code
$ python -m cProfile magic_square_orig2.py
         81524 function calls in 3.462 seconds
# With the changes below
$ python -m cProfile magic_square2.py
         18110 function calls (18107 primitive calls) in 2.496 seconds

With powers(75):

# Your code
$ python -m cProfile magic_square_orig2.py
         336810 function calls in 30.210 seconds
# With the changes below
$ python -m cProfile magic_square2.py
         148883 function calls (148880 primitive calls) in 18.832 seconds

Use better names (!!)

Even now, where you changed some variable names for better names, the function checksquare is very hard to understand because of variables called g, h, j, k. But since I will take away their meaning as integers below, anyways, we can find better names for them.

Iterate over the contents of a list

It is always easier to iterate over the list, instead of iterating an index, compare:

for i in range(len(l)):
    print l[i]
for element in l:
    print element

The latter is a lot easier to read (and understand). It is the recommended way to iterate over a list. So I changed your logic and gave the variables better names:

Use collections.Counter()

There is already an existing construct that builds a dictionary with counts of objects, it is callen collections.Counter. This way you can replace:

for e in range(len(listcheck)):
        for f in range(3):
            try:
                dictofnos[(listcheck[e])[f]] += 1
            except KeyError:
                dictofnos[(listcheck[e])[f]] = 1

with:

from collections import Counter
...
dictofnos = Counter(item for sublist in listcheck for item in sublist)

Use list comprehensions where possible

List comprehensions are in general faster than manually writing the for loop, because they are implemented in C (they are not, see e.g. here) a more succinct way to write simple loops that build a list. You can replace some loops:

for i in range(len(listcheck)):
                if len(listcheck[i]) != 3:
                    listcheck.remove(listcheck[i])

becomes one of these two:

listcheck = filter(lambda powers: len(powers) == 3, listcheck)
listcheck = [powers for powers in listcheck if len(powers) == 3]

which seem to be about the same speed. where the latter should be slightly faster, because the filter has to take a lambda instead of a predefined function. But using the fact that the only two possible lengths are 0 and 3 and bool(0) == False and bool(3) == True we can just use

listcheck = filter(len, listcheck)

in this case.

function powers

You compute for example b**2 more than once. It saves quite some time if you save b2 = b**2 (and similar for the other variables) at appropriate places.

int() already performs floor so it is not needed here. (int(3.14) == 3 and int(3.99) == 3)

You can collect what to write to the output file and write it in one go. This should be faster than repeated opening, writing and closing of the file. For this the function checksquare needs to be adapted to return the values instead of writing it:

if listcheck:
        return listin[0], dictofnos, listcheck

and in powers we add a list to collect the return values:

def powers(limit):
    out = []
    ....
        if temp >= 8:
                squares = checksquare(templist)
                if squares:
                    out.append(squares)
    ....
    return out

Additionally, we can put the writing part to a new function, separating the calculation and output part:

def write_powers(n):
    with open("output2.txt", "w") as out_file:
        for power in powers(n):
            out_file.write("\n{}\n{}\n{}\n".format(*power))

This also guarantees that the file will be overwritten with each subsequent call to the script ("w" writes, over-writing the file, while you "a+" was always appending).

Misc

Use the __name__ hook in order to allow importing you function from another script without executing powers(75) every time:

if __name__ == "__main__":
    write_powers(75)

Use an actual set for setof0s.

Result

from collections import Counter

def checksquare(listin):
    # listcheck only contains the lists of length 3.
    listcheck = listin[1:]
    # dictofnos is used to check the amount of each number in listcheck.
    dictofnos = Counter(factor for factors in listcheck for factor in factors)
    # setof0s is used to remove numbers which are not repeated.
    setof0s = set()
    # The first loop checks the amount of each number in listcheck.
    # The second loop removes any value that is not repeated.
    for factor in dictofnos:
        if dictofnos[factor] == 1:
            for factors in listcheck:
                if factor in factors:
                    for power in factors:
                        if dictofnos[power] == 0:
                            pass
                        dictofnos[power] -= 1
                    listcheck.remove(factors)
            #listcheck = filter(lambda powers: len(powers) == 3, listcheck)
            listcheck = [powers for powers in listcheck if len(powers) == 3]
    # This if/elif is used to catch any lists that passed the two loops
    # while having non-repeating numbers.
    if 0 in dictofnos.values():
        setof0s |= set(k for k in dictofnos if dictofnos[k] == 0)
    elif 1 in dictofnos.values():
        listcheck = listin[:1] + listcheck
        checksquare(listcheck)
        return
    # The final loop is deleting entries in the dict which are removed
    # (hence the use of setof0s).
    for l in setof0s:
        del dictofnos[l]
    # Outputs to output.txt.
    if listcheck:
        return listin[0], dict(dictofnos), listcheck

# powers checks if 3 squares add up to a number.
def powers(limit):
    out = []
    numberrange = 3 * ((limit + 1) ** 2)
    for a in range(numberrange):
        # Everything here is for efficiency.
        temp = 0
        templist = [[a]]
        check = 1
        b = b2 = 0
        c = int((a / 4.0) ** 0.5)
        d = int((a / 2.0) ** 0.5)
        c2, d2 = c**2, d**2

        while b <= c <= d <= limit and d2 < a:
            b += check
            b2 = b**2
            if b == c or 4*b2 > a:
                c += 1
                c2 = c**2
                b = b2 = 1
                continue
            if c == d:
                d += 1
                d2 = d**2
                c = int((a / 4.0) ** 0.5)
                c2 = c**2
                b = b2 = 1
                continue
            if (b + c + d) % 2 != a % 2:
                check = 2
                b -= 1
                b2 = 1
                continue
            if b2 + c2 + d2 == a:
                templist.append([b, c, d])
                temp += 1
        # If 8 solutions for b^2 + c^2 + d^2 = a are found
        # for any a, then it is sent to checksquare.
        if temp >= 8:
            squares = checksquare(templist)
            if squares:
                out.append(squares)
    return out

def write_powers(n):
    with open("output2.txt", "w") as out_file:
        for power in powers(n):
            print power
            out_file.write("\n{}\n{}\n{}\n".format(*power))

# The usage of these functions would be to put
# powers(whatever the upper bound of d is).
if __name__ == "__main__":
    write_powers(75)


When a function does too little...
I personally find that your mod-3 and mod-5 functions do something so very specific that you may as well at least combine them into a generic function.
I would call them something different, because what your functions are really doing is not a modulus (there's already a mod function for that), it's verifying if a number is evenly divisible by another number. I would write something like this:
(defun evenly-divisible-by (n x)
  "Given divisor n and dividend x, returns true if x ÷ n has no remainder."
  (zerop (mod x n)))

analyzer
This function's name really doesn't say much to the next person reading the code. What does it analyze? Why? What goal is it trying to achieve? I think a name like calc-fizzbuzz-for-n would honestly be much more clear about (1) the action "calc" and (2) the expected result from the action "fizzbuzz".
In this function, the indentation you applied is a bit misleading. I added some comments below to illustrate:

(defun calc-fizzbuzz (n)
  (if (evenly-divisible-by 3 n)
  ;then...
  (if (evenly-divisible-by 5 n)
      ;then...
      'fizzbuzz
      ;else...
      'fizz)
  ;else...
  (if (evenly-divisible-by 5 n)
    ;then...
    'buzz
    ;else...
      n)))

This seems minor for just a small indentation (and Lisp can make it seem more trivial since you have all those parentheses anyways), but if you wrote something like this in a more "typical" language, I would certainly expect it would be pointed out during a code review...

if (condA) {
if (condB) {
    foo.actionB();
} else {
    foo.actionA();
}
if (condC) {
    foo.ActionC();
} else {
    foo.defaultAction();
}
}

Applying above changes as well, I think this would be better:
(defun calc-fizzbuzz-for-n (n)
  "Given a number n, return whether it is evenly divisible by 3 (fizz), 5 (buzz),
  or both (fizzbuzz). Returns n when neither condition is true."
  (if (evenly-divisible-by 3 n)
      (if (evenly-divisible-by 5 n)
          'fizzbuzz
          'fizz)
      (if (evenly-divisible-by 5 n)
          'buzz
          n)))

Optional & default values
As far as I can tell, the only purpose of the fizzbuzz function is to take a limit argument, then call fizzbuzz-helper with the limit and added nil for its result argument. This can be simplified by making the result argument optional, like so:
(defun fizzbuzz (limit &optional result)

Note: I changed its name to fizzbuzz since it is no longer a "helper" to your original fizzbuzz function.
According to a related article on nullprogram.com:

If second and third arguments are not provided, b and c will be bound to nil. To provide a default argument, put that parameter inside a list. Below, when a third argument is not provided, c will be bound to "bar".
(defun foo (a &optional b (c "bar"))

So in your case, result will be nil unless it is provided a different argument. Alternatively, and as it appears to be the intention, you can force result to be nil by default using the let special operator:
(defun fizzbuzz (limit)
  (let (result) ;; defaults to nil if not specified
                ;; you can also do this if you find it more clear: (let ((result nil))
    (cond ;...

Alternative solution using lambda expression
This type of approach is often more idiomatic to Lisp/functional programming. You can use an anonymous function (a.k.a. lambda expression) as an argument to a map function. Your last line would look something like this:
(t (map 'list
        #'fizzbuzz
        (loop for i from 1 to limit by 1 collect i)))

or simpler:
(t (loop for i from 1 to limit collect (fizzbuzz i)))

More modern Lisps have a built-in range function to make things simpler, which Common Lisp doesn't; thankfully though, you can just write your own (code below from Stack Overflow answer Python's range() analog in Common Lisp):

(defun range (max &key (min 0) (step 1))
   (loop for n from min below max by step
      collect n))

And your last line can simply become:
(t (map 'integer #'(lambda (N) (fizzbuzz N)) (range limit 1)))
Thanks to @Renzo for the correction,  your last function could be written as:
(defun fizzbuzz (limit)
  (mapcar #'calc-fizzbuzz-for-n (range (1+ limit) :min 1)))

or using LOOP:
(defun fizzbuzz (limit)
  (loop for n from 1 upto limit
        collect (calc-fizzbuzz-for-n n)))


Blinking LED code at a particular frequency

Your code:

void fault_blink(int frequency){
/* starts the LED blinking at a particular frequency */

while(1)
{
 PORTCbits.RC4=0XFF;  // RC4 on
 __delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz
 PORTcbits.RC4=0X00;   // RC4 off
 __delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz
}
}

Indentation

The body of the fault_blink function should be indented, along with the body of the while loop.

The code now:

void fault_blink(int frequency){
/* starts the LED blinking at a particular frequency */

    while(1)
    {
         PORTCbits.RC4=0XFF;  // RC4 on
         __delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz
         PORTcbits.RC4=0X00;   // RC4 off
         __delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz
    }
}

Spacing

To enhance readability, there should be spaces around arithmetic operators and = signs.

The code now:

void fault_blink(int frequency) {
/* starts the LED blinking at a particular frequency */

    while(1)
    {
         PORTCbits.RC4 = 0XFF;  // RC4 on
         __delay_ms(1000 / frequency);   // time in ms dealing with frequency values in kHz
         PORTcbits.RC4 = 0X00;   // RC4 off
         __delay_ms(1000 / frequency);   // time in ms dealing with frequency values in kHz
    }
}

0X vs 0x

This isn't the biggest thing, but most people have a lower-case 'x' when defining a number as a hexadecimal number.

The code now:

void fault_blink(int frequency) {
/* starts the LED blinking at a particular frequency */

    while(1)
    {
         PORTCbits.RC4 = 0xFF;  // RC4 on
         __delay_ms(1000 / frequency);   // time in ms dealing with frequency values in kHz
         PORTcbits.RC4 = 0x00;   // RC4 off
         __delay_ms(1000 / frequency);   // time in ms dealing with frequency values in kHz
    }
}

Unnecessary comments

Don't repeat your comments; especially when the original comment is very near.

In this part of your code:

PORTCbits.RC4=0XFF;  // RC4 on
__delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz
PORTcbits.RC4=0X00;   // RC4 off
__delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz

You can remove the comment on the second __delay_ms call as the comment is identical to the call right above it.


Attempting to efficiently compute the largest prime factor

Some advice about maths and algorithms which will be useful for this problem and for future problems:

You are interested in prime factors.
You don't care about the non-biggest factors (you might go through them but there is not much point in storing them).
If a number n can be decomposed in n = m*p then at least one of m and p is smaller than sqrt(n).


Integer Overflow

I suspect that your problem has to do with integer overflow and not with your algorithm itself.  If you don't guard against integer overflow, doing A = A * 3 + 1 could result in a negative value, and you may end up in an infinite loop where you never reach 1.  Try changing your variables to long and resubmit.

By the way, to test for infinite loop cases, try the starting value 113383.

Other suggestions

You could use a HashMap instead of a TreeMap.  A HashMap has \$O(1)\$ insert and lookup compared to \$O(\log n)\$ for a TreeMap.  The difference for this program will be very small though.
In the A loop, you shouldn't have to check if visited.containsKey(A) because the collatz sequence never repeats until you reach 1.  You can just always add A to the map.
If b is 1, your program never prints anything.


You can use xrange's third param to do the stepping for you to shave off a little bit of time (not huge).

Changing:

for j in xrange(1, n / i + 1):
    divs[i * j].append(i)

To:

for j in xrange(i, n + 1, i):
    divs[j].append(i)

For n=100000, I go from 0.522774934769 to 0.47496509552.  This difference is bigger when made to numDivisorSieve, but as I understand, you're looking for speedups in divisorSieve


I agree with other commenters that you should have your memory usage measured first, so you know for sure you need to solve this. That said, I don't think MinMax requires storing all board states of the tree. Why do you need to have more boards in the memory than the level of the tree search? That should be 10-15 boards in the memory tops, no? I would even think about storing just one board in the memory and passing just the "moves" down the recursion. You will perform the move when you go down the recursion and undo the move when going up.


Python already constructs a generator when you loop over a file object with a for loop. So you could simplify your code to:

with open(sys.argv[1],'r') as f:
    for line in f:
        for token in tokenize(line):
            print(token)

Note that I renamed the file variable to f, to avoid shadowing the built-in file.

If you really need to implement a class, you should implement the iterator protocol, allowing Python to iterate over your object. First, let me define a dummy tokenize function for testing purposes:

def tokenize(line):
    return line.split()

Then, let's define the class. Note that I renamed it in PascalCase, to adhere to Python's official style-guide, PEP8.

It has two important methods, first the __iter__ method, which just returns self. This just tells Python that this class is the actual iterator which it can iterate over. It is important for if you nest iter calls, namely iter(iter(tokenizer)) == iter(tokenizer).

The second important method is the __next__ method, which, just like the name suggests, tells Python how to get the next element from the iterator. It is similar to your implementation, only I use the iterator interface of the file. This method is called a second time if we got to a new line. It will stop at the end of the file, because then the unguarded next(self.file_it) will raise StopIteration, which the for loop will catch and stop iterating.

Note that since we call iter on the output of the tokenize function, it is enough for tokenize to return an iterable (this can be a list, like  here, but it can also be an iterator itself).

class Tokenizer:
    def __init__(self, f):
        self.file_it = iter(f)
        self.token_it = None

    def __next__(self):
        if self.token_it is None:
            self.token_it = iter(tokenize(next(self.file_it)))
        try:
            return next(self.token_it)
        except StopIteration:
            self.token_it = None
            return next(self)

    def __iter__(self):
        return self

if __name__ == "__main__":
    with open(sys.argv[1],'r') as f:
        for token in Tokenizer(f):
            print(token)

I also added a if __name__ == "__main__": guard around your code running the tokenizer to allow importing this class from other scripts.

Normally I would expect the tokenize function to be a method of the Tokenizer. Either directly defined:

class Tokenizer:
    ...
    def tokenize(self, line):
        return line.split()
    ...

Or, using the strategy pattern, plugged in at creation time:

def tokenize(line):
    return line.split()

class Tokenizer:
    def __init__(self, f, tokenize):
        self.f_it = iter(f)
        self.tokenize = tokenize
        self.token_it = None
    ...

Or, using inheritance:

class Tokenizer:
    ...
    def tokenize(self, line):
        raise NotImplementedError

class SplitTokenizer(Tokenizer):
    def tokenize(self, line):
        return line.split()


Decorator pattern with a builder in a booking application

You can possibly try Domain Events. Or just Event Broker patterns?

What I usually use is something like this:

static class Event
{
   public static void Raise<T>(this T e) ...
}

interface IHandler<T>
{
   void Handle<T>(T e);
}

So I can define in my code:

class OrderCancelled
{
   public OrderCancelled(int orderId) ...
   public int OrderId { get; }
}

class MoneyReturn : IHandler<OrderCancelled> ...
class LastOfferSender : IHandler<OrderCancelled> ...
etc...

My IoC container was setup to construct and invoke a transient instances of all implementations of IHandler<T> on a T event raising.

new OrderCancelled(id).Raise();

You can chain events.