Anchor Text String Transformation in Swift

We should always be thinking about how to write our code in a generic way.  Otherwise, what happens if we want something very similar to what we've just written, but slightly different in some minor way?  Well, it usually results in a lot of copy & pasting.  Let's write some code that will allow us to apply the rules you want to apply, but in a more generic way.

I want to start with a skeleton that looks something like this:

struct StringFormatter {
    enum CaseRule {
        case None, UppercaseOnly, ConvertToUpper, LowercaseOnly, ConvertToLower
    }

    enum AsciiRule {
        case None, AsciiOnly
    }

    var blacklistCharacters = Set<Character>()
    var replacementCharacter = ""
    var caseRule = CaseRule.None
    var asciiRule = AsciiRule.None

    func stringByApplyingFormatting(toString string: String) -> String {
        // TODO: Implement actual formatting logic
        return ""
    }
}

Now we've got a reusable structure for applying this sort of formatting to our strings.  Importantly, despite there being no logic in it yet, we have implemented the method we'd be calling to apply the formatting, so we can stick with test-driven development and go ahead and write our unit test.

class StringTestStuff: XCTestCase {
    func testStringFormatting() {
        let input = "Is my résumé good enough?"
        let expectedResult = "is-my-r-sum-good-enough-"

        var stringFormatter = StringFormatter()
        stringFormatter.blacklistCharacters = Set(" -&+$,/:;=?@\"#{}|^~[]`\\*()%.!'".characters)
        stringFormatter.replacementCharacter = "-"
        stringFormatter.caseRule = .ConvertToLower
        stringFormatter.asciiRule = .AsciiOnly

        let formattedString = stringFormatter.stringByApplyingFormatting(toString: input)

        XCTAssertEqual(formattedString, expectedResult)
    }
}

We can run the test and see that's it's failing (confirming that the test works):

Of course, much like my previous answer, this test is far from complete.  All this test is doing, though, is simply testing the one known acceptance criteria you've provided.  Realistically, we'd want quite a few tests for this, and we'd want to test several of the different aspects of the StringFormatter individually (applying just the case rule, applying just the ASCII rule, etc), and several variations of different combinations.  We'd also probably want to see some performance tests for the StringFormatter too.  There are going to be multiple ways to accomplish this, and we want to make sure that when we refactor, we've not only not broken things, but we've also not made things run super slow.

But let's not kid ourselves, it would be impossible to ever test this code nearly as completely as the simply isAscii test manages.  We will simply have to pick a set of smart tests and be prepared to add tests as edge cases appear.

So with all this in mind, let's work on making this test pass.  (I know your code would pass the test, but let's see if we can do it without import Foundation).

In order to keep in line with the single responsibility principle, we need to add a couple of helper functions.

First, this function will apply our caseRule property:

private func stringWithCaseConversionApplied(string: String) -> String {
    switch caseRule {
    case .ConvertToLower: return string.lowercaseString
    case .ConvertToUpper: return string.uppercaseString
    default: return string
    }
}

And if our caseRule property is set to an "only" value rather than a "convert" value, this method will determine if any individual character would pass that check:

private func caseFilter(character: Character) -> Bool {
    if caseRule == .LowercaseOnly && String(character).uppercaseString == String(character) {
        return false
    }

    if caseRule == .UppercaseOnly && String(character).lowercaseString == String(character) {
        return false
    }

    return true
}

But we've implemented another method to apply all of the filtering rules:

private func ruleFilter(character: Character) -> Bool {
    if blacklistCharacters.contains(character) {
        return false
    }

    if asciiRule == .AsciiOnly && !character.isAscii {
        return false
    }

    return caseFilter(character)
}

So, now we have all the pieces in place to check individual characters.  It's time to break out some of the Swift standard library functions that will allow us to avoid importing Foundation.

We're back to working in stringByApplyingFormatting(), the method around which we've written our unit test.

We're going to first apply the case conversion rule by calling the method we wrote to do that, then we're going to filter out any illegal characters based on our ruleFilter method.  This will break our string down into an array of character sequences which can be joined back together with our replacementCharacter.  This will eliminate the trouble of repeatedly checking for occurrences of doubles of the replacement character.

The last step looks a little weird.  We need to check if the first or last character was an illegal character, and if so, stick the replacement character at the beginning or end (or both) because the join method will only place it between our sub sequences.  It won't keep track of whether or not it eliminated the first or last characters.

So, the logic within our stringByApplyingFormatting() method now looks like this:

func stringByApplyingFormatting(toString string: String) -> String {
    // Apply case conversion rule
    let caseValue = stringWithCaseConversionApplied(string)

    // Apply the rule filter to each character
    // This splits the string into an array of character subsequences
    let splitCharacters = caseValue.characters.split { !ruleFilter($0) }

    // Map the array of character subsequences to an array of strings that can be joined
    let splitString = splitCharacters.map(String.init)

    // Join the array of strings with the specified replacement character
    let joinedString = splitString.joinWithSeparator(replacementCharacter)

    // Check if the original string started or ended with an illegal character
    // If so, prepend/append the replacement character
    let finalString =
        (!ruleFilter(caseValue.characters.first ?? Character("")) ? replacementCharacter : "") +
        joinedString +
        (!ruleFilter(caseValue.characters.last ?? Character("")) ? replacementCharacter : "")

    return finalString
}

And with this logic, if we re-run our unit test, it's passing now.  And we also no longer need to import Foundation into our code base, so this code runs perfectly well on Linux too.

From here, the next step is adding a pretty significant suite of tests around all of the individual rules and all of the possible combinations of rules, with all sorts of test strings.

The full StringFormatter struct:

struct StringFormatter {
    enum CaseRule {
        case None, UppercaseOnly, ConvertToUpper, LowercaseOnly, ConvertToLower
    }

    enum AsciiRule {
        case None, AsciiOnly
    }

    var blacklistCharacters = Set<Character>()
    var replacementCharacter = ""
    var caseRule = CaseRule.None
    var asciiRule = AsciiRule.None

    func stringByApplyingFormatting(toString string: String) -> String {
        let caseValue = stringWithCaseConversionApplied(string)

        let splitCharacters = caseValue.characters.split { !ruleFilter($0) }

        let splitString = splitCharacters.map(String.init)

        let joinedString = splitString.joinWithSeparator(replacementCharacter)

        let finalString = (!ruleFilter(caseValue.characters.first ?? Character("")) ? replacementCharacter : "") + joinedString + (!ruleFilter(caseValue.characters.last ?? Character("")) ? replacementCharacter : "")

        return finalString
    }

    private func stringWithCaseConversionApplied(string: String) -> String {
        switch caseRule {
        case .ConvertToLower: return string.lowercaseString
        case .ConvertToUpper: return string.uppercaseString
        default: return string
        }
    }

    private func ruleFilter(character: Character) -> Bool {
        if blacklistCharacters.contains(character) {
            return false
        }

        if asciiRule == .AsciiOnly && !character.isAscii {
            return false
        }

        return caseFilter(character)
    }

    private func caseFilter(character: Character) -> Bool {
        if caseRule == .LowercaseOnly && String(character).uppercaseString == String(character) {
            return false
        }

        if caseRule == .UppercaseOnly && String(character).lowercaseString == String(character) {
            return false
        }

        return true
    }
}

The unit test is the same as posted above:

class StringTestStuff: XCTestCase {
    func testStringFormatting() {
        let input = "Is my résumé good enough?"
        let expectedResult = "is-my-r-sum-good-enough-"

        var stringFormatter = StringFormatter()
        stringFormatter.blacklistCharacters = Set(" -&+$,/:;=?@\"#{}|^~[]`\\*()%.!'".characters)
        stringFormatter.replacementCharacter = "-"
        stringFormatter.caseRule = .ConvertToLower
        stringFormatter.asciiRule = .AsciiOnly

        let formattedString = stringFormatter.stringByApplyingFormatting(toString: input)

        XCTAssertEqual(formattedString, expectedResult)
    }
}

As an addendum, one thing that might be neat to add to the StringFormatter struct would be a means for mapping certain characters to be replaced with specified characters.  So, for example, you're not going to allow ASCII, but you could potentially replace è with a "regular" e.

So we might add a property to the struct that looks like this:

var replacementMap = [Character: Character]()

So it's a dictionary where the key is the character we want to remove and the value is the character we want to replace it with.

stringFormatter.replacementMap = [
    "è" : "e",
    "é" : "e",
    "ê" : "e",
    "ë" : "e",
    "ē" : "e",
    "ė" : "e",
    "ę" : "e"
]

Of course, that particular map just covers the characters that might map to "e", and we'd have to do this before we applied the ASCII rule.  But implementation would look something like this:

private func stringByApplyingReplacementMap(string: String) -> String {
    return String(string.characters.map { return self.replacementMap[$0] ?? $0 })
}

For more reading on testing, check out Unit Tests Don't Prevent Bugs.


Utmost function that takes a comparator function

I agree that this generalization is not particularly useful: to abstract a part of a program to a functional parameter is meaningful when you can reuse that program with a class of different functions, not with two operators like < and >. For this, it is sufficient to define a boolean parameter:

(defun most (fn lst &key lowest)
 "What's the el of a list with highest or lowest score, according to provided
scoring fn?"
  (if (null lst)
      (values nil nil)
      (let* ((wins (car lst))                   ; 'wins' is 'winning element'
             (val (funcall fn wins))            ; 'max' is 'winning score'
             (comparison (if lowest #'< #'>))) ; highest or lowest ?
        (dolist (obj (cdr lst))
          (let ((score (funcall fn obj)))
            (when (funcall comparison score val)
              (setf wins obj
                    val score))))
        (values wins val))))

CL-USER> (most #'length '((a b) (a b a c) (a)))
(A B A C)
4
CL-USER> (most #'length '((a b) (a b a c) (a)) :lowest t)
(A)
1

More, I think that in this case one possibility of generalization could be not on the comparison itself, but on the functional parameter applied to the results, that it the maximum (for which the comparison is used). In fact the Paul Graham's function is the optimization of the following simpler (and less efficient!) function:

(defun most (fn lst)
  (let ((val (reduce #'max lst :key fn)))
    (values (find val lst :key fn) val)))

Abstracting on the function #'max:

(defun most (fn op lst)
  (let ((val (reduce op lst :key fn)))
    (values (find val lst :key fn) val)))

Making it a little more efficient:

(defun most (fn op lst)
  (let* ((vals (mapcar fn lst))
         (val (reduce op vals))
         (wins (position val vals)))
    (values (when wins (nth wins lst)) val)))

But I think that even this generalization is not particularly useful, even if it could have a little more sense:

CL-USER> (most #'length #'max '((a b) (a b a c) (a)))
(A B A C)
4
CL-USER> (most #'length #'min '((a b) (a b a c) (a)))
(A)
1
CL-USER> (defun avg (a b) (/ (+ a b) 2))
AVG
CL-USER> (most #'length #'avg '((a b) (a b a c) (a)))
(A B)
2
CL-USER> (most #'length #'+ '((a b) (a b a c) (a)))
NIL
7


Use different contructors of disposable class

As the constructor of PrincipalContext which only takes a ContextType as parameter internally calls this constructor

public PrincipalContext(ContextType contextType, string name, string container,
      ContextOptions options, string userName, string password){}

by passing null for the name I would change your method to

public class LDAPManager : ILDAPManager
{
    public bool ValidCredentials(string username, string password, string domain)
    {
        if (string.IsNullOrWhiteSpace(domain)) {
            domain = null;
        }
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            return context.ValidateCredentials(username, password);
        }
    }
}

based on the valid comment of Lightness Races in Orbit it can be that this implementation will change sometime. So be careful.

After getting this comment, I also noticed some naming issue with this method. Based on the naming guidlines, you should use verbs or verb phrases to name your methods.
So the method would be better named ValidateCredentials().


Passing uint64_t from C++ to R: Hilbert Mapping - xy2d function

Because we write C++, there's no reason to declare (most) variables at the beginning of the scope of your function. For example, all of d, rx, ry and s have been declared for no reason if you happen to throw and exit the function.
You don't need s after the for-loop, so it should be local to the loop only. Similar for rx and ry.
Make use of shorthand operators like /= and +=.
You can make v const and initialize it with a suitable constructor, in this case std::vector<uint64_t> v(1, d); initializes v to hold one element equal to d. But really, as it stands, I see no point in using an array here if you just have a single value (I suspect your example is incomplete and not representative of your real use case, which is a shame).
Because len can be const, make it const. This protects from unintended errors and possibly allows the compiler to perform more optimizations.
As a general comment, avoid saying using namespace std;, it's not good for you.
I don't know the interface of Rcpp::NumericVector, but might you initialize it directly in the spirit of const Rcpp::NumericVector nn(v.cbegin(), v.cend()), for instance?


Counting business days in a month, ignoring holidays

It is possible to do a cumulative sum in Oracle, indeed, using Analytic Function.

I've created a sample test table trying to reproduce the model presented in the question:

CREATE TABLE CALENDAR_DT AS
SELECT rownum calendar_dt_id
      ,DATE '2014-01-01'   + rownum - 1 calendar_dt
      ,0      business_day_number
FROM dual
CONNECT BY LEVEL <= 365;

A cumulative sum can be achieved using this sintax for instance:

SELECT SUM(t.calendar_dt_id) over(ORDER BY t.calendar_dt_id) cumulative_sum
      ,t.calendar_dt_id
FROM calendar_dt t;

The resultset will look like this

CUMULATIVE_SUM CALENDAR_DT_ID
-------------- --------------
         1              1
         3              2
         6              3
        10              4
        15              5
        21              6
        28              7
        36              8
        45              9
        55             10
        66             11
        78             12
        91             13
       105             14
       120             15
       136             16
       153             17
       171             18
       190             19
       210             20

The order by clause inside the parenthesis produces de cumulative sum.
If it is necessary to reset the sum every new month you can use the partition clause:

SELECT SUM(t.calendar_dt_id) over(PARTITION BY to_char(t.calendar_dt,'MM') ORDER BY t.calendar_dt_id) cumulative_sum
      ,t.calendar_dt
      ,t.calendar_dt_id
FROM calendar_dt t;

CUMULATIVE_SUM CALENDAR_DT CALENDAR_DT_ID
-------------- ----------- --------------
         1 1/1/2014                 1
         3 2/1/2014                 2
         6 3/1/2014                 3
        10 4/1/2014                 4
        15 5/1/2014                 5
        21 6/1/2014                 6
        28 7/1/2014                 7
        36 8/1/2014                 8
        45 9/1/2014                 9
        55 10/1/2014               10
        66 11/1/2014               11
        78 12/1/2014               12
        91 13/1/2014               13
       105 14/1/2014               14
       120 15/1/2014               15
       136 16/1/2014               16
       153 17/1/2014               17
       171 18/1/2014               18
       190 19/1/2014               19
       210 20/1/2014               20
       231 21/1/2014               21
       253 22/1/2014               22
       276 23/1/2014               23
       300 24/1/2014               24
       325 25/1/2014               25
       351 26/1/2014               26
       378 27/1/2014               27
       406 28/1/2014               28
       435 29/1/2014               29
       465 30/1/2014               30
       496 31/1/2014               31
        32 1/2/2014                32
        65 2/2/2014                33
        99 3/2/2014                34
       134 4/2/2014                35
       170 5/2/2014                36
       207 6/2/2014                37
       245 7/2/2014                38
       284 8/2/2014                39
       324 9/2/2014                40
       365 10/2/2014               41
       407 11/2/2014               42
       450 12/2/2014               43
       494 13/2/2014               44
       539 14/2/2014               45
       585 15/2/2014               46
       632 16/2/2014               47
       680 17/2/2014               48
       729 18/2/2014               49
       779 19/2/2014               50
       830 20/2/2014               51
       882 21/2/2014               52
       935 22/2/2014               53
       989 23/2/2014               54
      1044 24/2/2014               55
      1100 25/2/2014               56
      1157 26/2/2014               57
      1215 27/2/2014               58
      1274 28/2/2014               59
        60 1/3/2014                60

In those examples I used the id for summing just to get more evident. In your case you can use a sum of 1 conditioned to be a "day of week" using a Case expression exactly the way you used in your block, like this:

SELECT SUM(CASE
             WHEN to_char(t.calendar_dt, 'd') NOT IN (1, 7) THEN
               1
           END)
        over(PARTITION BY to_char(t.calendar_dt, 'MM')
             ORDER BY t.calendar_dt) new_business_day_number
      ,t.calendar_dt_id
      ,t.calendar_dt
      ,t.business_day_number
FROM calendar_dt t

After achieving the expected resultset, you can proceed with the update, but you don't need a block to do this if you use a MERGE statement:

MERGE INTO calendar_dt t
USING (SELECT SUM(CASE
                     WHEN to_char(t.calendar_dt, 'd') NOT IN (1, 7) THEN
                       1
                   END)
                over(PARTITION BY to_char(t.calendar_dt, 'MM')
                     ORDER BY t.calendar_dt) new_business_day_number
              ,t.rowid rid
        FROM calendar_dt t) u
ON    (u.rid = t.rowid)
WHEN  MATCHED THEN
  UPDATE
  SET    t.business_day_number = NVL(u.new_business_day_number,0);

I put the NVL function to avoid null value when the month happens to start in a weekend (feb-mar/2015 for instance) but I could have used the "ELSE 0" clause in the CASE expression as well.

I hope this helped you in some way.


Feedback on a small PHP function that generates JSON data

The first problem is what @Kinjal identified in your comment. You should only run your query once (in this particular case. You can do this because your querys basically return the same result).

So you run your query and load it into a table, and then you can iterate and work with that table. This will be much faster than running your query 3 times. Even so because 2 of your queries runs in a loop.

The second problem are your JSON members. using "a" and "b" as member names are a bad idea - name these what they should represent. I'd suggest substituting them for "unique" and "total". So your final JSON should looke like

{"date": "yyyy-mm-dd", "unique": 0, "total": 0 }


I don't have time to give you a full review, so I'll just add some comments about checkWinner:

It will read better if you remove the mutation of global state from it.  Make it a pure function that returns true or false.
You might consider using a 2D array as your data structure.  This isn't necessary, but it maps more naturally to the visual board, and will likely clean up some of your logic.

As for the duplication, you can remove a lot of it by introducing a helper function to capture the abstract logic that's being repeated in every block.  This will also clarify the high-level logic of checking for a winner:

function checkWinner() {
  for (var i = 0; i < board.length; i++) {
    var rightWin = winAt(i, 1)
    var downWin = winAt(i, width)
    if (rightWin || downWin) return true
  }
  return false
}

function winAt(i, step) {
  if ( board[i] === undefined ) return false
  for ( var j = 1; j < 5; j++) {
    var nextIndex = i + (j * step)
    if ( board[i] !== board[nextIndex] ) return false
  }
  return true
}

EDIT: Answer to question

Green Ball, regarding the problem you mentioned with using a 2D array, there are ways around that: you can pad with extra rows of undefined, or you can abstract a cell(i, j) which hides the ugly bounds checking, and keeps it in one place.  Indeed, that last point is the key one, not whether you use a 1D or 2D array.

In your current implementation, the arithmetic logic around rows is forced out on the client: any code that wants to get an i, j pair must do the calculation itself.  Currently happens in checkWinner and tileClick: board[tile + row * width].  It also happens implicitly in the double loop that constructs the html.

Regardless of the underlying structure that holds the board, you want your client code to be able to work with the concepts of "rows" and "columns" as first class citizens, since that's how we humans are thinking about this.  It will make the code more natural.


Your code looks good, just a few small things I would change. First, I didn't know where to start reading your code, since the function you would start with is at the bottom, and your example doesn't actually call it.

parseInt is used to convert a string to a number. If you just want to floor a number, use Math.floor instead. It is much faster.

In the isPrime function, every iteration of the loop calculates the same square root, which is not a simple calculation. Store the square root in a variable before the loop, and compare to that.

The getPrimes function works fine, but has potential for optimization, based on what we know about primes. For instance, with exception of 2, every primes is odd, so you only need to check every second number. You could also look into other methods, like a prime sieve.

There is no reason to still is var. Use let and const.


You're using C headers (which end in .h), not the C++ ones.  This will also ensure that they're put into the std namespace.  Also, you can remove <string.h> since it's not currently in use.
All of your operations rely on command line arguments, yet the program is still allowed to continue even if there aren't any (excluding the filename).  You can fix this by terminating the program right away if argc is too low.

if (argc == 1)
{
    // print this to the standard error stream
    std::cerr << "Additional arguments are required!";
    // same as return 1, also used for failure
    return EXIT_FAILURE;
}

With this in place, you should also redo the other argc checks.  Add this given check first, then have the others.  I'd also consider replacing else with an else if that includes a specific number of command line arguments.  With the else there, that code block will be executed with any other value not already given in an if.
Consider changing the parameter names of the functions for clarity.  Even if you're trying to pass the command line arguments to them, the functions themselves aren't very self-documenting.

You could also assign the various argv[] values to separate variables in main() and passing them to the other functions.  This again helps with self-documentation.
There's no need to declare and then initialize:

double operand;
operand = strtod(argv[2], NULL );

If you just need to initialize, then do that only:

double operand = strtod(argv[2], NULL );

The contents of mean():

double summation = sum(argc, argv);
return summation/((double) argc-2);

can just be a single line:

return sum(argc, argv) / ((double) argc-2);

The sum() function still reveals the intent, so it can be put together.


csview: A tiny utility to view csv files

Constants
They are better defined outside of functions; there is no need in reinitializing them each call.
Also they are not balanced, fixing it will avoid a weird body = '<tr>\n' + ....
Files management
Just in case the path of the input file contained a dot, I recommend you use rsplit('.', 1).
Also you should try to open the input file before the ouput one. Just in case an error happen during the access to the file, you won't create an empty output file.
And since you're dealing with CSV files, why not use the csv module? It will allow you to handle edge-case data (such as fields containing comas or newlines) easily.
Wrap stuff into tags
Since you're outputing HTML, it may be a better idea to build it as such: by wrapping stuff into tags.
You could define a PATTERN = "<{tag}>{{}}</{tag}>"  and a formatter:
def formatter(tag):
    return PATTERN.format(tag=tag).format

map that formatter at will to wrap stuff into tags.
Proposed improvements
import webbrowser
import sys
import csv

PATTERN = "<{tag}>{{}}</{tag}>"

def formatter(tag):
    return PATTERN.format(tag=tag).format

def csv_to_html(csv_file):
    reader = csv.reader(csv_file)

    header = formatter('tr')(
        '\n'.join(map(formatter('th'), next(reader)))
    )

    data = '\n'.join(
        map(formatter('tr'),
            '\n'.join(map(formatter('td'), row))
            for row in reader
        )
    )

    return formatter('table')('\n'.join((header, data)))

if __name__ == "__main__":
    csv_filename = sys.argv[1]
    html_filename = csv_filename.rsplit('.', 1)[0] + '.html'
    with open(csv_filename) as in_file:
        with open(html_filename, "w+") as out_file:
            out_file.write(csv_to_html(in_file))
    webbrowser.open(html_filename)


Increase the interval but shrink the view

Because you're plotting points you can't just increase the number of points you have, as you know, that will take up much more processing power. To mitigate this processing power issue, you need to shrink the view of your graph to display a smaller area. This has the effect of zooming in.

If you were using a more advanced way to draw the functions (i.e. estimating the area between points and drawing curves) you would most likely not have this issue, but using only points and a for loop limits you.

Another problem I barely noticed, you're overdrawing. It would seem that you're plotting past the borders of your canvas/graph. This causes unnecessary drawing that slows down everything. You should be basing the size of the area you're drawing on the width and height of the canvas.


StreamIterable - create an iterable from a Java 8 Stream

Two things:

I think you have missed the native implementation. Are you intentionally re-inventing the wheel? Streams have an iterator() method.
Note that streams cannot be reversed, so, while you can create an iterator once, from the stream, you cannot create a second iterator.... In other words, you cannot loop more than once through your iterable.

Consider reworking your class as:

public class StreamIterable<T> implements Iterable<T> {

  private final Stream<T> stream;

  public StreamIterable(Stream<T> stream) {
    this.stream = stream;
  }

  @Override
  public Iterator<T> iterator() {
    return stream.iterator();
  }
}

That's it, no additional code needed. You can still only iterate it once, but, you can add the above to an enhanced-for loop:

for (String v : new StreamIterable(Files.lines(...)) {
    ....
}


I'm no CSS expert, but two things I would change are:

remove unnecessary spaces (indenting and in ' : ').
condense explicit margin-top, margin-left etc (and padding):

h1{
width:40%;
background:#eee;
box-shadow:0 0 5px 5px #888;
margin:10% 30% 0 30%;
padding:10px 0 10px;
text-align:center;
font-family:"Arial", "Century Gothic", "Lucida Sans Unicode";
}

form{
width:30%;
background:#eee;
box-shadow: 0 0 5px 5px #888;
margin:1% 35% 35%;
padding:10px 0 10px;
}

label{
width:60%;
display:inline-block;
text-align:right;
margin:10px 10px 10px;
font-family:"Arial";
}


Java Implementation of Sieve of Eratosthenes algorithm

Using vertical spaces (new line) to group related code will help to easier read your code.
if(primeNumbers[i] == true) the checking with == true is superfluous because the condition of the if is a boolean one, so you can simplify this to if(primeNumbers[i])

- instead of using maxPrime here

    boolean [] primeNumbers = new boolean [maxPrime];
    Arrays.fill(primeNumbers, true)

you should take advantage of the computed int maxNumToTest like you did in the first loop. You should also add this computed value as the end of the inner loop and the result loop like so

    int maxNumToTest = (int) (Math.floor(Math.sqrt(maxPrime)));
    boolean [] primeNumbers = new boolean [maxNumToTest];
    Arrays.fill(primeNumbers, true);

    for(int i = 2; i <= maxNumToTest; i++) {
        if (primeNumbers[i]) {
            for (int j = i * i; j <= maxNumToTest; j += i) {
                primeNumbers[j] = false;
            }
        }
    }
    long stop = System.nanoTime();
    for(int i = 2; i <= maxNumToTest; i++) {
        if(primeNumbers[i]) {
            System.out.print((i) + ", ");
        }
    }

- putting everything int main() should be avoided. The current code could be divided into 3 methods:

reading the input
computing the primes
writing the output

In this way each method has a single responsibility and is easier to read and to maintain.


Macro for rounding with variable precision

I'd go with an inline function, as @pacmaninbw said, instead of a macro. It's more readable and it's easier to notice things that you may want to optimize.
A couple of things that may speed this up a bit if you use a function:

It would be easier to store the result of pow((double)10,numDig) in a variable, so you can compute that only once (you're doing it twice, now). While you're at it, you may think about pre-computing a few values, say up to 10^26 and use a lookup table. I'm not really sure that it'd be faster for such a simple operation, though.
The MY_SIGN macro only returns -1 or 1, then you multiply the result by 0.5. These are hard-coded values, so why not having something that returns -0.5 or 0.5 instead ?


You didn't incude it in your post, but I'm comment on it anyway: The way you assign the validator function to your select elements isn't very optimal:

      $('#MainContent_ddOpenBrd1').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd2').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd3').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd4').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd5').change(function () {
          validateTeam('openSelect');
      });

You've got five calls all doing the same thing. You should at least combine them into one:

      $('#MainContent_ddOpenBrd1, #MainContent_ddOpenBrd2, #MainContent_ddOpenBrd3, #MainContent_ddOpenBrd4, #MainContent_ddOpenBrd5').change(function () {
          validateTeam('openSelect');
      });

Even better would be to select them with a more optimal selector such as a common class, or in this case a desendent selector:

      $('#openSelect select').change(function () {
          validateTeam('openSelect');
      });

This assigns the handler to each elements separately. You can go yet another step and use a delegated event handler, so that in the end you'll have a single handler assigned to a single element:

      $('#openSelect').on('change', 'select', function () {
          validateTeam('openSelect');
      });

And now you can get rid of the hard-coded ID as the parameter for your function:

      $('#openSelect').on('change', 'select', function (event) {
          validateTeam(event.delegateTarget.id);
      });

So, if you have multiple independent groups you can assign them all with one call - even if you don't reference them by their IDs, but for example a class:

      $('.select-group').on('change', 'select', function (event) {
          validateTeam(event.delegateTarget.id);
      });

Speaking of the function parameter: Instead of passing the ID you should directly pass a reference to that element - and with the change from above it's simple:

      $('#openSelect').on('change', 'select', function (event) {
          validateTeam(event.delegateTarget);
      });

So the start of your function changes to:

      $(section).find('> .form-group select').each(function () {

A short point about your variable names: You should only use $ as a prefix if the variable contains a reference to a jQuery object. Neither $selectionArr nor $optText do that. Also $selectionArr is a bad name. Something like selectedCountries would be better.

One impracticable thing you are doing, is reading/parsing the country abbreviation from the display label of the option. Generally trying to get information from a text that is intended for the user to read is a bad thing, since it can change at any time, e.g.

the abbreviation is moved to the end of the string
the full name of the country should be displayed
the abbreviation/name is replaced with an icon
etc.

Any of those events requires you to change your validation function.

Instead you should store such important information independently from the display string, for example in a data-* attribute:

<option value="11700599" data-country="AFG">AFG Farazi Khaiber (2134)</option>

and get it from there:

      var country = $(this).find('option:selected').data('country');

      if (country) { // No need to check the length, just if the value is set at all
        $selectionArr.push(country);
      }

You can also optimize the reading of the countries, for one by directly selecting the options in the "outer" selector (and also limiting it to ones that actually have a data-country attribute), and for another by usings jQuery's .map() function to convert the list of options directly into a list of strings:

         var $selectionArr = $(section).find('> .form-group option[data-country]:selected').map(function () {
           return $(this).data('country');
         });

That's all for now. If I have time I'll come back later.

EDIT: Some more:

Now to the validation loop:

You can optimize the checking of duplicates by using an object like a set instead of an array. That saves you having to search the array, but however requires you to count the number of entries yourself.

You should also also move the updating of the warning label to after the loop, since currently you are unnecessarily updating it in each run through the loop.

Finally you shouldn't hard code the ID for the warning label, because it won't work if you have multiple groups. Instead give it a class and search for it inside the group. Also it would be better to show/hide it instead of just clearing the text.

var countrySet = {};
var countryCount = 0;
var hasDuplicates = false;

$.each($selectionArr, function (index, country) {
    if (countrySet[country]) {
        hasDuplicates = true;
    } else {
        countrySet[country] = true;
        countryCount++;
    }
});

var warningLabel = $(section).find('.warning');

if (!hasDuplicates && countryCount === 5) {
   warningLabel.removeClass('label-danger').addClass('label-success').text('Valid!').show();
} else if (hasDuplicates) {
   warningLabel.removeClass('label-success').addClass('label-danger').text('Duplicates!').show();
} else {
    warningLabel.hide();
}

I'll leave displaying the duplicate country as an exercise :-)


Simple LRU cache with an expiration time

I still don't see how it is LRU, but that's beside the point.

One obvious problem is a race between testing for cache.get(key).isExpired() and cache.remove(key) on the next line. It is very well possible for another thread to preempt right in between just to get() that object.

A thread performing get() would believe that it updated useTime, yet the entry would have been removed.

Depending on the use case, the consequences could be catastrophic, or harmless.


Mechanism to retry failed requests, with throttling

Prefixing field members with _ is more of an "old school" C# approach. It's a preference, I guess, but I think it's not really used anymore.

If the only thing you do with SECONDS_TO_THROTTLE is Task.Wait(SECONDS_TO_THROTTLE * 1000), then SECONDS_TO_THROTTLE should be equal to 60000, not 60, it's kind of confusing. At first I thought maybe there was something related to milliseconds, but no.

Reading your explanation, I understand why you do : if (_timesFailed >= ATTEMPTS_BEFORE_THROTTLE * 3), but if I only had your code, I wouldn't. Consider either adding another constant or maybe a comment.

CheckForThrottle's name is confusing. Reading this, I'd expect the method to tell me if I need to throttle, not to do the throttling itself. I'd either rename it to something else. But then again, I'd notice that a name like MaybeThrottle is a poor name. I'd keep the "should I throttle?" approach in this method, but I'd move Task.Delay(SECONDS_TO_THROTTLE * 1000).ContinueWith((t) => { _timesSinceReset = 0; }); some place else.


Determine if the student has passing grades

Reduce code repetition / redundant checks
Your if statements are redundant. If grade = 90, it already satisfies the grade >= 80, so just use that. No need to check if it equals 90 exactly because that's already covered.
Instead of having four different lines where you show a message dialog, have a string that you assign the message to and print that at the end? Something like this:
String message;
if (grades >= 80) {
    message = grades + ": Passed!";
} else if (grades >= 75) {
    message = grades + ": Academic Warning!";
} else {
    message = grades + ": Failed!";
}
JOptionPage.showMessageDialog(null, message);

Reduce unused code
You created a Scanner in all of your functions, but never use them. I'd remove them for code clarity.


Userscript to redirect insecure pages to HTTPS

Overview

Pass global variables as parameters to IIFE to make your code more independent and clear
Use addEventListener method to follow recommended way of attaching event listeners
Do you really need to execute redirection code, only when everything is loaded?
I would use regex to replace protocol to make solution robust
Try to not duplicate constant values (in this case protocol)

Suggested solution

(function (w) {
    'use strict';

    var secureProtocol = 'https';

    if ( !w.location.protocol.startsWith(secureProtocol) ) {
        w.location.href = w.location.href.replace(/^[^:]+/, secureProtocol);
    }
})(window);


I'd rename the searchModule method to readModuleName since it doesn't search, it just reads the name of the name of the searched module.
Instead of the iterators use the new foreach loop (as you already use it for the modules):

for (Student student: students) {
        ...
}

If you use iterators set the type parameter which makes the casting unnecessary:

final Iterator<Student> it = students.iterator(); // type parameter here
while (it.hasNext()) {
    Student student = it.next(); // no casting here
    ...
}

Declare variables on the first use:

Scanner scan = new Scanner(System.in);

Don't forget to close the Scanner That was a bad advice, since it closes System.in too. See also: Close a Scanner linked to System.in
Split up the moduleStudentSearch method, it does four things:

read the searched module name
search the module by name
search student by module
print the results

Each function should have a separate method:

public static void moduleStudentSearch(final Set<Module> modules, final Set<Student> students) {

    final String searchedModuleName = readModuleName();
    final Module module = searchModule(searchedModuleName, modules);
    if (module == null) {
        printNoModuleFound(searchedModuleName);
        return;
    }
    final Set<Student> studentsWithModule = getStudentsWithModule(students, module);
    printStudents(studentsWithModule);
}

private static void printNoModuleFound(String searchedModuleName) {
    System.out.println("No module found with name: " + searchedModuleName);
}

public static String readModuleName() {
    System.out.print("Search module code: ");
    final Scanner scan = new Scanner(System.in);
    try {
        final String searchModule = scan.nextLine().trim();
        return searchModule;
    } finally {
        scan.close();
    }
}

// you could return a list/set here if there are more than one results
public static Module searchModule(final String searchedModuleName, final Set<Module> modules) {
    for (final Module module: modules) {
        final String moduleName = module.getName();
        if (searchedModuleName.equalsIgnoreCase(moduleName)) {
            return module;
        }
    }
    return null;
}

public static Set<Student> getStudentsWithModule(final Set<Student> students, final Module module) {
    final Set<Student> result = new LinkedHashSet<Student>();
    for (final Student student: students) {
        if (student.hasModule(module)) {
            result.add(student);
        }
    }
    return result;
}

private static void printStudents(final Set<Student> students) {
    for (final Student student: students) {
        System.out.print(student.getName());
        System.out.print(" ");
    }
}

I'd create a StudentManager and a ModuleManager class. searchModule should be in the ModuleManager and it should use its internal Set<Module> modules field instead of the method parameter. The same is true for the getStudentsWithModule method: it should be inside the StudentManager class and it should use its internal Set<Student> students field instead of the method parameter. It results high cohesion.

Once you have these classes, remove the static modifier of the methods.
Check your input: check for nulls, empty Strings etc. and throw proper exceptions (usually NullPointerException or IllegalArgumentException) with a helpful message:

public static Set<Student> getStudentsWithModule(final Set<Student> students, final Module module) {
    if (students == null ) {
        throw new NullPointerException("students cannot be null");
    }
    if (module == null) {
        throw new NullPointerException("module cannot be null");
    }
    ...
}


If I understood what you are doing correctly you are compiling index.handlebars using data from content.js and you want to recompile if any of those files changes. Below is a simplified and NOT TESTED example of what your code can look like

// removed gulp-watch (built in gulp by default)
// also removed spawn, argv and batch
var gulp = require('gulp');
var handlebars = require('gulp-compile-handlebars');
var rename = require('gulp-rename');

handlebars.Handlebars.registerHelper('next', function(context, idx, options) {
    if (context[idx + 1]) {
        return options.fn(context[idx + 1])
    } else {
        return "";
    }
});

// compile index.handlebars with data from content.js
gulp.task('handlebars', function() {
    var templateData = require('./content.js');
    var options = {};

    return gulp.src(['index.handlebars'])
        .pipe(handlebars(templateData, options))
        .pipe(rename('indexCompiled.html'))
        .pipe(gulp.dest('.'));
});

// watch for changes in content and index files
// and then run handlebars task
gulp.task('watch', function(){
    gulp.watch(['content.js', 'index.handlebars'], ['handlebars']);
});

// on run `gulp` compile and start watching for changes
gulp.task('default', ['handlebars', 'watch']);


Suffix array construction in \$ O(n \log^2 n) \$

1. Review

I'm reviewing the updated version of the code only.

There's no docstring. What does this function do? How do I call it? What does it return? Can you give an example of what it does?
The names are obscure. We're not running out of letters, so suffix_array would be clearer to the reader than sufar. (You said in comments that this was to make it "quicker to type" but in that case maybe you need a better editor? Most programming editors these days have some kind of completion facility on names.)
The algorithm is tricky enough that it needs explanation. My advice would be to add comments to the loop explaining the invariants that holds at each iteration. (Figuring out loop invariants is invaluable for understand how an algorithm works, and they can be turned into assertions that check the correctness of the implementation.)
The code does not actually implement the algorithm in the Vladu/Negruşeri paper. A comparison with their C implementation on page 6 shows that there are two points of difference.

(i) When preparing the L array (result in sufar), if i + cnt is out of bounds (j + n in sufar), the dummy element is used, but in sufar the index is wrapped around to get cls[(j + n) % N].

(ii) When computing the new P array (cls in sufar), if L[i] differs from L[i - 1] then the entry in P is assigned the value i. However, in sufar, the entry in cls is assigned the value cls[result[j - 1][2]] + 1.

Nonetheless, despite these differences in the implementation, sufar gets the correct result!

In case (i) that's because the original algorithm imagines extending the string with enough dummy characters to make the suffixes the same length (thus abac becomes abac$$$$ and the 4-character suffixes are abac, bac$, ac$$, c$$$, and $$$$ which gets discarded), whereas sufar images extending the string with a single dummy character and then a repeat of itself (thus abac becomes abac$aba and the 4-character suffixes are  abac, bac$, ac$a, c$ab and $aba which gets discarded). But the single $ is enough for these to come out in the correct order.

In case (ii) we only care about the sorted order of the entries in P, not their actual values, so the change makes no difference.

I think that difference (ii) is fine, but (i) is sufficiently tricky that I would avoid it if at all possible. (Or else write a comment explaining why I did it.)
To make it easy for the reader to check that you've correctly implemented the algorithm in the paper, I would use the same notation as the paper unless there was a very good reason not to. So txt → A, cls → P, result → L, N → n, n → count, etc.
Instead of set(t for t in txt), just write set(txt).
Instead of adding chr(0) to txt and then making equivalence classes for the entries in txt (which relies on chr(0) not already appearing in txt), make the equivalence class first, and then append an equivalence class that you know is not present, for example -1.
Instead of computing ceil(log2(N)), start with count = 1 and double it each iteration until it is too large. This avoids the dependence on the math module.
It turns out that there's no need to actually add a dummy value to the text in the first place. If we avoid this, then we can also avoid adding 1 to N and avoid having to drop the initial element of result at the end.
The initialization of the cls array based on the sorted equivalence classes of the length-1 substrings of txt is really just a special case of the way that cls is updated in the loop. If the loop were turned upside down so that it computes cls first and then result, you could arrange to avoid the special initialization of cls. See below for how this is done.
Another benefit of turning the loop upside down is that it avoids a wasteful computation of cls on the last iteration that will never be used.
Numeric tuple lookups like the [2] in result[j][2] are hard to understand. It's usually better to unpack the tuple into local variables so that you can refer to its elements by name.
In Python it's usually best to avoid iterating over sequence indices, if possible, and to prefer iterating over the elements directly. Here the computation of cls involves iterating over pairs of adjacent elements in result; you could use the pairwise recipe from the itertools module, or combine zip and itertools.islice as I've done below.

2. Revised code

from itertools import chain, islice

def suffix_array(A):
    """Return a list of the starting positions of the suffixes of the
    sequence A in sorted order.

    For example, the suffixes of ABAC, in sorted order, are ABAC, AC,
    BAC and C, starting at positions 0, 2, 1, and 3 respectively:

    >>> suffix_array('ABAC')
    [0, 2, 1, 3]

    """
    # This implements the algorithm of Vladu and Negruşeri; see
    # http://web.stanford.edu/class/cs97si/suffix-array.pdf

    L = sorted((a, i) for i, a in enumerate(A))
    n = len(A)
    count = 1
    while count < n:
        # Invariant: L is now a list of pairs such that L[i][1] is the
        # starting position in A of the i'th substring of length
        # 'count' in sorted order. (Where we imagine A to be extended
        # with dummy elements as necessary.)

        P = [0] * n
        for (r, i), (s, j) in zip(L, islice(L, 1, None)):
            P[j] = P[i] + (r != s)

        # Invariant: P[i] is now the position of A[i:i+count] in the
        # sorted list of unique substrings of A of length 'count'.

        L = sorted(chain((((P[i],  P[i+count]), i) for i in range(n - count)),
                         (((P[i], -1), i) for i in range(n - count, n))))
        count *= 2
    return [i for _, i in L]


FIFO queue for a 2D array in ANSI C, version 2

Good formatting
Good use of (u)intN_t types
When printing, use a matching format specifier: printf("%" PRI16u , array_print[0]);
Avoid naked magic numbers
Define constants for flexibility and clarity
// int user_num[5] = { 0] };
//uint16_t big_array[10][5] = { 0 };

#define BIG_ARRAY_MAXJ 10
#define BIG_ARRAY_MAXI 5
int user_num[BIG_ARRAY_MAXI] = { 0 };
uint16_t big_array[BIG_ARRAY_MAXJ][BIG_ARRAY_MAXI] = { 0 };

Instead of 9, use BIG_ARRAY_MAXJ - 1, etc.
To address the "I could have put macros down to name 5 and 10 but I didn't see how that could be advantageous," comment: using named constants convey to others, including yourself at a later time, the relationship amongst the many constants and their individual meaning.
Global objects
Typically, it is far better to code for use of local objects than global ones.
Instead of
random_num_input(void)

Pass in a pointer to the array and its dimensions.  If VLA is supported:
random_num_input(int jn, int in, uint16_t a[j][i]) {
  for (int j = 0; j < jn; j++) {
    for (int i = 0; i < in; i++) {
        a[j][i] = rand() % 256;
    }
}

Array indexing
For big arrays, consider size_t instead of int to well handle large arrays.  size_t is the Goldilocks size for array sizing and indexing: not too small, not too big.
For big arrays, likely also need to move to allocated memory rather than fixed sizes.
Comment/code off by 1.
rand() % 255 forms values [0...254], not [0...255].
// stores random numbers between 0-255 into big_array ...
        big_array[j][i] = rand() % 255;

Consider
big_array[j][i] = rand() % 256;
// or
big_array[j][i] = (uint8_t) rand();

Copying arrays
With arrays of the same dimension and type, as here, could use memcpy().
// for (int j = 0; j < 10; j++) //
//    for (int i = 0; i < 5; i++) {
//        big_array_copy[j][i] = big_array[j][i];
//    }
//}

// if known to be non-overlapping
memcpy(big_array_copy, big_array, sizeof big_array_copy);
// else
memmove(big_array_copy, big_array, sizeof big_array_copy);

Minor: Tidier print
Consider not printing a trailing ','.  Little reason for a global array_print[].  Use the correct portable specifier
    char *sep = "";
    for (int i = 0; i < BIG_ARRAY_MAXI; i++) {
        printf("%s%" PRI16u , sep, big_array_copy[j][i]);
        sep = ",";
    }
    printf("\n");


Represent a person who has different roles for different offices

Here's my comments on your code.

interface Person {
    name : string,
    /**
     * Because you can have an employee working at multiple offices, they cannot have only one OfficeRoles object.
     * The roles relationship should reflect the potential for multiple offices.
     */
    roles : OfficeRoles
}

interface OfficeRoles {
    roles : OfficeRole[]
    office : Office
}

interface OfficeRole {
    /**
     * This doesn't need to be a function, you could implement a readonly property in the class that's assigned
     * when the OfficeRole is created.
     */
    getType() : RoleType
}

/**
 * The Office object does not include the roles it has, or the employees who currently hold those roles.
 */
interface Office {
    name : string
}

/**
 * I'd recommend against going with an Enum if the type of roles could be office specific.
 */
enum RoleType {
    CLERK,CUSTODIAN,SECURITY
}

let office : Office = { name : "OfficeMax" };
// Does not compile, there is no Role class or interface.
let roles : Role[] = [ new ClerkRole( "John" ) , new SecurityRole(1) ];
let person : Person = { name : "John" , roles : roles };

/**
 * No Role interface exists.
 * Also, you shouldn't subclass OfficeRole just to provide a different value for {@link getType}, that can be done
 * in a constructor.
  */
class ClerkRole implements Role {
    private name : string;
    constructor( name : string ) {
        this.name = name;
    }
    getType() { return RoleType.CLERK; }
}

class SecurityRole implements Role {
    private id : number;
    constructor( id : number ) {
        this.id = id;
    }
    getType() { return RoleType.SECURITY; }
}

Here's the direction I'd take it in. This does not include any methods you'd normally have to manage the relationships between employees and roles, nor does it include the classes (they're straightforward). It also doesn't include any methods you'd need to maintain the integrity of your object graph.

/**
 * Represents an employee.
 * An employee can work at different offices and does not have a relationship with an office beyond having a
 * role there, therefore office is not modeled on the employee directly.
 */
interface IEmployee {
    name : string
    roleAssignments: IAssignedRole[];
}

/**
 * An employee can work at multiple offices with different roles, which means a N:N relationship between
 * {@link IEmployee} and {@link IRole}.
 */
interface IAssignedRole {
    employee: IEmployee;
    role: IRole;
}

/**
 * Assumes there can be any number of roles for a given office. Each role needs a name and exists for only one office.
 */
interface IRole {
    name: string;
    office: IOffice;
}

/**
 * Represents an office.
 */
interface IOffice {
    name: string
    /**
     * Defines roles permitted for this office.
     */
    roles : IRole[];
    /**
     * Captures the roles assignments for this office.
     */
    roleAssignments : IAssignedRole[];
    /**
     * Provides list of employees by iterating through the role assignments.
     */
    readonly employees: ReadonlyArray<IEmployee>;
}

Let me know if you have any questions :)


Custom ViewModel to check property existance prior to update

#if DEBUG
// We need reflection in order to debug our Property Changed Notifications
using System.Reflection;
#endif

That #if directive is overkill. A using statement isn't like a C++ include, it doesn't clutter up your assembly with code you may not need. All it does, is facilitate coding by telling the parser that types in these namespaces don't need to be fully qualified; once the code is compiled, they're "inlined" anyway.

Now, the idea is nice, but as you noticed, you can give it just about any value and it happily passes the "name" to whoever is listening for that event.

That string parameter isn't refactoring-friendly. You've mitigated the issue by throwing an InvalidOperationException - if your ViewModel classes' setters are 100% covered with unit tests, you're probably good to go.

The thing that worries me is that the exception isn't thrown in a release build, so instead of blowing up and failing promptly, you're failing silently, and worse things could result from this. Of course that should not happen.. but the room for human error is there.

The best way to implement that interface, is in my opinion with a strongly-typed overload that takes a selector expression and passes the selected member's name to the interface's stringly-typed method.

Something like this for example, can turn your setters into something like this:

private int _foo;
public int Foo
{
    get { return _foo; }
    set
    {
        if (value != _foo)
        {
            _foo = value;
            OnPropertyChanged(() => this.Foo);
        }
    }
}


Is this a bug ?

The correspondending tree you showed is not consistent.  It should look like

|--p_
    |--p_a
    |--p_a_
          |--p_a_test  <- this
    |--p_LIG
    |--p_p
    |--p_p_
        |--p_p_c
        |--p_p_c2
        |--p_p_ccc
        |--p_p_test
    |--p_tres
TestLineGraph1
TestLineGraph

Style

You should always be consistent with the coding style you use. So if you omit (<-bad) braces {} for loops with a single statement, you should stick to it.
You shouldn't shorten variable / parameter names because that removes readability. -> lvl

Comments

Comments should describe why something is done. What is done should be described by the code itself by using meaningful names for classes, methods, parameters.

A comment which describes what is done like

 // Create the new node
new GraphUINode(children, this, currentPrefix, lvl + 1);

should be removed.

Refactoring

Can't be done until the possibility of the bug as mentioned is cleared.

As the root problem to solve is to create a tree structure based on a List<string> I would extract this tree creation outside of the constructor to a separate method which only takes a List<string> as input parameter and is returning something like

class TreeNode
{
    public String Name { get; private set; }
    public IList<TreeNode> ChildNodes { get; private set; }
    public TreeNode()
    {
        ChildNodes = new List<TreeNode>();
    }
    public void FillChildNodes(IList<String> childNodes)
    {

    }
}


Don't put everything into one big main()

If you can separate out the reading of inputs and writing of results from the actual multiplications, then it will be easier to test the multiplication code separately.

Avoid non-standard libraries

Here we have "stdafx.h" and scanf_s that aren't part of standard C++.  Ditch those and use the standard facilities (e.g. std::cin >> a[j][l]).

Include what you use

We don't seem to use <cmath> anywhere, so let's drop that.  We'll need <cstdio> for std::printf() - or switch to C++ style output using <iostream>.

Avoid using the whole std namespace

The std namespace isn't one of the few that's designed to be imported wholesale like that, and there's potential for name conflicts when moving to a new standards version.  Specify just the names you need, or just get used to writing std:: - it's intentionally very short.

Use C++ collections

It's easier to work with the C++ collection types such as std::array or std::vector than with raw (C-style) arrays (which decay to pointers when passed as function arguments).


Using generators to print the tree-like structure of a project

Generators

Since you were asking about generators specifically, let’s start with some suggestions on how you’re using them:

Your find_entities() function opens a file, then iterates over the lines in that file. That’s a good use of Python’s ability to iterate directly over the lines in a file, but it’s a bit fiddly to unit test because you have to create files.

I often write my generators to take an iterable of lines (which could be an open file object, or something else) – this makes the code easier to unit test, and more generic. I can read the lines from an arbitrary iterator, not just a file. It’s a small change:

def find_entities(lines, pattern):
    for line in lines:
        m = pattern.match(line)
        if m:
            yield m.group('entity'), m.group('component').split('.')[-1]

Your _vhdltree() function is really doing two things: it’s working out the level, entity and path for an element in the iterator, and then printing it. Problem with printing is that it becomes hard to reuse this computation elsewhere. Better if you split the printing out from this function, and defer that to the caller.

Something like:

def parse_vhdltree(level, filepath, pattern, vhd_files):
    for entity, component in find_entities(open(file path), vhd_files):
        try:
            path = vhd_files[component.lower()]
        except KeyError:
            continue
        yield level, entity, path
        for entry in parse_vhdltree(level+1, path, pattern, vhd_files):
            yield entry

...

for level, entity, path in parse_vhdltree(0, filepath, p, vhd_files):
    print('    ' * level + entity + ' : ' + path)

(I’ll talk about the KeyError in a minute.)
I really like your find_vhd() generator, and it’s a good example of how generators can clean up code in Python. All the messy logic of deciding which files to count is absorbed in this function.

One tweak I would make is to throw away the dirnames data – you’re not using it. Using an underscore in its place is a common convention to indicate you’re not interested in a particular value:

def find_vhd(proot):
    for (dirpath, _, filenames) in walk(proot):
        if not isexcluded(dirpath.lower()):
            for fn in filenames:
                if fn[-4:].lower() == ".vhd":
                    yield fn[:-4].lower(), pjoin(dirpath, fn)

General Python style

Generators aside, here are some comments on your general Python style:

I have a bit of a hobby horse about use of regular expressions. I think you’re using them for a sensible reason, but you could be better about commenting, and explaining what they’re trying to match.

Breaking it over multiple lines, and explaining exactly what you’re trying to match against, will make it much easier to read. Additionally, when you come back to this code in six months, you’ll thank your past self for those comments.

I would also suggest pre-compiling the instantiation_regex at the top of the file, alongside BASIC_ID_REGEX.
Your isexcluded() function could be replaced with a one-liner:

return any(excluder in path for excluder in EXCLUDES)

This is using a lazy generator expression as the argument, and the nice thing about any() is that it exits as soon as it gets a positive element.

I see that you’re already using an equivalent expression with all() in the GitHub version, which is similarly lazy. It exits as soon as it finds a negative element.
I’m not a super fan of from foo import bar style imports, especially from the standard library. Even worse if from foo import bar as baz, as you’ve done with os.path.join.

Characters are cheap – use the full, stdlib name. It will make your code much easier to read for other Python developers, who don’t need to worry about what pjoin() does. They can just recognise os.path.join.
Rather than using a sentinel value from dict.get() to denote a missing key in the dictionary, do a lookup with square brackets and catch the KeyError. This is more Pythonic, and avoids problems if the sentinel value turns up in the dictionary.

And I think using a dictionary here is fine. It’s simple, clean, and it works.


Using Token Bucket to rate limit function calls

Avoid casting time too much
A lot of code is spent on converting time to integers. Avoid casting too early; store time as much as possible as std::chrono types.
In fact, intead of storing how much tokens there are in the bucket, you could instead store how much time there is in the bucket. Then only in areTokensAvailable() do you need to cast from the amount of time in the bucket to the number of tokens.
For example, the result of two calls to std::chrono::...::now() can be subtracted from each other, the result is a duration that can be added to another duration.
Consider using shorter function and variable names
Your function and variable names are very verbose, to the point that they make the code harder to read. Try to make them more concise, remove redundant information. I would also avoid using prefixes such as fa_. Does it stand for function argument? It's already clear from the function definition that it's an argument. The m_ prefx for private member variables is more commonly used, and sometimes helps avoid name clashes, so I would keep that.
Use a single type to store the number of tokens
In your code, you use both uint64_t and int for the number of tokens. Be consistent and stick with a single type. Use a type alias to make it more explicit.
Use std::chrono::steady_clock
Don't use std::chrono::system_clock for measuring the passage of time. It will give incorrect results when daylight savings time changes, when there are leap seconds and whenever the system clock gets changed (either by an administrator or by something like an NTP daemon). The std::chrono::steady_clock is guaranteed to be a monotonically increasiing clock. I would also create a type alias for it to reduce typing.
Example
Here's an example of how the code can be made to look:
class tokenBucket {
    using count_type = uint64_t;
    using clock = std::chrono::steady_clock;

public:
    tokenBucket(count_type rate): m_rate(rate) {}

    bool request(count_type count) {
        std::lock_guard<std::mutex> lock(m_mutex);
        refill();
        return try_remove(count);
    }

private:
    std::mutex m_mutex;

    count_type m_rate;
    clock::time_point m_last_refill{clock::now()};
    clock::duration m_available{};
    clock::duration m_capacity{std::chrono::seconds(1)};

    void refill() {
        auto now = clock::now();
        m_available += now - m_last_refill;
        m_available = std::min(m_available, m_capacity);
        m_last_refill = now;
    }

    bool try_remove(count_type count) {
        auto requested = count * clock::duration(std::chrono::seconds(1)) / m_rate;

        if (requested <= m_available) {
            m_available -= requested;
            return true;
        } else {
            return false;
        }
    }
};

Note: m_capacity here holds the size of the bucket as a time duration. If it is constant, you can make it a static constexpr variable.


Best practice to create XML messages with DOMDocument class in PHP

Your message classes currently have two responsibilities: representing an application logic message and transforming itself into a representation. If you want to add other ways of serialization you have to modify the message classes itself.

The message classes only should represent the message while some other facility should be responsible for serializing your messages into xml. This keeps the interface of your message classes clean (not inheriting all those methods from DOMDocument) and allows to easily add other serialization formats.

This particular situation wants a strategy pattern: a dedicated MessageXmlSerializer takes a message, creates the surrogate DOMDocument and itself delegates the serialization of the message further to specialized classes for each message:

<?php

class MessageXmlSerializer {

    private $messageSerializers;

    public function serialize(Message $message) {
        $node = $this->createDocumentContainer();

        foreach ($this->messageSerializers as $serializer) {
            if ($serializer->canHandle($message)) {
                $node->appendChild($serializer->serialize($message));
            }
        }
    }

    protected function createDocumentContainer() {
        $node = new DOMDocument();
        // Do your intialization here
        return $node;
    }
}

The dedicated serializers are rather simple. Of course they all share a common interface:

interface MessageSerializer {
    public function canHandle(Message $message);

    public function serialize(Message $message);
}

And finally the serializer specialized on serializing Message_1

class MessageOneSerializer implements MessageSerializer {
    public function canHandle(Message $message) {
        return $message instanceof Message_1;
    }

    public function serialize(Message $message) {
        // create your node here and return it
    }
}

So far the basic concept. Now new message types can easily be added and serializiation the messages itself are separated. Of course, as for any pattern, this concept can (should) be extended and adjusted to your needs.


Saving a recommended web article from form in Rails controller

Your controller is very creative but its got some pretty big problems. In Rails controllers are notoriously hard to test and can quickly become very buggy if they contain too much logic. Skinny controllers are a vital part of good MVC code.

Any time your controller action has more than two possible code branches than you should stop and rethink it.

The Rails way of approaching this problem is nested routes and nested parameters.

Lets start out with the nested routes:

resources :collections, shallow: true do
  resources :recommendations
end

This would give us routes like:

                      Prefix Verb   URI Pattern                                               Controller#Action
   collection_recommendations GET    /collections/:collection_id/recommendations(.:format)     recommendations#index
                              POST   /collections/:collection_id/recommendations(.:format)     recommendations#create
new_collection_recommendation GET    /collections/:collection_id/recommendations/new(.:format) recommendations#new
          edit_recommendation GET    /recommendations/:id/edit(.:format)                       recommendations#edit
               recommendation GET    /recommendations/:id(.:format)                            recommendations#show
                              PATCH  /recommendations/:id(.:format)                            recommendations#update
                              PUT    /recommendations/:id(.:format)                            recommendations#update
                              DELETE /recommendations/:id(.:format)                            recommendations#destroy
                  collections GET    /collections(.:format)                                    collections#index
                              POST   /collections(.:format)                                    collections#create
               new_collection GET    /collections/new(.:format)                                collections#new
              edit_collection GET    /collections/:id/edit(.:format)                           collections#edit
                   collection GET    /collections/:id(.:format)                                collections#show
                              PATCH  /collections/:id(.:format)                                collections#update
                              PUT    /collections/:id(.:format)                                collections#update
                              DELETE /collections/:id(.:format)                                collections#destroy

So the user would create a brand new collection from /collections/new -
and POST to /collections.

but we want the user to be able to create a recommendation on the fly as well. So lets make so that we can pass recommendations into the collection.

So what we do is add accepts_nested_attributes_for to RecommendedCollection:

class RecommendedCollection < ActiveRecord::Base
  has_many :recommendations, class_name: 'RecommendedResource'
  accepts_nested_attributes_for :recommendations, reject_if: :all_blank?
end

So from our Collection controller we can create both the collection and the recommendation

class CollectionController < ApplicationController

  def new
    @collection = RecommendedCollection.new
    @collection.recommendations.build # create an empty recommendation for the form.
  end

  def create
    @collection = RecommendedCollection.create(collection_parameters)
    if @collection.persisted?
      redirect_to @collection
    else
      render :new, notice: 'Collection could not be created.'
    end
  end

  def collection_parameters
    params.require(:collection).allow(recommendation_attributes: [:title, :url])
  end
end

So now if we do POST /collection  collection: { recommendation_attributes: ['Test', 'http://www.example.com'] } we create a collection and a recommendation.

The form would look something like this:

<%= form_for(@ollection) do |f| %>
   <%= f.fields_for(:recommendations) do |nested_fields| %>
     <%= nested_fields.text_field :url %>
     <%= nested_fields.text_field :title %>
   <% end %>
<%= end %>

Later when other users or the same user wants to add more recommendations to a collection they would post to /collections/1/recommendations.


Listing prime numbers up to the given number

The first thing I'd suggest is break out code segments into functions.  This keeps your Main free of clutter and makes the flow easier to understand.

You don't mention which IDE you're using.  If it doesn't have the option for you to format your code according to acceptable guidelines, I would seriously consider changing programs.  There are several well established IDE's freely available.

Your, check for prime, algorithm, while naive, could do with some optimization.  Check for 0,1, and 2 separately.  If the number is bigger than 1 then add 2 to the list.  The loop should start at 3 and step by 2.  As was pointed out, all primes larger than 2 are odd.

There are much better algorithms for getting a list of prime numbers, not the least of which is the Sieve of Eratosthenes.  With this algorithm it is very easy to make a master list of primes then build the sublist that you want.


Table component for scrolling through lines of data

hide the overflow on the body when the mouse enters the component to stop the scroll event from moving the whole page instead of just the data in the component

Isn't that already the default behavior of scrollable divs? Well, except the page doesn't set overflow:hidden on itself. Once your cursor is in a scrollable area, scroll will transfer there. When it reaches the end, the page scroll will pick up the rest of your scroll (really apparent when answering in SE with a really tiny textarea).

So I believe you're preventing that "page picking up after the end" thing. If so, you don't need to disable scrolling for the component. Once you hover over it, just disable the page scroll and enable when you move out.

Now for your code, you're inconsistently doing the "egyptian" (collapsed, K&R) brackets. Well, the problem is the inconsistency, not the fact that you're using one or the other. Just choose one style and stick with it.

maxRow: Ember.computed('content', function () {
  return Ember.get(this, 'content.length');
}),

let TableComponent = Ember.Component.extend({
  tagName: 'table',
  layout: layout,
  ...

To make these checks easier, try configuring your IDE to tell you. I believe most IDEs/text editors have plugins for eslint, jshint, and jslint.


Beginner python solution to CSES "Permutations"

Your list slicing idea is a good one. You could simplify further by doing something
analogous with ranges, eliminating most of the need for intermediate variables
def beautiful_permutation(n):
    odd  = list(range(1, n + 1, 2))
    even = list(range(2, n + 1, 2))
    return even + odd

Your validator probably should check more things and can also be simplified by
taking advantage of abs(). Optionally, you could express the adjacent-number
check using all() and zip(). We're still looping over the numbers, but
just more concisely.
def check_solution(n, sol):
    return (
        # Must not be empty.
        sol and
        # Must cover all intergers 1 through N.
        set(range(1, n + 1)) == set(sol) and
        # No adjacent numbers with difference of 1.
        all(abs(a - b) != 1 for a, b in zip(sol, sol[1:]))
    )

One additional point. The method used to create the sequence nearly ensures
validity. By definition, the individual sub-lists (odd and even) will follow
the adjacent-number rule. The only way there can be a problem is at the
junction point where we glue them together. But our function could directly
validate the issue. If you were to add this and include a preliminary check for
bad or special inputs (0, 1, etc.), you would have a function that,
at least for practical purposes, is provably correct -- no need for a validator!?!
if odd and even and abs(even[-1] - odd[0]) != 1:
    return even + odd
else:
    return None


NumPy is just plain awesome! Now I can move 3X more octagons without any lag at all! And it greatly shortens the length of lines so I can use more descriptive names, too! Here's the NumPy version:

import pyglet
import numpy as np
from circle import octagon
from random import randrange

R = 50
SIZE = 800
COUNT = 333 # NO LAG! RUNS @ >60 FPS!
WIN = SIZE, SIZE, 'Camera', True, 'tool' # x, y, caption, resizable, style

def clr():
    return (randrange(256), randrange(256), randrange(256)) * 9

def coord():
    return randrange(SIZE)

win = pyglet.window.Window(*WIN, vsync=False) # to unlimit FPS
batch = pyglet.graphics.Batch()
shapes = [octagon(coord(), coord(), R, clr(), batch, None) for _ in range(COUNT)]
coords = np.array( [shape.vertices for shape in shapes], dtype=int)
fps = pyglet.clock.ClockDisplay()

@win.event
def on_draw():
    win.clear()
    batch.draw()
    fps.draw()

@win.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    global coords
    for i, shape in enumerate(shapes):
        coords[i][::2] += dx
        coords[i][1::2] += dy
        shape.vertices = tuple(coords[i])

def on_step(dt):
    pass
pyglet.clock.schedule(on_step)

pyglet.app.run()


Python decorator for optional arguments decorator

The code looks rather complicated. Instead of trying to understand it, I'd just like to point to NickC's answer to the linked SO question.

If I add **kwargs to his optional_arg_decorator like this...

def optional_arg_decorator(fn):
    def wrapped_decorator(*args, **kwargs):
        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
            return fn(args[0])

        else:
            def real_decorator(decoratee):
                return fn(decoratee, *args, **kwargs)

            return real_decorator

    return wrapped_decorator

...and adapt your decorators like this, I'm getting the same output from the test cases.

from functools import wraps

@optional_arg_decorator
def my_text_decorator(f, start_val="-=[", end_val="]=-"):
    @wraps(f)
    def wrapper(*args, **kwargs):
        return "".join([f.__name__, ' ', start_val,
                        f(*args, **kwargs), end_val])
    return wrapper

@optional_arg_decorator
def my_text_decorator2(f, start_val, end_val="]=-"):
    @wraps(f)
    def wrapper(*args, **kwargs):
        return "".join([f.__name__, ' ', start_val,
                        f(*args, **kwargs), end_val])
    return wrapper


C# Ping - Checking availability of hosts

It doesn't make sense to have the CancellationTokenSource private like you have now. Who is going to be able to cancel the operation? The user of your class can't access the source or provide their own token. The class doesn't offer any API to cancel.

Instead, you should alter the private bool IsOneOfTheHostsAvailable() method to accept a CancellationToken as input. You can then let the user care about creating a source and possibly cancelling the operation. Or, if you don't feel like offering the option to the user, you should just do away with the cancellation token as a whole. Right now it isn't doing anything.


A singly linked list implementation in C

Do not cast the result of malloc. If your code does #include <stdlib.h>, the cast is redundant. If it does not, the cast just masks the warning, which may lead to hard to find bugs.
Prefer sizeof(object) to sizeof(type). The latter leads to the double maintenance problem, in case the type is changed.
I strongly recommend to have a constructor-like function to create a node:

struct node * create_node(int num)
{
    struct node * node = malloc(sizeof(*node));
    node->value = num;
    node->next = NULL;
    return node;
}

It will spare you plenty of trouble when the definition of struct node changes.
You should get a warning that get doesn't always return a value (if you do not, enable all warnings, or change the compiler). It is a very serious warning, and in real life the code with such a problem leads to some dire consequences. You must return get(lst->next, pos); in a recursive clause.

The fact that your main printed expected values is an unlucky coincidence.

What to return in the IndexOutOfBound situation is a different matter. Consider returning an error code along with the value.
Calling length(lst) at each level of recursion degrades performance to quadratic.
As a side note, rather than testing for position < 0, consider passing a position as some unsigned type. size_t is the most obvious candidate.
Along the same line, a low level utility function such as get should refrain from printing anything.
I strongly advise agains recursion when an iterative solution is immediately available.


You code looks good and well formatted. There are only a few minor issues:

It seems that you have tried to check it with JSHint but there are some issues that JSHint reports about your code. In particular, semicolons and unused variables.
It is not clear when the character "\n" is required in messages, and when it is not. It looks like sometimes you just forgot it.
This one looks inconsistent. It looks like there is an error:

console.log('The backup file has been saved to your Dropbox: %s', '');

This actually a bad pattern:

if (err) {
    return failWithMySQLError(err);
}

it shortens a code a little but adds impression that the value of the function is important, while it is not.
else is redundant here:

if (err) {
    failWithDropboxError(err);
} else {

and as you see, the long lines complicate the code review.


Creating a function when user clicks on element to toggle another element

I know you're trying to be flexible here, but your approach comes at a cost: The API isn't understandable. I can see you're trying to toggle the second parameter element with the first parameter as the toggle,  But I don't understand exactly how the third or fourth works, if it's even needed. It's also a weird convention.

Reflect on these three things here:

The point of programming is having stuff done easier.
The point of a programming language is to do programming in that's understandable to humans.
The point of an API is to "lift" (abstract) the programming language.

Fail on one of those, and the rest before it breaks apart (and things like the great flood, alien invasions, world war 3 happen). So before you design an API, or even just a function, think about the users/developers using it. It might be you in the distant future.

Now off to your code. Seeing you're using jQuery, a similar feat could have been done through this piece of code. I do notice you said "elements that can't be easily targeted. For example, they don't have an #id." - jQuery still can target them using your standard CSS selectors (here's a few to remember), and some custom jQuery selectors (which I think is a superset of CSS selectors, if I'm not mistaken).

. The :eq() part is optional, but it does what you need, select specific indices.

// Assuming delegation for future elements
$(document).on('click','li:eq(0)',function(){
  $('div:eq(0)').toggle();
});

It's as simple as "Get the first of all <li> and toggle the first of all <div>". Simple enough. But what if you wanted your own simple function for it and not some jQuery mashup that is copy-paste bait? Something like this could be done too:

;(function ($) {
  $.fn.customToggle = function (trigger, target, event) {
    // Let's add a twist, custom functions. Assume click if not defined.
    event = event || 'click';
    this.on(event, trigger, function () {
      $(target).toggle();
    });
  }
}(jQuery));

// Still, future-proof, let's support future elements
$(document).customToggle('li:eq(0)', 'div:eq(0)');
$(document).customToggle('li:eq(1)', 'div:eq(1)','mouseover');

There you have it. Now you'd wonder "That's not any different from my code" - exactly. It's the same. However, there's one important bit I changed - it's the way I selected the elements and indices. I used CSS selectors - which every developer who came across CSS or jQuery should already know.

Here are other suggestions on how you could structure the API:

// Chained:
$(document)
  .customToggle('li:eq(0)', 'div:eq(0)')
  .customToggle('li:eq(2)', 'div:eq(4)')
  .customToggle('li:eq(3)', 'div:eq(9)')

// Map
$(document).customToggle({
  'li:eq(0)' : 'div:eq(0)',
  'li:eq(2)' : 'div:eq(4)',
  'li:eq(3)' : 'div:eq(9)'
});


Object properties.

If you overwrite the prototype you will lose existing properties.

There are other solutions using the class syntax, but it is important to note the following.

  JavaScript classes, introduced in ECMAScript 2015, are primarily
  syntactical sugar over JavaScript's existing prototype-based
  inheritance. The class syntax does not introduce a new object-oriented
  inheritance model to JavaScript.

from MDN Classes

Using class has some major problems, and in my opinion should be avoided as the same and better can be done using standard syntax for objects.

A word on code.

You don't need to add return to a function. Its automatic.
Use function shorthand when adding functions to objects.
Don't mix naming styles. You have snake_case and camelCase.

Apply that to

const held ={stateName:"Held",
  close: function(){
    this.changeState(closed);
  },
  reopen: function(){
    return;
  },
  place_hold: function(){
    return;
  },
  remove_hold: function(){
    this.changeState(open);
  }
}

Becomes

const held = {
  stateName: "Held",
  close() {              // function shorthand
    this.changeState(closed);
  },
  reopen() {},           // return implied Same as return undefined;
  placeHold() {},        // camelCase
  removeHold() {
    this.changeState(open);
  }
};  // objects have semicolons..

Object properties.

When you are creating objects with dynamic properties you can assign properties directly to the object using Object.assign(obj, properties) This has some performance benefits as well.

The following is an example of an instanceable account state machine using object assign to assign the the state.

const Account = (() => {
    const actions = {
        close() { this.transition(states.closed) },
        hold()  { this.transition(states.held) },
        open()  { this.transition(states.open) },
    };
    const nulls = {close(){ }, hold(){ }, open(){ }};
    const states = {
        open : {
            state: "Open",
            close: actions.close,
            hold: actions.hold,
        },
        held : {
            state: "Held",
            close: actions.close,
            open: actions.open,
        },
        closed : {
            state: "Closed",
            open: actions.open,
        }
    };
    return function(){
        const account = {
            ...states.closed,  // default State
            balance : 0,
            transition(state) { Object.assign(account, nulls, state) },
            statement() { console.log(account) },
        };
        return account;
    };
})();

To use

const foo = Account();
// or
const foo = new Account();

foo.close();
foo.open();
foo.hold();
foo.statement();


Displaying current date and time using JavaScript and HTML time tag

Semantic markup is less important for dynamically generated HTML than it is for server-generated HTML, but it is a laudable goal nonetheless.  If you're going to produce a datetime attribute for machine consumption, then I suggest using T as the delimiter between the date and time, as recommended by ISO 8601.

Since you frequently need to zero-pad a number, you should define a function for it.

For clarity, you should avoid excessively long lines of code.  In addition, I think it would be a good idea to define separate functions for each of the datetime formats.

I would eliminate the hourap array, since it's not that difficult to achieve the same effect programmatically.

The timeDiv variable refers to a <time> element, not a <div>, and should therefore be renamed.

The semicolon after the final if block is unusual.

var MONTH_NAME = ['January', 'Febuary', 'March', 'April', 'May', 'June',
                  'July', 'August', 'September', 'October', 'November', 'December'];
function showTime() {
    function twoDigit(n) {
        return ('0' + n).slice(-2);
    }
    function iso8601(date) {
        return date.getFullYear() +
               '-' + twoDigit(1 + date.getMonth()) +
               '-' + twoDigit(date.getDate()) +
               'T' + twoDigit(date.getHours()) +
               ':' + twoDigit(date.getMinutes());
    }
    function en_US(date) {
        var h = date.getHours() % 12;
        return MONTH_NAME[date.getMonth()] +
               ' '  + date.getDate() +
               ', ' + date.getFullYear() +
               '<br />' + (h == 0 ? 12 : h) +
               ':'  + twoDigit(date.getMinutes()) +
               ' ' + (date.getHours() < 12 ? 'am' : 'pm');
    }

    var timeEl = document.getElementById('time');
    if (timeEl !== null) {
        var now = new Date();
        timeEl.innerHTML = en_US(now);
        timeDiv.setAttribute('datetime', iso8601(now));
    }
};
setInterval(showTime, 1000);
<time id="time"></time>


Anchoring an element to the browser's vertical scrollbar

What is wrong with:

    ...

This is the element

css:

#myfloatingElement
{
    position: fixed;
    right: 0;
    top: 50%;
}


Ruby Fibonacci(n) recursive computation optimized with reflection

considering that this is Code Review, I have to say that you probably don't want to use an instance variable. You expose the internal data, and any user could destroy the workings of your method inadvertently. In Ruby 1.9, Ruby added a very interesting feature for just these types of situations that involve infinite sequences. It's called a Fiber.

It's true that Fibers aren't perfect for situations where you have to go backwards in the sequence in addition to forward.

Another option for this is to put the data in a module:

module Fibonacci
  @fib=[0,1,1]
  def self.fib_array(n)
    @fib[n] ||= fib_array(n-2) + fib_array(n-1)
  end
end

And use it like so:

Fibonacci.fib_array(42)


Project Euler #8 - Largest product in a series


Correct implementation for background task execution in web application?

you needn't call super.init(); according to docs, it is a NOP . but as a rule calling initializers of some superclass at the beginning of the overriding method will save you headache in the future.

backgroundExecutor shouldn't be static. suppose you have multiple instances of this servlet in an application. destroying any one of those servlets shuts down the last created updater. what happens to the rest?


It's not clear how many digits the output is supposed to have.  For midnight, you output "00", but for 1 am to 9 am, you echo the hour, which may or may not have a leading zero.

Taking the last two characters as the suffix, then doing time.replace(suffix, ""), feels like a fragile operation.  Consider treating this as a pattern-matching exercise instead, and using a regular expression.  Since the pattern also describes the valid input strings, you get input validation for free.

private static final Pattern TIME12 = Pattern.compile(
    "(?<h>0?\\d|11|12):(?<ms>[0-5]\\d:[0-6]\\d)\\s*(?<ampm>[AP]M)"
);

public static String time24(String time12) {
    Matcher m = TIME12.matcher(time12);
    if (!m.matches()) throw new IllegalArgumentException();

    int h = "12".equals(m.group("h")) ? 0 : Integer.parseInt(m.group("h"));
    if ("PM".equals(m.group("ampm"))) h += 12;
    return String.format("%02d:%s", h, m.group("ms"));
}


Grep for pattern recursive and disable file

Bash idiom for looping over searchfiles is

for file in $searchfiles; do
    process "$file"

Invoking awk just to print a field looks like an overkill. Consider

read -d : str rest <<< "$file"


Program for entering 1000 random numbers into two different databases, one for odd numbers and one for even

Structure your code

Name your variables appropriately! It is not a good idea to have the connections called con and conn. Likewise ps and ps3 are not good names for your prepared statements. It will confuse you when trying to debug this.
Make a method that inserts a value into a database.
Do not catch Exception. Make sure you know what exception you catch and why. Right now you declare your main to throw exceptions, but I don't think it really does.

Prepared statements are reusable

You prepare a statement to let the database optimize for it. It takes a bit of time, but it saves time when you use it. What you do, is you prepare the statement inside your loop, making it a lot slower. Move the preparation of your statement

PreparedStatement ps = con.prepareStatement("insert into try values (?)");

outside your loop. This will make your program run faster.

Random is reusable

You create a new instance of Random on every rotation of the loop. Move this outside the loop - it will make your code run faster.

Remove unnecessary things

Your code is littered with statements executing expensive methods to no use.

What does

Class.forName("com.mysql.jdbc.Driver");

do?

What is the purpose of

ps.addBatch();
breakcon = breakcon + 1;
if (breakcon % 500 == 0 || breakcon == val)
  ps.executeBatch();

What is the purpose of oddcount and evencount?


Find the longest connect cells region per color

Looks fine overall, but there are a few oddities here and there, and there are some opportunities for significant performance improvements:

Since you're going to visit every node in the given int[,] graph you might as well use a bool[,] instead of a Dictionary<int, HashSet<Tuple<int, int>>>. I see no reason to group visited nodes per color, because you're already keeping track of the largest group separately. For me, this made things about 6x faster.
Using an 'old-style' tuple as return type isn't very descriptive. Consider using value-tuples instead: public static (int color, int count) FindLongestConnectedColor().
In GetConnectedRegionLength, I'd combine directionRow and directionColumn into a single array of (int x, int y) tuples. Not a list - it's not going to be resized. This also provides a small performance increase. Also consider storing it in a static field, so you only need to initialize the array once, for yet another performance increase.
q1 and q2 are rather undescriptive names - openNodes would be better. It's also unclear why there are two queues instead of one (you mentioned the reason in your post, but it's not documented in the code). About that reason - Queue<T> is generic, so a Queue<Tuple<int, int>> or Queue<(int, int)> is not going to involve boxing. Yes, you'll need to create tuple objects, but you no longer need to call Enqueue and Dequeue twice. Performance should be more or less the same. When in doubt, measure!
connectedCellsCount can be initialized to 1 directly.
while (q1.Count > 0) is faster than while (q1.Any()).
a is rather uncommon as a counter variable name - I'd stick to i.
Personally I'm not a fan of putting single if-body statements on the same line: if (...) continue;. It makes these 'early-outs' more difficult to spot when scanning code.
The various if/continue statements can be combined into a single if.

As for breadth-first versus depth-first, I guess I don't really see the point here: the only difference is the order in which you visit nodes, but you still have to visit all of them. Either way, instead of recursion you can also combine iterative code with a stack data-structure. Similar to your current solution, just with a stack instead of a queue.


I believe you're looking for String.IsNullOrEmpty.

// test for null or empty string
if (!String.IsNullOrEmpty(password) {
}

// -- OR --

// If the hasher call just can't accept null values, you can specify
// an empty string to fall back on like so:
(...LINQ...).FirstOrDefault(String.Empty);

I would also probably refactor this a bit:

public void CheckAssistantsPassword()
{
  using (DbClassesDataContext myDb = new DbClassesDataContext(dbPath))
  {
    var password = (from userAccounts in myDb.Assistants
                    where userAccounts.Ass_UserName == txtUserName.Text
                    select userAccounts.Ass_Password).FirstOrDefault(String.Empty);

    var hasher = new Hasher { SaltSize = 16 };
    if (hasher.CompareStringToHash(txtPassword.Text, password))
    {
      // Success
    }
    else
    {
      // Invalid password
    }
  }
}

Optionally you can place error checking on your context making sure you can establish a connection. Also, I recommend placing a using() block around your context to free it up after you're done with it.