Calculating the number of prime numbers to solve the puzzle

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;

Clean up those imports. Importing everything in a package is a bad idea, as it might easily lead to conflicts between same named classes. Also it is hard to see what is actually used.

You ain't got a package defined, define one.

class Solution{

That's a not very good class name. Classes should be named after what purpose they serve, or what purpose the methods contained within the class serve.

public static int[] b = new int[217287];

Here is the ultimate rule for variable naming:

  You're only entitled to use one character variable names if you're dealing with dimensions (x, y, z). Second best is you're allowed to use one character variable names in simple for loops (i, j, k)...but the last point is up for debate and it should not be the case.

And here is a simple guide for naming variables:

  Name variables after what they contain. You're not allowed to use one character variables except when dealing with dimensions.

Why is it so important to name variables after what they do? Well, quick, tell me what this code does:
 if (b[n] != 0).

for(int x=0;x<t;x++){

This is even worse. x is normally only used for the dimension, so unless you're looping over the x dimension of something here, this variable should be called different and according to what it does.

for(int i=0;i<=n;i++){
    a[i] = -1;         //initialise all value in the array as -1.
}

Only comment things that are not obvious from the code. In this case I can see that the array is initialized to -1...or I could see it if the variables would have fitting names:

for (int index = 0; index < a.length; index++) {
    a[index] = -1;
}

Note that a is still not a good name. Also what I do not see from the code at this point is why it is initialized to that value. So if to comment something, then the why is interesting.

if(n<4)
    System.out.println("0"); // if n<4, number of possibilities =1. So no prime number before that is 0.
else{

You should not omit braces from ifs and fors, even one line once. It can be very confusing in the long run.

else{
for(int j=0;j<4;j++){
    a[j] = 1;          //till n<=3, number of possiblities = 1. These will work as base cases.
}
a[4] = 2;             //for n=4, possibilities = 2. This is a base case.
int num1 = recursive(a,n);          // storing number of possibilities in num1.
int num2 = prime(num1);    //calling to calculate number of prime numbers before or equal to num1.
System.out.println(num2);
}

Why are your else branches not indented?

public static int recursive(int[] a, int n){

That's another not very good name. Functions should be verbs, not adjectives. They have a function, not a state, and the name should mirror that function.

You have no JavaDoc in there, fix that.

Consider using a code formatter, and then consider using more blank lines and more whitespace to make the code easier readable.


Production-ready comparison between byte-array and ByteBuffer

Minor issues in MD_GetHsmInfo()

valueLen = strlen(str); serves no purpose below as the value assigned to valueLen is not used.

int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int valueLen) {
    ...
    valueLen = strlen(str);
    return 0;
}

Perhaps

int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int *valueLen) {
    ...
    *valueLen = strlen(str);
    return 0;
}

or

int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, size_t *valueLen) {

Cast not needed

int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int valueLen) {
  ...
  // jbyte *jb = (jbyte*)pValue;
  jbyte *jb = pValue;


Model validation from within the Service Layer

It feels somewhat awkward to answer a question this old, but there are some things that can be done.

First, I want to comment on the naming, simply from the fact that I'm currently building an ASP.NET app which is very large, and I've learned through the process that the ViewModel name becomes cumbersome, and is partially a lie. I've begun to name my 'View Models' as 'DTOs' instead, that is: Data-Transfer Object.

This has begun to make my code much more clear, as it's now obvious that the DTO can be a two-way object: data can be fed to it from the back-end or from the UI.

Regarding the service-layer handling database access: this is a good approach, I'll tell you that a lot of my code in this project I've mentioned previously is in the controller, and it's cumbersome. What I would change is reject the idea of needing to create a dict (or pass it to the .Merge method) controller-side, and do one of two things:

Create a BaseController that will handle adding the validation errors to the ModelState itself, though this can become complicated.
Pass the Controller to the method doing the validation, and allow it to add the errors to the ModelState.

It's been a while since I've touched ASP.NET MVC 3, but in 4 and 5 you can directly manipulate the ModelStateDictionary, and use .Add or .AddModelError. I do this on various validation methods to remove that responsibility from the controller, and reduce the call to:

[Authorize(Roles = "ADMIN")]
[HttpPost]
public ActionResult Create(PostEditViewModel postEditViewModel)
{
    BlogPost post = new BlogPost();

    postEditViewModel.MapTo(post);
    _postService.CreatePost(post, this);

    if (!ModelState.IsValid)
        return View();

    return RedirectToAction("Index", "Home");
}

Another pointer: I would recommend converting your Roles attribute parameters to constants, I've found that it becomes unpleasant to change the name of a Role later, if you need to. I actually have a Constants.Roles class that has each role string associated to a type, so that if I have to change the name from Controllers to Inventory, it's right there, and my code can still reference the InventoryControllers constant. (You can also use the constants with XML-docs to make things more descriptive in the future.)

You have:

BlogPost post = new BlogPost();

But then:

var dic = _postService.CreatePost(post);

Be consistent. If you're using var in one location, use it in the others. I used to be anti-var period because I felt it made my code look less organized, but to be honest, it helps align all the variable names to the fifth textual column (counting the space), so it's easy to identify where something is declared. (Of course, with the highlighting Visual Studio does it's not necessary, and F12 is a wonderful tool, but it's still helpful at times.)

It also allows you to ignore what type it is when declaring. I'd have to type BlogPost out in one of those two places on that line (though one can argue that with intellisense when you type BlogPost thing = new it automatically suggests BlogPost() to finish it) so I don't mind changing the manual typing from BlogPost post = to var post = new BlogPost();, personally I type faster that way anyway.


Wrapper function to do polynomial fits with gsl

One issue is numerical stability. Although the GSL uses stable routines, the problem of fitting a polynomial in the monomial basis is so ill-conditioned (especially for large ranges in x and large (eg 50) degree), that you risk getting significant errors. Unless you really, really need the coefficients in this basis then I think you should use another basis, for example Legendre or Chebycheff polynomials. This will mean that any code that uses the coefficients will need to know how to do so, but the evaluation is in fact almost as efficient as evaluation in the polynomial basis.


Getting the current IP from the command line

I would use a different service that provides output in a format that is good for tools (not humans (html is for displaying for humans)).

Hit this url:

https://ifconfig.co/json

You're output looks like this:

{
  "ip": "154.140.296.288",
  "ip_decimal": 926648668,
  "country": "United States",
  "city": "Seattle",
  "hostname": "154-140-296-288.Bob.com"
}

Which is obviously json which can be parsed using the jq tool.

> curl -s https://ifconfig.co/json  | jq .ip -r
154.140.296.188


Haskell Parsec parser of Verilog-style number literals

Let's start with your imports. You should get rid of those you don't need, e.g. System.IO, import Data.Either.Extra (fromRight). Next, you shouldn't mix integral and floating point calculations, unless you're fine with imprecise results. For example, integerLog will give the wrong answer around 1024:

ghci> integerLog (2^1023)
1023
ghci> integerLog (2^1024)
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216

Next, record field names are functions:

data Number = Number {val::Integer, len:: BitSize} deriving Show

This gives you two functions,

val :: Number -> Integer
len :: Number -> Integer

Unless you're fine with those functions at global namespace, it's usually a better idea to either a) use a complete name, e.g. value, bitLength, or b) prefix/suffix them with the type's name, e.g. numberValue or lenNumber. The story slightly changes if you want to use lenses and Template Haskell, but that's for another post.

What follows afterwards are several top-level functions without type signature, which is considered bad style:

readBin = readInt 2 (`elem` "01") digitToInt

-- conversions String -> Number
hexToInteger x = fst $ readHex x !! 0 :: Integer
octToInteger x = fst $ readOct x !! 0 :: Integer
binToInteger x = fst $ readBin x !! 0 :: Integer

All those functions are partial, e.g.

ghci> hexToInteger "Hello"
*** Exception: Prelude.!!: index too large

Your use prevents this kind of error, since you're using ithexToInteger only on valid combinations, but you shouldn't export them either. That's not really an issue here since you've wrote a Main (main) module, but you should keep that in mind.

However, those functions would be a lot nicer with the appropriate type:

convertWith :: ReadS Integer -> String -> Maybe Integer
convertWith fn xs = case fn xs of
                      [(n,"")] -> Just n
                      _        -> Nothing

hexToInteger, octToInteger, binToInteger :: String -> Maybe Integer
hexToInteger = convertWith readHex
octToInteger = convertWith readOct
binToInteger = convertWith (readInt 2 (`elem` "01") digitToInt)

In this case we've dumped the plumbing into convertWith, added type signatures and made the functions non-partial. Now, let's step back to your smart-constructor:

-- |makeNumber is a safe constructor of an Either String Number
makeNumber :: Integer -> Integer -> (Either String Number)
makeNumber v l
  | v < 0     = Left "makeNumber: Negative values not allowed in Number"
  | size > l  = Left $ "makeNumber: Value " ++ show v ++ " is "
    ++ show size ++ " bits long, should be at most " ++ show l ++ " bits"
  | size <= 0 = Left $ "makeNumber: Size can't be negative or zero"
  | otherwise = Right $ Number v l
  where size = numberSize v

While that's better than just a Maybe Number, it's still not optimal if you have an application that's creating those numbers. Since sum types aren't expensive to write, let's use one:

data NumberError = ENegative
                 | ENegativeSize
                 | EBitOverflow Integer Integer
 deriving (Show, Eq)

That way you can separate the formatting from the number handling:

makeNumber :: Integer -> BitSize -> (Either NumberError Number)
makeNumber v l
  | v < 0     = Left $ ENegative
  | size > l  = Left $ EBitOverflow v l
  | size <= 0 = Left $ ENegativeSize
  | otherwise = Right $ Number v l
  where size = numberSize v

You could also provide some functions, e.g.

eNegative    :: Either NumberError a
eBitOverflow :: Integer -> BitSize -> Either NumberError a

to ease the use of those, but that's an overkill here.

Speaking of overkills, did you notice the BitSize above? Many of your functions use Integer -> Integer -> …. But what do those Integer's mean? Which one is the value? Which one is the bitsize? And is Integer as bitsize really a good idea?

Therefore, try to add some documentation at the type level, even if it isn't a new type:

type BitSize = Int

Now, let's have a look at the parser:

-- |parse Verilog-style numbers <size>'<radix>value
parseNumber :: Parser Number
parseNumber = do
  size <- option "32" (many1 digit)
  char '\''
  radix <- option 'd' $ oneOf "hH" <|> oneOf "dD" <|> oneOf "oO" <|> oneOf "bB"
  let (thisDigit, convert_digits) =
        case toLower radix of
          'h' -> (hexDigit, hexToInteger)
          'o' -> (octDigit, octToInteger)
          'd' -> (digit   , read)
          'b' -> (binDigit, binToInteger)
          _  ->  error "parseNumber: Internal error"
  val <- many1 thisDigit
  let size' = read size :: Integer
      val' = convert_digits val :: Integer
      num = makeNumber val' size'
    in
    either fail return num

This is well done, except for two minor quirks: you can collect all oneOf <prefix> parsers into a single one:

oneOf "hHdDoObB"

and your use of error, which makes this parser partial again. Instead, you could have used

  (thisDigit, convert_digits) <-
        case toLower radix of
          'h' -> return (hexDigit, hexToInteger)
          'o' -> return (octDigit, octToInteger)
          'd' -> return (digit   , read)
          'b' -> return (binDigit, binToInteger)
          _  ->  fail "parseNumber: Internal error"

Note that parseNumber slightly changes if you use String -> Maybe Integer from above (you should use readMaybe instead of read in this case). Also note that parseNumber isn't a good name in this case, it indicates that you're parsing, but you only define a parser. numberParser is usually slightly better.

Also, make sure that your variables follow the same naming convention. convert_digits kind of falls of the rest of your names.

Last but not least, it's strange that you get your numbers as arguments, e.g.

$ ./MyApplication 32\'b100101001

Usually, you take those values from stdin and print them to stdout. The interact function will come in handy.

Bonus content: Separated concerns and an applicative Parser

So, now that we had a look at your code, how would I write it? I would probably introduce a function that takes the bitsize, the prefix, and the rest:

type BitSize      = Word
data NumberFormat = Bin | Oct | Dec | Hex

makeNumber :: BitSize -> NumberFormat -> String -> Either NumberError Number
makeNumber l d xs = do
  num <- readWith d xs
  case num of
   _ | num  < 0 -> eNegative
   _ | bits > l -> eBitOverflow num l
   _            -> return $ Number num l
  where num  = readWith d xs
        bits = fromIntegral $ numberSize num

readWith :: NumberFormat -> String -> Either NumberError Number
readWith d xs = maybeToEither $ case d of
                   Bin -> binToInteger xs
                   Oct -> octToInteger xs
                   Dec -> readMaybe    xs
                   Hex -> hexToInteger xs

Essentially that's still your code, only put into two functions and using the NumberError above. This makes it possible to later test the parts of your previously large parseNumber. Note that all those functions are rather small, and do only one thing (and one thing well).

Now what's left is the Parser. Instead of the previous Monad one, we can now easily use an Applicative one. For this, we provide three additional parsers that parse the sub-expressions <bits>'<format><digits>:

bitSizeParser :: Parser BitSize
bitSizeParser = option 32 $ fmap read $ many1 digits
-- read is fine here, since we use only digits

numberFormatParser :: Parser NumberFormat
numberFormatParser = option Dec $ fmap toFormat $ oneOf "hHoOdDbB"
  where toFormat c = case toLower c of
          'h' -> Hex
          'b' -> Bin
          'd' -> Dec
          'o' -> Oct

digitsParser :: Parser String
digitsParser = many1 $ oneOf "0123456789abcdef"

Now what's left is using those three parsers together and feeding them into makeNumber:

 import Control.Applicative ((<$>), (<*>)) -- not needed in GHC 7.10 or higher

numberParser' :: Parser (Either NumberError Number)
numberParser' =
  makeNumber <$> bitSizeParser <*> numberFormatParser <*> digitsParser

numberParser :: Parser Number
numberParser = numberParser' >>= either fail return

Note that the parts of our parser are now reasonably dumb. They only get things, i.e. <bits>'<format><digits>. The logic is now in makeNumber, which can be used without actually parsing, which might be handy if you want to check values from a database or similar.


Submitting the current webpage to a bookmarking site

First of all, void is an operator, not a function. The parentheses are extraneous; it should be written as void 0.

href="#" should be avoided for the reasons given in the answer you linked; people will forget to cancel the event and the page will jump to the top when users click the link, or worse, if the page uses a base tag, the page will navigate somewhere else.

Most people will tell you to avoid putting JavaScript in tag attributes at all, instead binding events to the element later on, once the page has been loaded, or binding the event to a parent element and delegating.

If you're going to use an inline onclick attribute anyway, and there's nothing appropriate to put in the href attribute, I'd consider not making it a link at all. Make it a button or some other kind of element, possibly styled to look like a hyperlink.

As a final note, GET requests should be safe and idempotent, meaning following a link or visiting a URL should not cause changes on your server / in your database. https://www.example.com/add?... looks suspiciously like it breaks that rule; you may be in a world of trouble if spiders start crawling those links. Making a POST request, for example by submitting a form, would be the proper way to handle this.


break and span
When we try to split a string in Haskell, we're a little bit out of luck if we only use the trusty Prelude and base. Handy functions like split or splitOn  are in the adaptly named split package, and parser combinators are completely other beasts and an oribtal (heh) laser cannon on this problem.
However, there are two functions that provide almost exactly what parseOrbit is trying to achieve: splitting a string on a single character:
span, break :: (a -> Bool) -> [a] -> ([a], [a])
span  f xs = (takeWhile f xs, dropWhile f xs)
break f xs = span (not . f)

We can simplify parseOrbit therefore to
parseOrbit :: String -> Orbit
parseOrbit s = let (a, _:b) = break (==')') s in (a, b)

However, you seem to prefer where, so let's use a where clause instead:
parseOrbit :: String -> Orbit
parseOrbit s = (a, b)
    where (a, _:b) = break (==')') s

Type signatures in where clauses
As we have seen above, (a, _:b) had no type signature. Type signatures in where clasues are usually omitted. There is some controversy about that, however there are some things to keep in mind:

GHC never warns about missing type signatures in where clauses
functions with type parameters cannot have a type without ScopedTypeSignatures (see this SO question for an example)
a change in the top level type signature might need a lot of changes in where clauses
if a function is complex enough to need a type, it might be reasonable to promote it into a top-level function. That way it can also be tested.

I personally therefore omit type signatures in where clauses (ST shenengians aside).


Path from the root to a given node in binary tree

Step 1: use an IDE to reformat this nicely

Step 2: remove pointless comments

For example:

// if left of top is not null, push to stack.
// Check if the push values is equla to the required key
// If it is the require element break
if (topNodeLeft != null) {
    nodeStack.push(topNodeLeft);
    if (topNodeLeft.value == key)
        break;
}

The comment explained in English exactly what the code does. This is pointless.
On closer look, pretty much all the comments in this code are pointless.

Step 3: rename variables to more readable names

For example:

lnode -> left
rnode -> right

Step 4: let your IDE guide you

Pay attention to the warnings and try to fix them.
For example IntelliJ tells this:

The variable temp is never used: delete it
The Node topNode = rootNode; initialization is pointless, skip the initialization

Step 5: remove unnecessary elements

Look at every variable with suspicion. What's the purpose of topLeftNode?
After the renaming above, we have this line:

        topNodeLeft = topNode.left;

Which doesn't make a whole lot of sense. Can't we use just topNode.left ? Yes we can.

Why is topNode declared outside of the while loop when it is only used inside the loop, and assigned on the first line of the loop?
It's better to declare it inside:

    while (true) {
        Node topNode = nodeStack.peek();

Step 6: look for bugs in simple (degenerate) cases

The method crashes with EmptyStackException if the tree has only one node.

Same thing if the tree has only two nodes with the child in left position.

While fixing these bugs, you might find more opportunities to improve. Give it a try.

With the above suggestions, the code becomes this:

public void findPathFromRoot(Node rootNode, int key) {
    Stack<Node> nodeStack = new Stack<>();
    nodeStack.push(rootNode);
    boolean present = true;

    Node topNodeRight;

    while (true) {
        Node topNode = nodeStack.peek();
        topNodeRight = topNode.right;

        if (topNode.left != null) {
            nodeStack.push(topNode.left);
            if (topNode.left.value == key) {
                break;
            }
        } else if (topNodeRight != null) {
            nodeStack.push(topNodeRight);
            if (topNodeRight.value == key) {
                break;
            }
        } else {
            Node lastPoppedNode;

            do {
                lastPoppedNode = nodeStack.pop();
                topNode = nodeStack.peek();
            } while (topNode.right == null);

            topNodeRight = topNode.right;

            nodeStack.push(topNodeRight);

            if (topNodeRight.value == key) {
                break;
            }

            if (lastPoppedNode == topNodeRight) {
                present = false;
                break;
            }
        }
    }

    if (present) {
        for (Node tempNode : nodeStack) {
            System.out.println(tempNode.value);
        }
    } else {
        System.out.println("Element is not present in the tree");
    }
}

Step 7: Stop and think

What algorithm are you actually trying to implement here?
The top answer on the question you linked suggests using pre-order traversal.
That's a good suggestion that will work, though it won't be the fastest for all possible trees.
I suggest to implement that algorithm first.


Checking CSS code for best practices when mimicking

Here is my CSS

Well, no, actually. That's your HTML - it just happens to have some style attributes. Which it shouldn't have.

So step one, separate CSS and HTML. Use a <style> element in the <head> element, or better yet, include the CSS from a separate file. Don't inline your styling.

But for experiment purposes, you could try re-making your code as a jsfiddle or jsbin (both for your own sake, and to make it easier for reviewers later). Put HTML in the HTML panel, and CSS in the CSS panel, and play around with it.

And you should be using more semantic (i.e. meaningful) markup. You have a lot of div elements, but a div is a purposefully meaningless element used mostly for grouping other, more specific, elements.

The point is that when just reading the HTML, I can't tell what it represents. It could be anything since it's almost all div elements. Yet in the picture I see things that should probably be links or buttons, headings or spans, and maybe forms and images.

Here's an analogy to illustrate the idea of "semantic markup": Imagine for a moment that you're writing a book: the HTML elements form your outline. Right now, that outline would say:

Text
Text
Text
Text

Ok, sure, a book consists of text, but that's not a very useful outline.

A more useful book outline would say something like

Title
Introduction
Main body (likely divided into chapters or sections)
Summary and conclusion

That's what HTML is meant to do: Mark up information so as to reveal and codify its structure. Hence, the tags you use matter a great deal. And it makes it easier to apply CSS, since you've now grouped content in a logical manner. You can style things based on what they are; headings, paragraphs, images, etc.. You want all your links to be red? Just change the style for a elements, and you're done. The HTML stays the same, since the links are still links - the CSS just makes them look different, but doesn't (shouldn't) change their meaning.

That said, there of course aren't pre-existing elements for everything you can think of, and often you want some headings to look one way, and other to look a different way, even though they're all headings. That's when class names and sometimes IDs come in, since they allow you to further specify things.

When I look at that first image, I see a structure (outline) like

div.dialog
  header
    img.thumbnail
    h1
    h2 (update: an h2 isn't really correct here, see comments)

  div.body (maybe it's actually an image?)

  footer
    p
    div.actions
      a.favorite
      a.share
    form
      button
      button

I've given the containing element a dialog class, because it looks sort of like a dialog box to me. And yes, it's a div because there's no HTML element that captures the idea of a "dialog". That's when div comes in handy, since you can apply your own meaning (semantics) to it using an ID and/or a class name.

But it might not be a dialog box; it might be a cell in a grid view. In that case the class name should reflect that and be called grid-cell or something (update: actually, no it probably shouldn't - see comments). And perhaps the element should be an article. Again, pick an element and, if necessary, an ID and/or class name to describe what something is (not how it looks, or how it behaves).

Now, I'm not saying that the structure above is correct (as you can see, a few things have already been brought up in the comments), but that's how it mapped out in my head. If I were to start actually coding it, I'd probably end up changing a bunch of things.

For instance, footer probably isn't quite the right element to use, since it really contains more important stuff. Yet is it the "body" then? I don't know, but you've got to start somewhere, and then iterate, iterate until the CSS and the HTML each look clean and semantic separately, and together produce the desired result.

I know I haven't actually tackled the styling you've written, but that's because I find that less important than getting the overall approach right first.


User model with validation, delegates, and carrierwave upload mounter

A partial (an really short) answer:

for User.active method you have the following:

system = 0 or system is null

I think you should change the condition order to

system is null or system = 0

This because when (and depending of dbms) the database compare null with a value (system = 0 could be null = 0) it can invalidate the condition.


PEP 8

There is a generally accepted style for Python known as PEP 8. Most notably camelCase functions/methods should become snake_case. There are some other issues with stylistic conventions, I would give the document I linked to an overview.

Main Function

I would advise you add a main function to your program. The main reason being: If I want to use the functions from your script, when I import your script I probably don't want to actually run your program, just use generateSolution and isSafe. So:

N = int(input())
startCol = 0
board = [[0 for i in range(N)] for j in range(N)]
# print(board)

if generateSolution(board, startCol) == False:
    print("No Solution Exists")
else:
    print("Solution exists")
    print(board)

Becomes:

def main():
    N = int(input())
    startCol = 0
    board = [[0 for i in range(N)] for j in range(N)]

    if generateSolution(board, startCol) == False:
        print("No Solution Exists")
    else:
        print("Solution exists")
        print(board)

if __name__ == '__main__':
    main()

Avoid global

You should almost always not use the global keyword. In this case: just pass N into your generateSolution function, i.e. generate_solution(board, col, N).

Naming

I am not entirely sure how your code works (I am, ashamedly, unfamiliar with the N-Queen problem). I assume N refers to the number of queens? I would recommend that you call it queen_count or something of the sort. In addition, generate_solution is rather unspecific. I would call it (possibly) n_queen_solvable.

Does generate_solution actually do that?

I mentioned changing it to the name n_queen_solvable because you have return a truth value. I would expect a function like that to actually give me a configuration, not answer whether a solution exists or not. You may want to refactor this into two functions: n_queen_solvable and gen_queen_config or something of the sort.

Default parameters

You seem to want to start at the zeroith column. Makes sense. Instead of explicitly passing the startCol explicitly, I would just make col default to 0. This is done by changing:

def generateSolution(board, col):

to

def generateSolution(board, col=0):


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

Fix the return type for main

Unless you're working on an "unhosted" system (e.g. an embedded microcontroller), main should be declared as returning int and not void.

Update: As pointed out by @TimČas in a comment:

  Actually, main should be declared as int even in freestanding/unhosted (the C99 standard demands that compiler supports it; they are free to allow others, but the int version must be allowed")

The implication, of course, is that even if you're writing for an embedded system, unless you have a very old or noncompliant compiler, you should still use int as the return type for main.

Prefer standard functions

The main() function uses getch() but that's not actually standard.  Instead, you could use getchar() which is standard and will allow this code to work on any platform.

Always return an appropriate value

Your delFirst() routine has control paths that cause it to end without returning any int value.  This is an error and should be fixed.

Be careful with memory pointers

This code declares two pointers, premium and normal and then calls create which dereferences those uninitialized pointers.  That is not going to work.  Whenever you dereference a pointer, you should ask yourself "can this pointer possibly be NULL?" and "is this pointer actually pointing to something?" In this case, the pointers are not pointing to anything because they have not been set to any particular value.  Instead, you should call your makenode function instead, which actually allocates memory, and then initialize the members.

Combine allocation and initialization

The code currently has two separate functions: makenode and create both of which do part of the job of allocation and initialization.  Better would be to combine the two so that the a node is both allocated and initialized.  In C++ this is typically called RAII which stands for "Resource Acquisition Is Initialization" and it simply means that once you have a thing (a struct in this case), it's fully usuable.

Use single pointers where practical

In both your addLast and delFirst routines, the first parameter should be struct queue *q (with a single *) instead of what it currently has which is a **q.  That simplifies the rest of the code where you can replace every instance of (*q) with simply q.

Check for NULL pointers

The code inside makenode correctly avoid dereferencing a NULL pointer if the call to malloc fails, but addLast does not check p before dereferencing it. It should also check q to make sure that's not NULL either.

Consider separating the queue from the linked list

Each of the nodes in a linked list needs a next pointer, but not front or rear pointers.  Really, you only need one front and one rear pointer per queue and then just info and next per node.  You might consider creating separate node and queue structs for that reason.

Don't mix I/O with data operations

Generally speaking having a printf within a data manipulation function such as delFirst is not a good idea.  It makes it harder to reuse the function.  It's OK for diagnostics and for troubleshooting, but it would be better to omit it from the final version.


when calling malloc(), always check the returned value to assure the operation was successful

use meaningful variable names.   x is not a meaningful name and just makes the code more difficult to understand.

it seems the threads.h header file is not available everywhere.

For portability, suggest changing to the POSIX threads

#include <pthreads.h>

and using the related functions like:

pthread_create()
pthread_exit()
pthread_join()
pthread_t
pthread_mutex_lock()
pthread_mutex_unlock()

when a function fails, most likely one or more of the Philosopher entities have already been created via malloc()  to avoid a memory leak, those memory allocation pointers need to be passed to free()

When returning out of main, due to an error, return EXIT_FAILURE (or similar value) rather than returning 0 which indicates success.

in main(), the calls to create() need to check the returned value to assure the operation was a success.

the eat() function just zooms through and exits.  This is not the (typical) action of the Dining Philosophers problem.  Suggest searching stackoverflow.com for implementations of the problem and using the overall logic, with some modification for the 'left handed' diner.

The posted code fails to free() the malloc'd memory at the end of the main() function


jQuery Fallback Support for the CSS Property "background-attachment: local"

This code annoyed me for a while, the part outside of the initialization does not belong and it seemed silly to add it to the listener. Plus, the code outside of the listener will mess up when you have multiple data-holder elements.

Then I realized that I could take a different approach, do this in 2 steps:

Determine whether I should hide or show the top
Determine whether I should hide or show the bottom

Then, I do not need the piece of code outside of the listener, and it becomes cleaner.
Also, the 200 has to be a constant, also I would take only the #shadowbottom and #shadowtop belonging to the .data-holder.

So, in all, I would counter propose:

$(document).ready(function(){
  var fadeSpeed = 200;
  $('.data-holder').scroll(function(){
    var scrollValue = $(this).scrollTop(),
        elementHeight = $(this).height(),
        $top = $(this).children('#shadowtop'),
        $bottom = $(this).children('#shadowbottom'),
        atTop = (scrollValue == 0),
        atBottom = (scrollValue == ( this.scrollHeight - elementHeight));
    (atTop)   ? $top.fadeOut( fadeSpeed )    : $top.fadeIn( fadeSpeed );
    (atBottom)? $bottom.fadeOut( fadeSpeed ) : $bottom.fadeIn( fadeSpeed );
  }).scroll();
});

I was mildly worried that with each scroll event the top / bottom might flicker because of the repeated fadeIn() calls, but I can tell from your CodePen that does not happen, so there is nothing to worry about there.

Finally, I did not look at your CSS as you actually are a CSS developer and also I did not test my code, but I am confident you get where I am going with this.


Find the longest rectilinear path in a matrix with descending entries

As I said in the comment, it's probably faster to get the local minima and check the paths that start from those points. You can then get the path with the maximum length and reverse the points if you want the descending path.

I haven't tested this a lot, but it takes less than a second on my pc with a 4x4 matrix.

Here's the code (again, I've only tested this with a few inputs and there's a bit of code duplication, take it as a general guideline):

def get_next_ascending_value(row, column, matrix, size):
    current_value = matrix[row][column]
    max_steepness = -1
    coords = []
    if (column > 0) and (matrix[row][column-1] > current_value):
        if max_steepness < matrix[row][column-1]:
            max_steepness = matrix[row][column-1]
            coords = [row, column-1]
    if (row > 0) and (matrix[row-1][column] > current_value):
        if max_steepness < matrix[row-1][column]:
            max_steepness = matrix[row-1][column]
            coords = [row-1, column]
    if (column < size - 1) and (matrix[row][column+1] > current_value):
        if max_steepness < matrix[row][column+1]:
            max_steepness = matrix[row][column+1]
            coords = [row, column+1]
    if (row < size - 1) and (matrix[row+1][column] > current_value):
        if max_steepness < matrix[row+1][column]:
            max_steepness = matrix[row+1][column]
            coords = [row+1, column]

    return coords

def is_local_minimum(row, column, matrix, size):
    current_value = matrix[row][column]
    if (column > 0) and (matrix[row][column-1] < current_value):
        return False
    if (row > 0) and (matrix[row-1][column] < current_value):
        return False
    if (column < size - 1) and (matrix[row][column+1] < current_value):
        return False
    if (row < size - 1) and (matrix[row+1][column] < current_value):
        return False

    return True

def get_local_minimum(matrix, size):
    for row in range(len(matrix)):
        for column in range(size):
            if is_local_minimum(row, column, matrix, size):
                yield [row, column]

# [4, 5, 6]
# [1, 1, 6]
# [4, 5, 6]

# starting_matrix = [[4, 5, 6],[1, 1, 6],[4, 5, 6]]
# size = 3

# [4, 5]
# [1, 1]

# starting_matrix = [[4, 5],[1, 1]]
# size = 2

# [4, 5, 7, 9]
# [1, 1, 2, 5]
# [4, 5, 7, 9]
# [1, 1, 2, 5]

starting_matrix = [[4, 5, 7, 9],[1, 1, 2, 5],[4, 5, 7, 9],[1, 1, 2, 5]]
size = 4

for coords in get_local_minimum(starting_matrix, size):
    print(coords, starting_matrix[coords[0]][coords[1]])
    next_coords = get_next_ascending_value(coords[0], coords[1], starting_matrix, size)
    while (len(next_coords) > 0):
        print(next_coords, starting_matrix[next_coords[0]][next_coords[1]])
        next_coords = get_next_ascending_value(next_coords[0], next_coords[1], starting_matrix, size)
    print('---')


Assembler-program which reverses the content of EAX

In assembler it is often possible to avoid jmp instructions. This is done to improve branch prediction and thereby performance.

Your code can be written without the jump to add_one:

xor ebx, ebx
shr eax, 1
adc ebx, 0

These three instructions replace the whole jumping. The adc (add with carry) instruction's original purpose is to support chained addition, but it can be used creatively for many other purposes. Note that I had to move the xor ebx, ebx to the top since it updates the carry flag.

There are also the rcr and rcl instructions that efficiently use the carry flag as a one-bit register. You can just repeat 32 times:

rcr eax, 1
rcl ebx, 1

And you're done. When you inline this loop, you have a constant-time operation that finishes in 64 instructions. Each of them probably takes a single cycle, therefore 64 cycles. That's already acceptable, but there are probably better ways.

On the electrical, hardware level, the bitswap operation can be implemented by just swapping the wires, therefore chances are high that there is some machine instruction that makes this task more efficient. Just read through the whole processor manual to see if there is anything related. Have a look for the keywords "swap", "shift", "mask".

If you want to get a really fast program, you should use the bswap eax instruction, followed by code that reverses the bit order. This can probably be found in the excellent book Hacker's Delight.

The basic idea is to take every second bit and shift it to the left. At the same time, take the remaining bits and shift them to the right. Like this:

bits0 = (x & 0x55555555) << 1
bits1 = (x >> 1) & 0x55555555
x = bits0 | bits1

Then do the same thing with groups of 2 bits, and then once more with groups of 4 bits. The groups of 8 and 16 bits are done by the bswap instruction, you don't need to implement them on your own.


F# wrapper to generate SHA256 signature for a file

The use binding is usually better than the using function. The object is disposed when leaving the scope of the use binding (when leaving the SHA256 function).

let SHA256 (file:FileInfo) =
    use hashFile = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    use sha256Hash = SHA256Managed.Create()
    sha256Hash.ComputeHash(hashFile)

You can avoid the use of a string builder by using String.concat. You can also use the F# sprintf function, which has slightly different format specifier syntax.

let HexEncoded (hash:byte[]) :string =
    hash
    |> Array.map (sprintf "%02X")
    |> String.concat ""

This might be slightly slower than your string builder because it requires an intermediate array. (Note that your implementation could remove the intermediate array by using Array.iter instead of Array.map and moving the ignore to inside the lambda.)


You are using the prepared statement with placeholders properly, so regarding security, I would only advise you to not display the actual error details to the end user -- you don't want naughty people getting any funny ideas.

As for readability, I try not to declare single-use variables, though it can be good to declare a single-use variable to clarify the data being processed.

I don't prefer the over-delimit, then rtrim() technique.  Building a temporary array of ? then imploding it with commas seems cleaner to me.

$columns = implode(',', array_keys($data));

$placeholders = implode(',', array_fill(0, count($data), '?'));

$values = array_values($data);


Read a txt file and split into 2 csvs based on regex

I really don't know why someone's recommending lambdas to you like that but it's not at all what I'd do. I do agree there's some refactoring that could be done here though.

Refactoring

Why is ConvertTxtToCsvs a class? It contains only one function, process, and no attributes. There's no need for it to be a class. Instead, have it function based, and you should split it up a bit. Notice how writing to the good and bad csvs are mirrors of each other? You should have one write_csv function. Since all the code is the same except the filename and the data, it's very easy to turn into a function:

def write_csv(filename, data):
    with open(filename, 'w') as myfile:
        wr = csv.writer(myfile)
        for line in data:
            row = (' '.join(line.split())).split(' ')
            wr.writerow(row)

And then it can be called for both like this:

write_csv(good_csv_fname, good_data)
print("Csv for the bad data has been created successfully")
write_csv(bad_csv_fname, bad_data)
print("Csv for the good data has been created successfully")

Which is much neater. Also notice I changed from using a 2 space indent to 4 spaces. That's suggested by the Python style guide and is much more readable. This is especially important since whitespace affects program flow in Python.

Also, you read all the lines of the file up front just to iterate over them anyway. It'd be easier and less resource hogging to just read it line by line. Python makes it very easy, as you can directly iterate over a file-like object.

with open(fname) as f:
    for line in f:
        good_csv.append(line) if pattern.match(line) else bad_csv.append(line)

And lastly, you create your two lists before the function is called. This is bad, because you couldn't call the function more than once without accidentally including all the old data. Instead create the two lists inside the function so with each function call you create new empty lists.

Style Notes

I linked the style guide just above and it's a good read, but there's some other stuff I'd like to specifically point out. Some of your namìng isn't helpful. good and bad are often poor descriptions. Why are they good? Does good mean valid data, matching data, useful data? Instead, consider a name more relevant to what that means. matched and unmatched perhaps? Similarly, I'd avoid the use of csv. A csv is a filetype, your lists are not csvs (yet), so you don't need to include that name.

And don't shorten filename to fname. That shortened three characters isn't worth the reduced clarity here. And instead of just filename it'd be better to use source or source_filename.

source_filename = "track_param_hist.txt"
matched_data_file = "good_hist_csv.csv"
unmatched_data_file = "bad_hist_csv.csv"
pattern = re.compile("([0-9]+) +([0-9\.-]+)" + "+([0-9\.\-+Ee]+)" * 21)
matched = []
unmatched = []

You have a lot of comments that you don't really need. Comments should explain complex code or intent that's confusing to follow. There's no need comment about using with open and readlines. These are simple to follow functions, Python is highly readable that way. This could be a good line to comment:

            row = (' '.join(line.split())).split(' ')

It took me a moment to realise that it's splitting and rejoining the sentence to ensure that there's only a one space gap instead of any multiple spaces. You should write a comment to clarify this as it's a slightly confusing solution.

Using a ternary in your for loop works fine, but is a little hard to read. Ternaries are really best used when they can remove duplicate code and shorten things. Your case is less lines, but just as many words. This might be a better use of a ternary:

good_csv.append(line if pattern.match(line) else "")

I'd personally think it's better to write the loop this way:

for line in lines:
    if pattern.match(line):
        matched.append(line)
    else:
        unmatched.append(line)

This is how I'd rewrite your whole script in the end:

import re
import csv

source_filename = "track_param_hist.txt"
matched_data_file = "good_hist_csv.csv"
unmatched_data_file = "bad_hist_csv.csv"
pattern = re.compile("([0-9]+) +([0-9\.-]+)" + "+([0-9\.\-+Ee]+)" * 21)

def write_csv(filename, data):
    with open(filename, 'w') as myfile:
        wr = csv.writer(myfile)
        for line in data:
            # Make sure all whitespace is reduced to one space character
            row = (' '.join(line.split())).split(' ')
            wr.writerow(row)

def process(source):
    print("Script for splitting text file into two separate csvs...")

    matched = []
    unmatched = []

    with open(source) as f:
        for line in f:
            if pattern.match(line):
                matched.append(line)
            else:
                unmatched.append(line)

    write_csv(matched_data_file, matched)
    print("Csv for the good data has been created successfully")
    write_csv(unmatched_data_file, unmatched)
    print("Csv for the bad data has been created successfully")

if __name__ == "__main__":
    process(source_filename)


Extract the title from a webpage using the python 3 standard lib

Looks pretty clean to me, good job! Here's what I recommend:

The to_ascii function is small and readable, but in my opinion the is_string and is_bytes functions are overkill:

def to_ascii(data):
    if isinstance(data, str):
        ...
    elif isinstance(data, bytes):
        ...
    else:
        ...

We can make to_ascii less complex by returning immediately:

def to_ascii(data):
    if isinstance(data, str):
        return data.encode("ascii", errors="ignore")
    elif isinstance(data, bytes):
        return data.decode("ascii", errors="ignore")

We can then leave out the else clause:

def to_ascii(data):
    if isinstance(data, str):
        return data.encode("ascii", errors="ignore")
    elif isinstance(data, bytes):
        return data.decode("ascii", errors="ignore")
    return str(data).encode("ascii", errors="ignore")

error_callback is pretty much useless. Maybe you planned on adding more functionality to the Parser class, but as is, you can just leave it out.
I don't expect a parser's constructor to automatically parse the data I pass. How about:

class Parser(HTMLParser):
    def __init__(self, data):
        self._data = data
        ...

    def parse(self):
        self._parsed = self.feed( ... )


First of all, you don't need to make a class for this. There's no real reason for FizzBuzz to be an object when all you have is a collection of functions anyway. Likewise, you have a lot of functions that don't really need to be functions. All your test functions could just be plain if statements and that'd make them more readable to Python. I see you've discovered the _ naming convention in Python, where names beginning with that are to be considered private. However you don't need to use these that often. Nothing's ever going to be truly private in Python without a lot of work, so instead allow people to access functions if they want to. Only mark functions private if there's actual problems with them attempting to use the function outside of a specific process.

parse_number is good, though I'd replace the tests with plain tests instead of your functions.

def parse_number(number):
    if number % 15 == 0:
        return "FizzBuzz"
    elif number % 3 == 0:
        return "Fizz"
    elif number % 5 == 0:
        return "Buzz"
    else:
        return str(number)

You could also add a docstring and maybe a comment, to indicate what the function does and returns as well as noting how number % 15 == 0 is the same as (number % 5 == 0) and (number % 3 == 0).

def parse_number(number):
    """Returns a string Fizzbuzz representation of a number"""

    # This is the same as (number % 5 == 0) and (number % 3 == 0)
    if number % 15 == 0:

Start seems like a not very worthwhile function and not a great name if you're no longer making a class. But if you want to keep it a name like fizzbuzz_string would be better.

Now, your _parse_numbers isn't a great name because it's too similar to an existing function. There's also little reason to mark it as private. Instead this could be your main method, or at least call it fizzbuzz. You could also build it easier and faster with something called a list comprehension. A list comprehension is basically a for loop like expression that will be evaluated to create a list. Yours is very simple, you just need to run parse_number on each number in your range, so this is how you could write it:

def parse_number(number):
    """Returns a string Fizzbuzz representation of a number"""

    # This is the same as (number % 5 == 0) and (number % 3 == 0)
    if number % 15 == 0:
        return "FizzBuzz"
    elif number % 3 == 0:
        return "Fizz"
    elif number % 5 == 0:
        return "Buzz"
    else:
        return str(number)

def fizzbuzz(end_number):
    """Return a list of Fizzbuzz parsed numbers up to end_number."""

    return [parse_number(number) for number in range(1, end_number+1)]

def fizzbuzz_string(end_number):
    return ",".join(fizzbuzz(end_number))

Now you can easily just call print fizzbuzz_string(number) and get the full list without needing an object or the other extraneous functions.


No particular comment on the Arduino-specific or Wifi-specific stuff, but here:

currentssidno = currentssidno + 1;
if (currentssidno == 6) //please change this count if you change the amount of ssids
{
  currentssidno = 0;
}

Two things. First, you can rephrase this conditional logic as simply

currentssidno += 1;
currentssidno %= 6;  // please change this, etc.

or equivalently

currentssidno = (currentssidno + 1) % 6;  // please change this, etc.

depending on where you'd prefer to repeat the name currentssidno. (I'd probably rename that variable to i and then use the latter form.)

Secondly, don't hard-code magic numbers like 6, if you can express them as "non-magic" numbers such as "the size of this particular array I've got".

// Put this macro in your toolkit. You'll use it frequently.
#define DIM(arr) (sizeof (arr) / sizeof (arr)[0])

/* ... */
currentssidno = (currentssidno + 1) % DIM(ssids);

Now you no longer need the comment, because the code no longer has that weird subtle dependency on the length of the ssids array. It Just Works, no matter what ssids you want to use.


CodeWars - Assembly Language - Check List For Value

First of all, props for the copious comments, particularly how you included a representation in C. The C representation itself has a signed vs unsigned comparison, which can cause weird bugs when and where you don't expect them, but I'm going to stick to the assembly code itself in this review. I would just recommend declaring the loop counter i as size_t, since that's what the type of the stop condition is.
I assembled your C function using gcc version 10.2.0 with -O3 -march=native, so I'll include the output here so I can walk through it step by step, comparing the two implementations. This is a really good idea, by the way, because working backwards through what the C compiler did helps you see real assembly language, not just practice examples you wrote. Compiler Explorer is a great tool for this.
Anyways, here is my input file.
#include <stdbool.h>
#include <stddef.h>

bool include(const int* arr, size_t size, int item) {
    for (size_t i = 0; i < size; ++i) {
        if (arr[i] == item) {
            return true;
        }
    }

    return false;
}

To assemble it, I use the following command. Note the -masm=intel argument; the default assembly syntax is AT&T for GNU tools.
gcc -S -O3 -march=native -masm=intel -o output.asm input.c

You can filter out auxiliary metadata and its containing labels using the following command.
cat output.asm | sed -E '/^\s+\./d;/^\.L[A-Z]/d'

And here is my output.
include:
        test    rsi, rsi
        je      .L4
        xor     eax, eax
        jmp     .L3
.L8:
        inc     rax
        cmp     rsi, rax
        je      .L4
.L3:
        cmp     DWORD PTR [rdi+rax*4], edx
        jne     .L8
        mov     eax, 1
        ret
.L4:
        xor     eax, eax
        ret

Notice that the first line is already different. In your version, you started by setting the rcx register to 0, using the mov instruction, whereas the compiler output test rsi, rsi. Why?
Well, as you noted, Intel x86-64 Linux assembly programming calling convention dictates that the rsi register contains the second argument to your function, in this case the size of the array.
From the Intel x86-64 documentation (pg. 1866), the test instruction performs a logical AND test on its arguments. If the result is zero, it sets the zero flag ZF equal to 1. The following instruction therefore makes sense, since the "jump near if equal" (je) instruction is carried out when the the zero flag is set (ZF=1).
In other words, the subroutine begins by checking whether or not the input array actually contains any items before actually doing anything with it. Note that you weren't checking for this edge case in your original code (nor did you verify the array pointer wasn't NULL), and it's a great example of compilers being awesome. Matt Godbolt (the guy who made Compiler Explorer) has an awesome talk about this kind of stuff that I highly recommend you check out if you like this sort of thing.
Anyways, if you look at the .L4 label, you'll notice it's semantically equivalent to your skip_loop. However, you literally set the rax register (i.e., the return value of the function) equal to zero by moving a 0 into it, whereas the compiler uses the exclusive-or xor instruction on eax with itself, which will obviously always be zero. You're not semantically wrong for doing it the way you did, but you can read this SO post that describes in significant detail why you should opt for the xor eax, eax method. The short version is that it's more efficient, and the longer version is that it's much more efficient, but there are other benefits, like power consumption. That post goes into a lot more detail, though, and it's a great read.
Your loop itself looks okay to me. The compiler used the rax register for the loop counter, which both you and the compiler then used to get the value of the array at the appropriate index. The only real difference between the two versions is that the compiler used an unconditional jump jmp instruction to skip the first part of its main loop, which contained the loop counter increment, whereas your code had that last.
I genuinely don't think this difference has any real impact, because both implementations contain two conditional jumps, which significantly impact performance because they trigger unconditional instruction fetches and involve more advanced processor features like branch prediction, which itself introduces problems via an optimization called speculative execution. (Long story short, optimization is complicated, you won't really know until you profile it, and you probably shouldn't even care about optimization until you have a working something to optimize, but you're "probably" fine.)
Something I found really interesting (although not particularly impactful or world-view shattering), was that believe it or not, creating that temporary variable and then comparing takes exactly as many bytes to encode as the direct comparison the compiler output in my version.
Here is a snippet from the objdump output for your version. (To generate this on your local machine, the command I used after assembling with nasm was objdump -Mx86-64,intel -D -S -s input.o.)
0000000000000005 <loop1>:
loop1:
    cmp rcx, rsi    ; if ( i < size ) {
   5:   48 39 f1                cmp    rcx,rsi
    jae skip_loop
   8:   73 14                   jae    1e <skip_loop>

    mov r8d, [rdi + 4 * rcx]        ; make a temp variable so we can see this in step debugging
   a:   44 8b 04 8f             mov    r8d,DWORD PTR [rdi+rcx*4]
    cmp edx, r8d    ; if ( arr[i] == item ) {
   e:   44 39 c2                cmp    edx,r8d
    jne skip_if
  11:   75 06                   jne    19 <skip_if>
    mov rax, 1      ; return true;
  13:   b8 01 00 00 00          mov    eax,0x1
    ret
  18:   c3                      ret

Now here's a snippet from the output for the compiler's version that contains the comparison operation.
0000000000000011 <include.L3>:
.L3:
    cmp     [dword rdi+rax*4], edx
  11:   39 94 87 00 00 00 00    cmp    DWORD PTR [rdi+rax*4+0x0],edx
    jne     .L8
  18:   75 ef                   jne    9 <include.L8>
    mov     eax, 1
  1a:   b8 01 00 00 00          mov    eax,0x1
    ret
  1f:   c3                      ret

Notice how in your version, the assignment to a temporary variable takes four bytes. You specified the r8d register as the destination register, so this isn't exactly groundbreaking stuff, but the following comparison instruction required only three bytes to encode:
44 8b 04 8f             mov    r8d,DWORD PTR [rdi+rcx*4]
44 39 c2                cmp    edx,r8d

The compiler's version skipped the intermediate variable assignment, but the resulting instruction required seven bytes to encode.
39 94 87 00 00 00 00    cmp    DWORD PTR [rdi+rax*4+0x0],edx

To explain why those extra zeroes at the end matter, I will borrow once again from this great post which you should definitely read.

Smaller machine-code size [...] is always an advantage: Higher code density leads to fewer instruction-cache misses, and better instruction fetch and potentially decode bandwidth.

To really drive this point home, let us read the conditional jump instruction documentation (pg. 1109 in the combined manual [vols 1-4]):

All conditional jumps are converted to code fetches of one or two cache lines, regardless of jump address or cache-ability.

I now leave this link to the latency numbers every programmer should know for your edification, although it should be noted this document is from 2012. Here's a cool updated version where you can look at the latency numbers by year (including 2020), but I actually just found this myself, so I admit I haven't vetted the source for accuracy. I am including it for completeness nonetheless.
As far as the labels themselves are concerned, since loop1, skip_if, and skip_loop are all logically related to the include subroutine, I would recommend using local labels to more intuitively organize your assembly code. Local labels are particularly useful because the subroutine name serves as a sort of namespace, allowing you to reuse the local label names defined therein. You can see the include version above assembled by gcc uses local labels.
The only recommendation I would make regarding loops is to be wary of using the right conditional jump for your situation. From the documentation:

The terms "less" and "greater" are used for comparisons of signed integers and the terms "above" and "below" are used for unsigned integers.

This isn't pedantry, either. Take for example, the  "jump if above or equal" jae instruction in your code. It follows a cmp instruction, which subtracts the second operand from the first and modifies the EFLAGS register accordingly. Specifically, the intermediate sub instruction performs both signed and unsigned subtraction, setting the overflow and carry flags, respectively. However, by using the jae instruction, you are implicitly only checking the carry flag, so hopefully your loop counter and stop conditions are of the same type.
The C standard defines how this should be done, which does help mitigate bugs by both converting as properly and safely as possible, and by providing helpful warnings and even error messages (depending on the compilation strictness settings). Of course, if you're going to be writing assembly language directly, this obviously does not help you.
For reference, the EFLAGS condition codes can be found in Volume 1 Appendix B of the Intel® 64 and IA-32 Architectures Software Developer’s Manuals, and the conditional jumps reference table starts on page 1106 of Volume 2.


Bank account supporting deposit, withdrawal, and interest

Well, this is really vague.

Regarding Account :

Your Account class looks like a anemic class except the computeInterest method. For this one, you should rename the n parameter to reveal his role.

I does not understand your getsetInterest method.

One thing that seems wrong is your close method. When an Account is closed it cannot be used anymore. You may maintains another state to know if the account is closed. Or create another ClosedAccount.

For TestAccountInterest :

You should have a look at a test framework that will run your tests and report failures.

Your class is called TestAccountInterest but you are doing more than testing the interest, you are also testing the deposit and withdraw methods.


Generate all possible combinations of letters in a word

I'm going to throw my hat in the ring with the iterative version of Heap's method of generating permutations. It took me a while to get right, as my reference source has a typo in the algorithm -_-.

function swap(chars, i, j) {
    var tmp = chars[i];
    chars[i] = chars[j];
    chars[j] = tmp;
}

function getAnagrams(input) {
    var counter = [],
        anagrams = [],
        chars = input.split(''),
        length = chars.length,
        i;

    for (i = 0; i < length; i++) {
        counter[i] = 0;
    }

    anagrams.push(input);
    i = 0;
    while (i < length) {
        if (counter[i] < i) {
            swap(chars, i % 2 === 1 ? counter[i] : 0, i);
            counter[i]++;
            i = 0;
            anagrams.push(chars.join(''));
        } else {
            counter[i] = 0;
            i++;
        }
    }

    return anagrams;
}

With some sample timings to count the anagrams of "codereview":

$ time node anagrams-heap-iterative.js
3628800

real    0m0.855s
user    0m0.000s
sys     0m0.015s

$ time node anagrams-megawac.js
3628800

real    0m2.286s
user    0m0.000s
sys     0m0.000s


Entity management design & smart pointers

The fact that AddEntity leaves behind a unique_ptr to a possibly destroyed entity bothers me (right now, moving your entity does not "destroy" it, but you might add destructible components later). In my opinion, AddEntity should not take its argument by pointer but by reference:

void EntityManager::AddEntity(const Entity& entity) {
    mEntities.push_back(entity);
}

You can provide an overload for rvalue-references to move entities that are meant to disappear anyway though:

void EntityManager::AddEntity(Entity&& entity) {
    mEntities.push_back(std::move(entity));
}

You probably didn't care because in your use case, you passed temporary variables that are destroyed right after having been created. But what you might actually want to do is to create the entities directly in the vector insteas of creating them, then adding them to the vector. Therefore, what you really need is an emplace_back function:

template<typename... Args>
void EntityManager::EmplaceEntity(Args&&... args) {
    mEntities.emplace_back(std::forward<Args>(args)...);
}

With such a function, you can init your world like this:

void World::Init() {
    // Add some initial entities
    for( int i=0 ; i < 200; i++ ) {
        mEntityManager.EmplaceEntity(*this);
    }
}

EDIT: Answering your comment. If Entity is an abstract class and you only add instances of derived classes, then I think that push_back still works fine since polymorphism will be achieved via reference semantics. On the other hand, EmplaceEntity could take another argument if you want to emplace instances of classes derived from Entity:

template<typename Derived, typename... Args>
void EntityManager::EmplaceEntity(Args&&... args) {
    std::unique_ptr<Entity> ptr( new Derived{std::forward<Args>(args)...} );
    mEntities.push_back(std::move(ptr));
}

I did not test the code above, but theorically it should. That allows you to create instances of classes derived from Entity directly without having to bother with the pointers. Here is how you could use it:

mEntityManager.EmplaceEntity<BlueEntity>(*this);

Anyway, whenever possible, try to use reference smantics and to hide pointer semantics inside the classes so that the users of the classes don't have to bother with the pointers.


Creating remote directories in a bash script via ssh (with error trapping)

Running ssh in a loop is not efficient. Since the script is not interactive,
you could pass the entire script to a remote Bash process on stdin,
so that loop will run entirely on the remote server, locally:

ssh remotehost bash << "EOF"
mydirs=(/var/www/files /var/www/photos /var/www/info)
for d in ${mydirs[@]}; do
   test -d $d
   res=$?
   test $res -ne 0 && { mkdir -p $d; res=$?; }
   test $res -ne 0 && { echo "error during mkdir on remote"; exit 1; }
done
EOF

Notice the double-quotes around the here document label, this is to avoid variable interpolation. The entire script is passed to the remote shell literally.

I made only the minimal changes to illustrate the point. Some important improvements are well advised:

All variables used as command line arguments should be double-quoted: "${mydirs[@]}", "$d", and so on.
As a comment mentioned, when using mkdir -p, it's unnecessary to test if the directory exists.
Now that the main operations run in a single process, the pipeline can be simplified.
As another comment mentioned, consider investing in learning a proper system administration tool such as Puppet, Ansible, Chef, or similar.


I am puzzled by how you use item both inside and outside ng-repeat.

Each iteration of ng-repeat has its own scope, so its own item. For instance, if items = [item1, item2], which item do you mean to use inside doSomething?
The way it is used now, the item seen by that function will be another item on the outside scope. If this is the intention, this variable should be named differently:

{{item.name}}

UPDATE. Having another look I see better what you are trying to achieve. Still I would improve design by making the directive more re-usable.

You basically want to throw any HTML inside the directive and pick the model associated with event's target. The directive makes this model available on the scope of your expression doSomething(model).  Just like $event made available inside the ng-click. I would then mark this model as something special like:

Then it is the job of the directive to pick the right model and make it available under this name. This way I can change item to my-item inside ng-repeat without breaking things, so the directive is more encapsulated and re-usable.


Search for User by first and/or last name, efficiently

These are just some ideas based on some assumptions, so I may be way off.

  Looking for a first_name in the last_name column sounds kind of silly hackery. Unless I'm looking at this the wrong way.

The "hacky" feeling is maybe not so much because of the code itself, but elsewhere in the design. It sounds like a "hacky" user-facing UI or client-server API, rather than hacky code, is to blame.

I assume the user interface (if there is one) always shows both a first name and a last name input field of some kind. If that's the case, isn't it valid to only search for the value(s) the user provides?

I certainly wouldn't expect to get results for last name OR first name matches if I only provide a "last name" search string. Similar, I wouldn't expect to find both "Daniel Craig" and "Timothy Dalton" if I type in "Da" in the first name field.

Even if the client has no obvious or direct user input, I'd still say the API should be clear so that an fname param searches for first name, and only first name matches, while lname is last-name-only.

Overloading a user interface or API with non-obvious, special functionality is no different than overloading a method with strange behavior that triggers when pass it certain arguments.

In other words, I'm not sure the OR case makes sense, given input that's so specific and the (assumed to be) equally specific UI.

So, if we can eliminate the OR query (and I admit it's all assumptions here), I'd might do something like:

# get the search parameters, but only
# keep those that that are actually present
search_params = {
  first_name: params[:fname],
  last_name:  params[:lname]
}.keep_if { |_, value| value.present? }

# now do the search
@users = if search_params.any?
  # chaining `where` calls will implicitly add the `AND` in between
  search_params.inject(nil) do |memo, pair|
    column, string = pair
    (memo || User).where("#{column} LIKE ?", "%#{string}%")
  end
elsif params[:email_search].present?
  User.where("email LIKE ?", "%#{params[:email_search]}%")
end

head :not_found if @users.blank?

Haven't tested it, but it should work.

Alternatively, you can leave the "search for name" vs "search for email" decision to the client, and simply say the the API will return for whatever matches all the criteria you send it; if you don't want something matched, don't send it. In that case, the elsif isn't even necessary:

search_params = {
  first_name: params[:fname],
  last_name:  params[:lname],
  email:      params[:email_search]
}.keep_if { |_, value| value.present? }

@users = search_params.inject(nil) do |memo, pair|
  column, string = pair
  (memo || User).where("#{column} LIKE ?", "%#{string}%")
end

head :not_found if @users.blank?

The client can then implement its UI/code however it sees fit, and send whatever params it needs to. Yes, it's just moving the problem, but your API is a lot clearer.

Of course, another solution still would be to index your data in some fashion, so you could just search on any field in one go by just passing a q param or something. But that's another kettle of fish entirely.

Again, just ideas based on assumptions.


C++ implementation of a Stack with dynamic C-style array

Prefer std::vector to dynamic allocation
I understand this project was meant for practice, I have done a similar project, who wouldn't want to mess around with memory allocation, but doing so leads to errors when the programmer is not careful or chooses to ignore certain things. Using std::vector gives you the following for free

Copy constructor
Copy assignment
Move constructor
Move assignment

This enables you to focus more on the business logic of the problem.
Stack class does not cater for default constructed objects
Right now, your class assumes that users do not have default constructible objects. This is okay because you are holding Integral values, but you might change it in the future. The following
int *p = new int{}

allocates and construct an int in memory, this is okay for int because it has a default constructor. Your class might hold objects that are very expensive to construct and as such, users might need to just have a stack that can hold their default constructible objects and construct them when they are needed. This give rise to placement new, see more about placement new here
CODE REVIEW

In Stack constructor, you declared the following

Stack(int32_t u_size = 10)

This is okay, you want a default stack to have 10 elements, A better approach is to declare a default stack to hold 0 elements, this is the behavior of std::vector. The stack can grow when necessary. If the user wants to explicitly request for space, declare a reserve method that allocates space. You might also consider a shrink_to_fit method, well am going overboard for a simple stack class.

You forgot to allocate memory in your copy constructor. This is dangerous, you are reading into memory that was never allocated. The result is undefined, it might work today and crash tomorrow. A correct approach is this

 Stack(const Stack& other) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ other.m_capacity } {        // copy constructor
    m_stack_arr = new int32_t[other.m_size];
    for (int32_t i = 0; i < other.size(); i++)
    {
        push(other.m_stack_arr[i]);
    }
}

Now this is better, we explicitly created m_stack_arr.

Move constructor does not work. On testing your move constructor, I resulted to a segmentation fault. m_size was not given the appropriate size, the same case with m_capacity. using a swap method, your move constructor can be defined as follow

void swap(Stack& lhs, Stack& rhs)
{
    using std::swap;
    swap(lhs.m_current_ind, rhs.m_current_ind);
    swap(lhs.m_size, rhs.m_size);
    swap(lhs.m_capacity, rhs.m_capacity);
    swap(lhs.m_stack_arr, rhs.m_stack_arr);
}

This method just swap the internal representation of objects. Using this method, move constructor and move assignment becomes easy
Stack(Stack&& other) noexcept {             // move constructor
    swap(*this, other);
    other.m_stack_arr = nullptr;
}

We set the value of other.m_stack_arr to a nullptr to make it a cheap resource for the compiler to destroy.
Move assigment is also similar, a self move is not bad and no need for a check here.
Stack& operator=(Stack&& other) noexcept {
    swap(*this, other);
    other.m_current_ind = -1;
    other.m_size = 0;
    other.m_stack_arr = nullptr;
    return *this;
}

Both methods are marked noexcept because we are guaranteed that move assignment and move constructor would not throw an exception, this gives room for compiler to optimize some certain things.

In clear method, you delete m_stack_arr before allocating a new one, what if new throws an exception, you have lost m_stack_arr.

void Stack::clear(int32_t new_capacity)
{
    int32_t* temp_arr; = new int32_t[new_capacity];
    delete[] m_stack_arr;
    std::copy(m_stack_arr, m_stack_arr + m_size, temp_arr);

    //.. Your code goes in here
}

Here we created our memory and store it temp_arr, if that doesn't throw, we delete our old array and copy the new one.
A more optimized version would be to use memcpy to copy the bytes from memory, but that is a different topic entirely.


Skipping over failed imports until they are needed (if ever)

There is one issue with your approach which is, in the case of multiple import failure, only the last one can be properly reported:

>>> try:
...   from .foo import Foo
... except ImportError:
...   from .base_engine import Default as Foo
...   setattr(Foo, 'name', 'Foo')
...
>>> try:
...   from .bar import Bar
... except ImportError:
...   from .base_engine import Default as Bar
...   setattr(Bar, 'name', 'Bar')
...
>>> Bar()
Traceback (most recent call last):
…
ImportError: The class Bar you tried to call is not importable; this is likely due to it not being installed.
>>> Foo()
Traceback (most recent call last):
…
ImportError: The class Bar you tried to call is not importable; this is likely due to it not being installed.

You instead want to generate a new class with the proper message each time.

Something along the line should do:

def mock_missing(name):
    def init(self, *args, **kwargs):
        raise ImportError(
            f'The class {name} you tried to call is not importable; '
            f'this is likely due to it not being installed.')
    return type(name, (), {'__init__': init})

Usage being:

try:
    from .foo import Foo
except ImportError:
    Foo = mock_missing('Foo')


Google Guice module that loads two kinds of views

What this is looking for is "Binding by Convention". Since Guice is intended to be as lightweight (and fast) as possible, it does not contain facilities to enable binding by convention.
Neither does Spring for that matter. I think you might be able to automate the bindings injected into the methods if you use Plexus.
Do note that none of this will alleviate you from the actual problem you're facing:
Why?
You write:

Basically I want to inject fully configured FXMLLoaders into some
Controller classes, so that they can work with the root nodes returned
from the loaders without having to know anything about other
controllers.

This makes  no sense: You're injecting FXMLLoaders into Controllers, specifically into a controller that's not the Controller you set on the FXMLLoader itself. To access the rootNode returned by the loader.
This violates the Law of Demeter. You're grabbing into the responsibilities of another controller.
The solution to this problem is to expose a method on the controller and inject a the controller instance you need, instead of the loader.
This whole module seems to me like it's solving the wrong problem in the first place ...


C++/STL Prime tuples (twin, cousin, sexy) up to the given limit

std::min_element is unwarranted. The list is initially sorted, and remove_if guarantees to maintain the order of remaining elements. A minimal element is *l.cbegin().
removeElementsInListDivisibleByP is very hard to read. Consider remove_multiples_of_P.
The list initialization loop really wants to be std::iota.
The sieving does work, but it seems less efficient than the classical one.
If an std::vector can be used, it performs better than std::list (mostly due to preferential locality and less memory overhead). You may want to experiment.
I don't see what adjacent_find is supposed to do. Is it a remnant of some debugging code, perhaps?


Use only necessary fields in an object for URL params

I think you could do this in one go using Object.keys on your formData Object, followed by a few methods from the Array and String prototype.

var formData = {
  account_name: 'SomeAccountName',
  custom_domain_name: '',
  id: 152
};

var enc = encodeURIComponent;

// create an array from formData props
var query = Object.keys( formData )
// filter by the prop value length
// which will only give you props where the value
// has a length property which is greater than 0.
  .filter( key => formData[key].length )
// map to acctually add the value to the filtered props
// separated by equal signs.
  .map( key => enc( key ) + '=' + enc( formData[key] ) )
// add your popup prop
  .concat( 'popup=true' )
// join your array elements to a string separated by &.
  .join( '&' )
// finally add ? to the beginning of the string.
  .replace ( /^/,'?' );

// here is your query string.
console.log(query)
.as-console-wrapper { top: 0; }


Shorthand and nicer python syntax for four options clicking a button

If 0 and 1 are the only possible values of af_button.checked, you could condense this to just one if:

if (state == 'click') != af_button.checked:
    squishtest.clickButton(squishtest.waitForObject(af_button))

The parentheses are important because otherwise Python would treat this as a chained comparison. (state == 'click') evaluates to True or False, and True equals 1 and False equals 0.


Sort multidimensional array based on another one containing the desired order

I think this would be the cleanest solution. Similar to @YourCommonSense answer, but slightly inverted as ordered index is already there - only values missing.

$sorted = array_flip($order);
foreach ($array as $value) {
    $id = $value['id'];
    $sorted[$id] = $value;
}


Avoid special cases
A lot of problems come from the fact that you have slightly different ways to construct a 2D point and to get its elements than you have for an arbitrary dimensional point. You should avoid that first, this will make your life much easier.
Here is a class Point that supports getX() and getY() with compile-time checking that the size of elements is large enough, and a constructor that takes a variable number of arguments, so you don't need to use braces when constructing a Point:
template <typename T, int N>
class Point
{
   std::array<T, N> elements;

public:
    template<typename... E>
    Point(E&&...e): elements({std::forward<E>(e)...}) {}

    Point operator+(const Point& other)
    {
        Point c;
        std::transform(elements.begin(), elements.end(), other.elements.begin(),
                  c.elements.begin(), plus<T>());
        return c;
    }

    const T& operator[](size_t k) const
    {
        return elements[k];
    }

    friend std::ostream& operator<<(std::ostream& os, Point const& x)
    {
        os << "P(";
        for (auto& k : x.elements) os << k << ", ";
        return os << "\b\b" << ')';
    }

    template<std::enable_if_t<(N > 0), int> = 0>
    const T& getX() const {
            return elements[0];
    }

    template<std::enable_if_t<(N > 1), int> = 0>
    const T& getY() const {
            return elements[1];
    }
};

There are various ways to enable/disable member functions at compile time, the above uses std::enable_if_t which completely disables a function. You can also use a compile-time assert, like so:
T getY() const {
    static_assert(N > 1, "this point doesn't have a y coordinate");
    return elements[1];
}

Although as pointed out in the comments, this has the drawback that you cannot check at compile time if a given Point type supports getX(), getY().
To make a Point2D convenience class, use using:
template<typename T>
using Point2D = Point<T, 2>;


Is this a proper quicksort algorithm in Python?

Some comments:

Write docstrings to document code
Use if/else instead of if/elif if possible
Use list comprehensions
Use random.choice to get a random element from a non-empty sequence

The code in the original questions with the suggested improvements would be as follows:

import random

def qsort(qslist):
    """"Quicksort implementation."""
    if len(qslist) < 2:
        return qslist

    pivot = random.choice(qslist)
    small = [x for x in qslist if x < pivot]
    equal = [x for x in qslist if x == pivot]
    big = [x for x in qslist if x > pivot]

    return qsort(small) + equal + qsort(big)

qslist = [9,1,8,2,7,3,6,4,5]
print(qsort(qslist))

Edit: If you prefer to avoid traversing the array three times, a partition
function to do that very similar to the one in the original question would be:

def partition(qslist):
    """Partition array using a pivot value."""
    small = []
    equal = []
    big = []

    pivot = random.choice(qslist)
    for x in qslist:
        if x < pivot:
            small.append(x)
        elif x == pivot:
            equal.append(x)
        else:
            big.append(x)

    return small, equal, big


Going to the thread pool and back using custom awaiters

What you are after is yielding to a different thread, which has been covered in this question. One difference is that Andrew's code implements ICriticalNotifyCompletion vs you're implementing just INotifyCompletion. I haven't found any good documentation which one to prefer and what Critical exactly means. It may mean that his code works in some weird corner case scenarios where yours might not - hard to say. Most articles state that it's optional to implement the critical interface so it may not matter.

The other difference is that Andrew's code doesn't provide an option to switch back plus he's using a struct while you are using a class (which is just a potential performance optimization)

The main conclusion was that Microsoft didn't provide this out of the box since they felt it was prone to abuse.

In general I prefer Andrew's usage pattern of TaskEx.YieldToThreadPoolThread() over your more direct await GoToThreadPool.Instance since it's slightly more readable.

So combining the two implementations one could end up with something like this:

public static class TaskEx
{
    public static YieldToThreadAwaitable YieldToThreadPool()
    {
        return new YieldToThread(null);
    }

    public static YieldToThreadAwaitable YieldToMainThread()
    {
        return new YieldToThread(Application.Current.Dispatcher.Thread);
    }

    public static YieldToThreadAwaitable YieldToThread(Thread target)
    {
        return new YieldToThread(target);
    }
}

public class YieldToThreadAwaitable : INotifyCompletion
{
    private Thread _Target;

    public YieldToThreadAwaitable(Thread target)
    {
        Target = target;
    }

    public bool IsCompleted
    {
        get { return _Target != null ? Thread.CurrentThread == _Target : Thread.CurrentThread.IsThreadPoolThread; }
    }

    public YieldToThreadAwaitable GetAwaiter()
    {
        return this;
    }

    public void GetResult() { }

    public void OnCompleted(Action continuation)
    {
        if (_Target == null)
        {
            ThreadPool.QueueUserWorkItem(o => continuation());
        }
        else
        {
            Dispatcher.FromThread(_Target).BeginInvoke(continuation);
        }
    }
}


I would advise using slightly longer names (rind should be row_ind, etc.), adding comments (while you are writing the code, not after) and avoiding counterintuitive variable names such as four. It is quite confusing when you are writing statements such as four == 2.

In addition, I would replace

self.last_move == ()

with

not self.last_move

to future-proof your code in case you switch to using lists or something else entirely.

Also, to simplify your structure, I would suggest splitting up your longer functions into other smaller functions, to make your code more digestible and reusable.

Also, instead of initializing players with tuples of seemingly random numbers, add some constants in your code for further increased readability.


Reading Data from XML and storing them into SQL Database

Review

Single responsibility principle
Method save_vendor_info (which we'll rename later) does data retrieval from an external source, xml to db mapping, and SQL command execution on a database. I would expect a method with the name Save* to only store data, in this case in the database. I would also suggest to split up loading the input data and saving to the database in separate methods. A mediator method could then call both methods and ensures the data is mapped correctly.

Resource management
You don't dispose of resources that you create. SqlConnection and SqlCommand implement the IDisposable interface. You should make sure to dispose these instances (SQL Disposable Pattern Example). You already open the connection before retrieving the web data. This is too soon. Keep the scope of a connection lifetime to a minimum.

Exception Handling
Definining an empty catch block is really bad practice. You don't know whether something went wrong. At least, log exceptions. Think about which specific exceptions you want to handle and which ones need to be propagated up the stack. Even in sand-box mode, where you don't want exceptions to reach the caller, you should return a boolean to the caller whether the call succeeded.

Naming & Style Conventions

Try to avoid underscores in method names and use PascalCase. Prefer SaveVenderInfo over save_vendor_info. As indicated earlier on, I would use this method name only for the part where you save the data to the database.
Use var when the type is inferred and don't use abbreviations for variable names: Prefer var dataTable = new DataTable(); over DataTable dt = new DataTable();.
Read SQL connection string information from a config file rather than hardcoding it. This gives better maintainability for different environments.
Be consistent in placement of curly braces. Either append an opening curly brace after the method with a white space between, or place the opening curly brace on the next line at the same indentation of the member declaration. Don't indent a curly brace on the next line, this leads to deeply indented code.


Babel codemod to transform require statements

The only problem with this code that jumps out is declaratorKinds = { let: null, var: null } for use with path.node.kind in declaratorKinds. It would be much better to just use an array or set.

const declaratorKinds = ['let', 'var']
...
if (declaratorKinds.includes(path.node.kind))

As far as I can tell VariableDeclaration is the best way to handle this, I have no experience with babel transforms, so I may be missing something.

Bugs:

var fs = require('fs'), temp; will be transformed into const fs = require('fs'), temp; which will throw a syntax error.
var temp = 1, fs = require('fs') will not be transformed.

A better solution would be to check each VariableDeclarator item in path.node.declarations, this could look something like the following. (Note that this rewrites multiple simultaneous declarations into separate declarations - the style I prefer)

export default function({types}) {
  return {
    visitor: {
      VariableDeclaration(path) {
        const { kind, declarations } = path.node

        if (!['let', 'var'].includes(kind)) {
          return
        }

        const requireDeclarations = declarations.filter(d => {
          return d.init && d.init.callee && d.init.callee.name == 'require'
        })
        const otherDeclarations = declarations.filter(d => !requireDeclarations.includes(d))

        if (requireDeclarations.length) {
          path.replaceWithMultiple([
            ...requireDeclarations.map(d => types.VariableDeclaration('const', [d])),
            ...otherDeclarations.map(d => types.VariableDeclaration(kind, [d])),
          ])
        }
      }
    }
  }
}

Demo here (forked from your demo)


Regular expressions, when compiled down, are very high performing. I would suggest that you build a composite expression, let the Regex engine optimize it, and have just a single check... something like:

string[] validators = {ComponentsResources.NorthAmericaAssetNumValidationRegex, ....};
var compoundValidator = new Regex("(" + string.join(")|(", validators) + ")");

Then, in your code, you can reuse that single regex just once:

public bool IsValidAssetNum(string assetNum)
{
    return compoundValidator.Match(assetNum).Success;
}

There are any number of ways you can add validators to the the system, config files come to mind as being an easy way to manage them without code changes.


Important:
Asking for the "best and shortest" code is a contradiction. If you write something as short as possible, chances are you're taking short-cuts in terms of error handling, maintainability, and readability. Take, for example these two snippets of code. Both do exactly the same thing, but one is so horribly obfuscated that nobody in their right mind would consider it to be good code:

$a = range('a', 'z');
for ($a=range('a','z'),$i=0,$j=count($a),$s='',$k=mt_rand()%j;$i<$j;++$i, unset($a[$k]))
{
    while (!isset($a[$k])) $k = mt_rand()%j;
    $s .= $a[mt_rand()%$j];
}
//compared to
$chars = range('a', 'z');//array of all chars to shuffle
$len = count($chars);//get the length, avoid calling count too many times
$string = '';//the string containing the chars in random order
for ($i=0;$i<$len;++$i)
{
    do
    {//keep generating a random key, until we find one that exists
        $k = mt_rand()%$len;
    } while(!isset($chars[$k]));
    $string .= $chars[$k];//add char to string
    unset($chars[$k]);//unset the char
}

Now I realize that this code is really rather pointless, but it's simply to prove a point. Which of these two snippets of code would you rather be confronted with, when trying to debug something? Or which snippet of code would be easier to explain? I don't know you, but assuming you're not a masochist, I'm going to assume you prefer the second version...
It contains comments, explaining what bit of code does what, it uses (more or less) meaningful variable names, and most of all, there isn't a single line of code that does more than it needs to. Cramming everything in one statement is the shortest route to introducing odd bugs, and because you've crammed everything into a one-liner, those bugs can prove tricky to fix.

Anyway, let's look at your code:

You have a fundamental flaw in your code: even if the page parameter is set, and is valid, the first statement of your code is overwriting it. Suppose the page parameter is 4, the first thing you do is:

$_GET['page'] = '01';//<-- reassignment

There's no way you'll ever get the actual requested page. I'd suggest you write a function to get the correct page number:

/**
 * @param array $params
 * @param string $key
 * @param array $filter
 * @param mixed $default = null
 * @return mixed
 * @throws \InvalidArgumentException
 */
function getValue(array $params, $key, array $filter, $default = null)
{
    if (!$params || !isset($params[$key])
        return $default;//no GET params, or key is not set, return default
    $value = $params[$key];//use the raw value
    //validate
    $validated = filter_var($value, $filter['type'], $filter['options']);
    if ($validated === false)
    {//validation failed
        throw new \InvalidArgumentException(
            sprintf(
                '%s is an invalid value',
                $value
            )
        );
    }
    return $validated;
}
//usage:
$page = getValue(
    $_GET,
    'page',
    array(
    'type' => FILTER_VALIDATE_INT,
    'options' => array(
         'min_range' => 1,//1 is valid, if user was on page 2, and requests page 1 again
         'max_range' => 10
    ),
    1//default value
);

Wrap this call in a try-catch block, and redirect the user if the exception is thrown. The benefit of this function is that you can easily re-use this function to validate other types of data:

$email = getValue(
    $_POST,
    'email',
    array(
    'type' => FILTER_VALIDATE_EMAIL,
    'options' => null
);
if ($email === null)
    //handle $_POST['email'] not set error

At first glance, this code seems slightly more verbose, but not much, and it's a "price" worth paying considering the benefits:

Reusable function
one call to validate $_GET, $_POST, $_COOKIE and $_SESSION keys
Can be used on any array (DB results, API responses)
Easy error handling (catch the exception, handle default returns if required)
If argument not set, get a usable default value back (like passing 1 in the page example as default value).
Maintainable code
This function might well be the first step towards building your own Request class.

But all in all, I'd suggest you look into existing paginator tools. There are plenty of them, some of them are really quite good, like the KnpLabs paginatorBundle.


If ComparisonIsTrue(thisPost, ComparisonOperator.NotEqualTo, goodCode) Then Me.Answer

I really don't like your GoTos...

If IsNull(sourceValue) Or IsNull(comparisonValue)
Or IsObject(sourceValue) Or IsObject(comparisonValue) Then
    ComparisonIsTrue = False
    Exit Function
End If

And gone are your gotos.