Get rid of the list. No, really, it's as simple as that. The sequence of is in factors will be non-decreasing, so essentially you could switch

System.out.print(Collections.max(primeFactors()));

with

List<Long> factors = primeFactors();
System.out.print(factors.get(factors.size() - 1));

While the list for prime factors might come in handy for other challenges, you're just interested in the largest, so it's fine to return just a single value:

private static long largestPrimeFactor(long n) {
    long largest = -1;
    for (long i = 2; i <= n; i++) {
        while (n % i == 0) {
            largest = i;
            n /= i;
        }
    }
    return largest;
}

Since you're interested in performance, you probably want to split the for into two parts to skip the unneeded even integers:

private static long largestPrimeFactor(long n) {
    long largest = -1;

    while(n % 2 == 0) {
        largest = 2;
        n /= 2;
    }

    for (long i = 3; i <= n; i = i + 2) {
        while (n % i == 0) {
            largest = i;
            n /= i;
        }
    }
    return largest;
}

Other than that, well done, and the correct approach. But just as in your previous code, ask yourself whether you really need the whole collection.


Using Scanner.nextInt() whilst ignoring rest of line

In order to remove the junk after the integer, you can make use of Scanner.skip(Pattern pattern). It allows you to skip over any set of characters that match a pattern:

scanner.skip(".*");

This method call will cause the Scanner to skip over any characters that match the pattern ".*"  .  The period character in a regular expression matches any single character.  The repetition character * causes matching zero or more of the previous character.  So the pattern .* will match zero or more of any characters.  Thus, it will skip over any characters currently on the stream. So now our code will look like:

    int myFirstInt = scanner.nextInt();
    // Ignore rest of line
    scanner.skip(".*");

    System.out.print("2) Enter an integer (and some junk afterwards): ");
    int mySecondInt = scanner.nextInt();
    scanner.skip(".*");
    System.out.print("3) Enter the third integer: ");
    int myThirdInt = scanner.nextInt();

    System.out.printf("\nFirst: %d, Second: %d, Third: %d\n",
                      myFirstInt, mySecondInt, myThirdInt);

It is a simple way to flush the stream so that it is clear of bad characters, and ready to be reused!


Determining the value of a position on an array based on its nearest datapoint known value

This is an application of rounding.

idx = int(round(float(pos) / step)) - 1

Note, however, that the result in case pos is exactly halfway into a step is different from your code, and also differs between Python versions.


Concept

imho you don't need build prob_space or normalize by max rank == 20
you only need

John: 1 ... 13^2
Joe:  13^2+1 ... 13^2+8^2
Averell: 13^2+8^2+1 ... 13^2+8^2+5^2
William: 13^2+8^2+5^2 ... 13^2+8^2+5^2+2^2
and choice a man having ranint(1, 13^2+8^2+5^2+2^2)

transform list [13**2, 8**2, 5**2, ...] to [13**2, 13**2+8**2, 13**2+8**2+5**2, ...] we can by accumulate
searching in this sorted list [13**2, 13**2+8**2, 13**2+8**2+5**2, ...] we can by binary search algorithm implemented in bisect module
the algorithm:

from collections import namedtuple
from itertools import accumulate
from random import randint
from bisect import bisect_left

Candidate = namedtuple('Candidate', 'name rank')

def pick_random_candidate(candidates):
    assert (len(candidates) > 0) # note: probably we want return None with empty list?
    squared_ranks_accumulated = list(accumulate(c.rank ** 2 for c in candidates))
    random_pick = randint(1, squared_ranks_accumulated[-1])
    return candidates[bisect_left(squared_ranks_accumulated, random_pick)]

if __name__ == "__main__":
    candidates = [Candidate(*t) for t in [('John', 13), ('Joe', 8), ('Averell', 5), ('William', 2)]]
    random_candidate = pick_random_candidate(candidates)
    print(random_candidate)

Implementation

better use from random import randint instead of import random
if you have randint(0, x - 1) you can replace it by randrange(x)
constants like 20 should be defined as variable, e.g. top_rank = 20 or even def pick_candidate(candidates, top_rank=20). Reason: if someone change 20 to 21 in next three months there are high probability that don't change comment (so better when comment explains top_rank not 20)
you can often define structure Candidate as namedtuple (dict is better only sometimes if have some dynamic fields to store)
what's with the empty list of candidates (exception KeyError is expected or something else should be?)


I don't see any reason for the added complexity of the second implementation. The Node class doesn't provide any methods or fields nor does it serve as a base class for your TreeNode1. It just makes naming the tree nodes worse: TreeNode is definitely a better name than Node.TreeNode1.

So in version 2 you end up with two classes:

The outer class Node does nothing useful.
The node class Node.TreeNode1 doesn't do anything a non-nested class couldn't do as well.

Even if you embed the TreeNode1 class into a more functional outer class, there isn't much benefit from static nesting.

So I'd definitely prefer implementation 1.

A nested class can be a good solution in cases where access to the enclosing class is useful, but I'd hide it from the API user, e.g. by exposing a Node interface which is internally implemented by the nested class.


Not that ugly. I've seen ugly code, and trust me, this is not ugly.

However, this is kind of a "God Class" that has more than a single responsibility, hence it violates SRP principle.

How to improve

Separate the class to:

ContentFetcher, which is responsible for fetching only

StoryParser, which parses the content and creates instances of your object model (Story[])

Both of the above should implement the Try.. pattern, so that the single method in the ContentFetcher has the following signature:

bool TryFetch(out string content){ /* code */ }

The same goes for StoryParser.

As for the fetcher itself

You can choose if the URL is either injected in the constructor, or is part of the method signature. Modern OOP coding is biased towards the constructor technique.
The code should implement the using (...) { ... } pattern for classes that implement the IDisposable interface, and be wrapped in a try-catch what so ever.

As for the parser itself

since rss is a format on top of xml, I don't think it's a good idea to parse it using regular expressions. Let the framework do the parsing by using either XmlDocument or XDocument. Or use an external library to parse the string for you (hopefully it's implemented by the above techniques, and not by using Regexes).
a try-catch might be needed here, too

Putting it all together

So finally, the class you have should use the above two classes (a fetcher and a parser), and then, getting the stories from the feed should look like this:

public Story[] Getstories()
{
    string content;
    if (!this.fetcher.TryGetContent(out content)) return null;
    Story[] stories;
    if (!this.parser.TryParse(out stories)) return null;
    return GetMostRecent5(stories, new StoryComparer());
}

As you can see, null is a special value for failure. You can change that to TryGetStories which returns a boolean and and out parameter if you want to avoid the special value of null.

The actual instances of fetcher and parser can be created by the class itself (in the constructor) and/or be injected to the class by the constructor. Let's see the injection pattern:

public class RssFeed
{
    private readonly ContentFetcher fetcher;
    private readonly StoryParser parser;

    public RssFeed(ContentFetcher fetcher, StoryParser parser)
    {
        if (null == fetcher) throw new ArgumentNullException("fetcher");
        if (null == parser) throw new ArgumentNullException("parser");
        this.fetcher = fetcher;
        this.parser = parser;
    }
}

As a final step of refactoring, you can extract the preparing code to its own method, moving the parsed stories to be part of the class' state:

private Story[] stories = null;

private bool Prepare()
{
    if (this.stories != null) return true;
    string content;
    if (!this.fetcher.TryGetContent(out content)) return false;
    Story[] temp;
    if (!this.parser.TryParse(out temp)) return false;
    this.stories = temp;
    return true;
}

public Story[] Getstories()
{
    if (!Prepare()) return null;
    return GetMostRecent5(this.stories, new StoryComparer());
}

Good luck!


Better way of checking if the current user already like a post

Have you created an index for likes.post_id? Note also that you can simplify that method by using has_many with the option through and  ActiveRecord#include?. That's what I'd write (with positive logic, I don't see why has_like_from? should perform a == nil):

class Post < ActiveRecord::Base
  belongs_to :user, :counter_cache => :count_post
  has_many :likes
  has_many :like_users, :through => :likes

  def liked_by?(user)
    like_users.include?(user)
  end
end


Changed a little bit input data:

n <- 60
set.seed(21)
a <- data.frame(
  DATE =
    rev(seq.Date(as.Date("2018-01-01"), as.Date("2018-06-15"), "days"))[1:n],
  OPERATION_STATUS = sample(c("PASS","FAIL"), n, replace = TRUE),
  CRIT_CODE = sample(c("A", "B", "C"), n, replace = TRUE)
)

Using data.table I would do it like this:

require(data.table)
setDT(a)
a[, group_i := DATE >= (Sys.Date() - 30)]
rates3 <- a[, .(
  Percent1 = round(sum(OPERATION_STATUS == 'FAIL') / .N * 100, 2),
  Percent2 = round(sum(OPERATION_STATUS[group_i] == 'FAIL') / sum(group_i) * 100, 2)
  ),
  keyby = CRIT_CODE]

rates3
#    CRIT_CODE Percent1 Percent2
# 1:         A    71.43    75.00
# 2:         B    63.16    66.67
# 3:         C    59.26    45.45

Presumably for large data one of the fastest approaches.

P.S. results changes depending on Sys.Date()

Names can be added directly:

rates3 <- a[, .(
  'Overall Percent' = round(sum(OPERATION_STATUS == 'FAIL') / .N * 100, 2),
  '30 Day Percent' = round(sum(OPERATION_STATUS[group_i] == 'FAIL') / sum(group_i) * 100, 2)
  ),
  keyby = .(Area = CRIT_CODE)]


There are several problems with your code. I will start with the method checkUsage(String[]). The check for the number of arguments should be if (args.length <= 2), with a <= instead of a < operator (or, alternatively, if (args.length < 3). Then, the check of the arguments themselves is faulty, because the condition you specify for an incorrect format will never evaluate to true. To check if none of two conditions hold true, you must either test

if (!(condition1 || condition2))

or

if (!condition1 && !condition2).

The two are equivalent, but be aware of operator precedence: The unary operator ! will be evaluated before || or &&, so in the first case, you have to surround the expression condition1 || condition2 with parentheses.

Next, you are comparing Strings using ==. This is dangerous, because == only checks for reference equality but not the contents of the Strings. You should rather use String.equals(Object) to compare Strings. In your case, you could even take advantage of String.equalsIgnoreCase(String), halving the number of method invocations and making the code easier to read.

So much for the method checkUsage(String[]). On to the methods shuffle(ArrayList) and max(ArrayList). I don't really see a point in defining these methods, since they do nothing but pass the argument to the respective method in Collections, so you might as well call Collections.max(Collection) and Collections.shuffle(List) directly from main(String[]).

The method removeDuplicates(ArrayList) unnecessarily creates a HashSet in the first line that will never be used, because the expression new HashSet<E>(list) passed to the ArrayList constructor in the second line creates a new HashSet that has nothing to do with the HashSet created in the first line, so the first line is completely redundant. Also be aware that HashSet.iterator() returns the elements contained in the Set in no particular order, so your method removeDuplicates(ArrayList) might not only remove duplicates, but also change the order of the List in general. Furthermore, you might want to consider defining the method parameter as a List (which is an interface) instead of an ArrayList (which is a class), because the method doesn't depend on the specific implementation of the passed List but only on its behavior, which is defined by the interface. That way, the method can also accept other implementations of the List interface and not only ArrayLists. And lastly, the name "removeDuplicates" is a bit misleading, since, unlike shuffle(List), the method doesn't actually modify the passed List but returns a new List without duplicates, leaving the passed List unmodified. Maybe "withoutDuplicates" would be better, or something like that.

Now, about the generic type parameter E. There is no point in defining it in the class declaration because the class itself does not depend on it, only your methods that accept an ArrayList (or List) as a parameter do. I suggest you remove it, because defining the class Prog7a with a generic type parameter <E> and then declaring methods that define a generic type parameter <E> again introduces ambiguity:

public class Prog7a<E> { /* If we instantiate a Prog7a<String>,
                            this E would be String */

    /* Now comes a method declaration that defines a generic
    type parameter <E> again. This newly defined parameter
    hides the parameter defined in the class declaration and is
    completely independent of it, so this method might
    very well accept a List<Integer>, even though the type
    of this class is Prog7a<String> */
    public <E> ArrayList<E> removeDuplicates(List<E> list) {
        // ...
    }
}

Regarding the actual problem at hand, which is the code repetition in your original code, the other two suggested solutions both seem appropriate to me, but I don't get the organization of slowy's code at all. Not only that the execution logic of the program is put inside a constructor, but the constructor actually doesn't serve any other purpose at all except establishing a type parameter, and the generic type parameter of the Prog7a class is unnecessary, as I already explained. This also means that your static methods can, indeed, remain static.


Determine all ways a string can be split into valid words, given a dictionary of all words

Honestly it looks like you're doing this wrong. Currently you're splitting the word into \$n^2\$ words and checking if they are in the dictionary. Rather than doing this you can traverse a Trie and loop through the input once. To do this you'd just need a 'partial words list' which is a set of Trie nodes. You then just need to make some lists for the output, and then return the one that you think is best. This can be a bit tricky to do, but the challenge is finding which output list(s) to append to, which you can do when adding new tries to the partial words list.

I'd implement this in the following way:

import collections.abc

class TrieNode(collections.abc.MutableMapping):
    def __init__(self, k):
        self._data = {}
        self._value = k
        self.end = False

    @staticmethod
    def build(iterable):
        root = TrieNode(None)
        for key in iterable:
            root[key] = True
        return root

    @property
    def value(self):
        return self._value

    def _keys(self, key):
        partial = ''
        for k in key:
            partial += k
            yield k, partial

    def _walk(self, data, key, *, build=False):
        if not key:
            raise ValueError()

        node = data
        if not build:
            for k in key[:-1]:
                node = node._data[k]
        else:
            for k, key_ in self._keys(key[:-1]):
                node = node._data.setdefault(k, TrieNode(key_))
        return key[-1], node

    def __getitem__(self, key):
        key, node = self._walk(self, key)
        return node._data[key]

    def __setitem__(self, key, value):
        k, node = self._walk(self, key, build=True)
        node = node._data.setdefault(k, TrieNode(key))
        node.end = value

    def __delitem__(self, key):
        key, node = self._walk(self, key)
        del node._data[key]

    def __iter__(self):
        return iter(self._data)

    def __len__(self):
        return len(self._data)

def word_break(word_string, words):
    words = TrieNode.build(words)
    output = {0: [[]]}
    partials = []
    for i, k in enumerate(word_string, 1):
        new_partials = []
        for partial in partials + [words]:
            partial = partial.get(k)
            if partial is None:
                continue

            new_partials.append(partial)
            if not partial.end:
                continue

            val = partial.value
            prevs = output.get(i - len(val))
            if prevs is not None:
                output.setdefault(i, []).extend([p + [val] for p in prevs])
        partials = new_partials
    return output[len(word_string)]

if __name__ == '__main__':
    words = word_break('catsanddog', {'cat', 'cats', 'sand', 'and', 'dog'})
    print(words)


Improving a function from using 1-D arrays to 2-D arrays as argument

Regarding your main question
From my point of view, yes, your current solution to allow legacy 1-D arrays to work with your new version is the best one I can think.
Rather funny: I just proposed a close solution in a PHP context question, less than 24 hours ago!
Another obvious method might be to keep the legacy function as is, and to write an almost identical one (simply expecting only 2-D arrays) with an alternative name.
But it doesn't seem better at all, notably because in case of changes regarding the core job they do, these two functions should be both updated!
Now since you asked for other possible improvements
I know that your example is not a real one, but since you implemented it "seriously" I propose you some points you might consider.
Performance
for (var i = 0; i < values.length; i++) {
  // ...
}

With the above code (your outer loop), values.length is evaluated for each step while looping, that may become significative when length is high.
A well known best practice is to avoid it, using this instead:
for (var i = 0, n = values.length; i < n; i++) {
  // ...
}

This way, values.length is evaluated only once.
Simplification
Anyway, instead of the above code you can use this alternative construction, resulting in a simpler code:
values.forEach(function(valuesSubArray, i) {
  // ...
});

NOTE: with this construction, you can also drop the previous declaration var valuesSubArray;.
Again simplification, and probably also performance
outputText = "";
for (var j = 0; j < valuesSubArray.length; j++) {
  outputText += valuesSubArray[j]
}

The above code (your inner loop) can be replaced by this simple statement:
outputText = valuesSubArray.join('');
NOTE: this results in 123 for a sub-array like [1, 2, 3], like does your outputText += valuesSubArray[j]. If you rather want to get 1,2,3 as stated by the initial explanation in your OP, you must use outputText = valuesSubArray.join(','); instead.
More simplification
At a higher level we can observe that the whole desired result outputDiv.innerHTML structure is the same as the outputText's one`:

each element is the current outputText
the separator is
 instead of a comma

So we can use join('
') at this level, applying it to an array of the generated outputTexts. This array can be obtained using reduce():
values.reduce(
  function(result, valuesSubArray) {
    result.push(valuesSubArray.join(','));
    return result;
  },
  []
);

NOTE: we don't need using i any longer, nor previously declaring outputText.
Finally
We can completely drop any variable declaration, and achieve the whole job with a "one-liner":

function writeToOutput(values, outputName) {
  if (!Array.isArray(values[0])) {
    values = [values]
  }

  document.getElementById(outputName).innerHTML =
    values.reduce(
      function(result, valuesSubArray) {
        result.push(valuesSubArray.join(','));
        return result;
      },
      []
    )
    .join('
');
}

writeToOutput([[1, 2, 3], [4, 5, 6]], 'outputs');


Here on Code Review, it's common to not receive some sort of feedback for a few hours. We all try our best to be on and answering!

I'm having a hard time deciding what you mean in your question. It's hard to understand... As of now, your class seems to be indescribably complex for such little functionality. You constructor is doing way to much work. It should really only be setting up the class that's being called! Login and authentication should either happen in separate methods, or even separate classes.

Have you not tested your class to see if $this works as it should? To the best of my knowledge, it shouldn't. And it seems unnecessary since you already made your variables public. Which they shouldn't be.

I'd also avoid throwing an exception from the constructor. It's uncommon and wouldn't really be expected.

This code because it seems jumbled and crammed. If the User class had less functionality (currently it's handling authentication, authorization, log outs, application functionality, and more) then it'd be easier for you to piece together the code. Let the code breathe, having different classes isn't a bad thing!

On a good note, the aesthetics of the code are very nice. Only a couple notes on the formatting:

Consistency is key. I noticed you have $useragent, $user_agent, and $u_agent. Which is it? Choose one and stick to it!
You've used die... Please don't use die. Handle the errors in a fashionable sense and give some proper error reporting to the user.
LoggedIn is not such a good namespace. More namespace info here.
Typically, class variables aren't all public. Using encapsulation is a good way to keep uniformity and conciseness.
Variables should give the reader some details about what the variable is meant for. What data type is $sign_in? What exactly is $btc_addr? $last_ajax of what, last Ajax call? $result is very ambiguous.
You could switch your conditionals around so you can simplify to the following code:

Notice I take out the false check, if it's an array, it won't be false.

$result = $this->fetch_details($e_mail,$p_word);
if (!is_array($result)) {
    throw new Exception('Invalid Username or Password');
}
$this->email      = $result['u_email'];
$this->hash       = $result['u_pass'];
$this->user_id    = $result['u_id'];
$this->user_agent = $u_agent;
$this->sign_in    = time();
$this->csrf_token = $this->csrf_create($this->sign_in,$this->hash);
$this->btc_addr   = $result['u_addr'];
$this->throttle   = 0;
$this->last_ajax  = ($this->sign_in - 5);
$this->verified   = $result['u_verified'];
$this->reputation = $this->fetch_rep($this->user_id);

Updates

When I say it has too much responsibility, I'm saying that the class is doing to many things unrelated to each other. Setting a bid is completely different than logging out. I'm saying that these things should be separated. The S in SOLID stands for Single responsibility (highly recommended read). You want your code to adhere to these principles. A class of User shouldn't be handling CSRF creation, and authentication, and data retrieval, and application business (i.e. bidding).
OWASP has graciously given some sample PHP CSRF information. They're using mt_rand, however, I'd have to agree with you that openssl_random_pseudo_bytes is a better choice. I can't see the benefit in infusing the timestamp and password into the string, but I also cannot see the downfalls.


Laravel Pagination with haversine formula in it

I think that working with a natural language style query builder has sent your implementation a little astray. I don't understand why you need to select a count of rows from a sub-queried result set when you could just count the rows returned from the query itself, without even pulling the result set down into the application.

Outside of that, I find your code hard to read.

Don't mix use of brackets on each side of if-else conditional
Consider using PSR-2 compliant styles

putting start of brackets for functions/methods, conditionals and looping constructs on same line.
Don't mix snake_case and camelCase within your user-written code.
One instruction per line.

Limit line lengths to ~80 characters.


Capturing optional regex segment with PHP

Consider your first pattern:

~/[0-9A-Za-z_-]+_archive/[0-9]+$~

Let's break it down:

/ a literal string /
[0-9A-Za-z_-]+ one or more of 0-9, A-Z, a-z, _ or -
_archive a literal string _archive
/ literal slash again
[0-9]+ one or more digits
$ the end of the string must follow the one or more digits

So basically you want to make #4 and #5 optional.  To be more specific, you want either both 4 and 5, or neither 4 nor 5.

Consider this:

(a[b]+)?

This means that you have one a followed by one or more b, and that this grouped a/b entity is optional.

Letting a be #4 and b be digits like in #5, we're left with:

(/[0-9]+)?

Or:

~/[0-9A-Za-z_-]+_archive(/[0-9]+)?$~

This will capture the entire group though, like /5:

php -r "preg_match('~/[0-9A-Za-z_-]+_archive(/([0-9]+))?$~', '/news_archive/5', $m); var_dump($m);"
array(2) {
  [0] =>
  string(15) "/news_archive/5"
  [1] =>
  string(2) "/5"
}

You can just add another group to remedy that though:

~/[0-9A-Za-z_-]+_archive(/([0-9]+))?$~

Example:

php -r "preg_match('~/[0-9A-Za-z_-]+_archive(/([0-9]+))?$~', '/news_archive/44', $m); var_dump($m);"
array(3) {
  [0] =>
  string(16) "/news_archive/44"
  [1] =>
  string(3) "/44"
  [2] =>
  string(2) "44"
}

You could technically make the outside group a non-capturing group (like (?:/([0-9]+))?), but I don't think the added complication is worth not grabbing the / part too.

(By the way, sorry if you're familiar with regex and you found this excessive.  I tend to take a very verbose approach to any regex related question :).)


Validating sign up pages using Selenium Python

This is not how the Page Object pattern should be implemented:

page object needs to have abstractions over the visual elements on a page
you should not be asserting things in the page object methods

There are, of course, many different Python+Selenium Page Object pattern implementations and I am not completely sure, which one is the One, here are some(1) of(2) them(3).

We can, at least, start with defining locators and then reusing them inside the methods, something along these lines:

class SignupPage(Page):
    cname_input = (By.ID, "cname")

    username_input = (By.ID, "cf_2727675")
    password_input = (By.ID, "cf_2697953")  # assuming this is password

    submit_button = (By.ID, "sbbut")

    def __init__(self, driver):
        super(SignupPage, self).__init__(driver)

    def submit(self):
        self.driver.find_element(*self.submit_button).click()

    def sign_up(self):
        self.driver.get("https://abc.com/s_csignup.jsp?token=XVtQHUUGYFFaRhNaXxJaQVBRZEl2EnBo")

        cname = self.driver.find_element(*self.cname_input)
        cname.send_keys("QA EXTERNAL")

        username = self.driver.find_element(*self.username_input)
        username.clear()
        username.send_keys("Test")

        password = self.driver.find_element(*self.password_input)
        password.clear()
        password.send_keys("Test")

        self.submit()

Or, even better, we can create a class for every Page Element, like suggested in the documentation.

Note that the assertion itself should be moved to the test case method, and, hence, your Page class should not be derived from the unittest.TestCase (or have the assertEqual method).

Also, here are some notes about the code style of the code in the question:

if your BaseTestCase class inherits unittest.TestCase (it should), there is no need for multiple inheritance. And, you would not need to override the setUp and tearDown methods:

class BaseTestCase(unittest.TestCase):
    # ...

class MatchingContactCompany(BaseTestCase):
    def test_matching_company(self):
        # ...

according to PEP8, a class name should start with a capital letter and be in camel case - call it SignupPage instead of signupPage
the test_* methods should be named according to the PEP8 method name convention - it should be test_matching_company instead of test_MatchingCompany
same note about your page object methods - use a lower case and separate words with underscore


Checking address fields for presence of a Post Office Box

There's 2 obvious places to clean this up a bit.  The first is the duplicated keyup handler and the second is the check for PO.

Most jQuery functions can be called on a collection of elements.  Since you are calling the same code on both your shipping address and billing address, we can combine them like so:

var $addresses = $('#checkout input[name="user_data[s_address]"]')
                 .add($('#checkout input[name="user_data[b_address]"]));

For the PO check, you can just use a regular expression:

//p, optional period, o
if(/p\.?o/i.test($value)) { ... }

So the whole thing becomes:

(function ($) {
    'use strict';

    // Check for PO Box text in address fields on checkout
    var $addresses = $('#checkout input[name="user_data[s_address]"]')
        .add($('#checkout input[name="user_data[b_address]"]')),
        message = "

We don't ship to PO Boxes. Sorry for the inconvenience.

";

    $addresses.after(message);

    $addresses.keyup(function () {
        var $value = $(this).val();

        if(/p\.?o/i.test($value)) {
            $(this).siblings('.message').removeClass('hidden');
        } else if ($value === '') {
            $(this).siblings('.message').addClass('hidden');
        }
    });

}(jQuery));

See: http://jsfiddle.net/6RnxG/7/


This isn't bad looking code. It's formatted nicely, and I think this is a good use of type hints.

My two main concerns are your naming, and your use of print.

Names should be snake_case according to PEP8. You started adhering to it, then reverted back to camelCase later. It can be a hard change to make if you're used to other languages, but it's proper for Python, and studies have shown that it's easier to read anyways.

I think you're "abusing" print here.

print_board is printing the board instead of returning a representation that can be used elsewhere. I'd change it to format_board (or stringify_board or something similar), and have it return a string instead of forcibly printing the board. It would be a fairly trivial change too. Just concatenate the different printed strings together, replace the print() calls with a "\n", and change your imperative for loop to a list comprehension that you give to join after. It would honestly probably be shorter and cleaner after those changes anyways.

Then elsewhere, like in solve, you're printing the results. I would instead return some kind of indicator value, like an Enum instead of printing there.

Why bother with limiting print? Testing and portability. Say you wanted to programmatically test print_board. You would need to intercept sys.stdin to get the printed text to compare it against a known string. This is both slower and more complicated than just having a function that returns a string in the first place. The same goes for solve. To test that's its operating correctly, you need to verify what it's printing instead of just checking the return value.

Forcing use of print also prevents you from using these function in any other context, like a Tkinter UI.

Return the data and let the caller decide how they want to use it.

If you really want a print_board function for convenience, just make a wrapper:

def print_board() -> None:
    print(format_board())

Lastly, instead of using strings to indicate piece types, I'd use an Enum. Right now, you have a strong "Q" to indicate a queen on the board. Strings can be easily typo'd though; enums can't. If the only two valid board piece options are an empty space and a queen, you should use an enum to not only make that explicitly stated, but to enforce it. Entering an invalid enum invalid enum value will lead to an error instead of code-dependant effects that may end lead to silent failures.

I also realized just as I was about to submit this that your print_board and backtrack functions are relying on the global board defined in the "main". Don't do this! If those functions require data like board, that data should be explicitly passed in as arguments. If you wanted to test those functions, you wouldn't be able to just generate a dummy board in the console and pass it in. You would need to modify the global, run the function, then remember to modify to global again before further testing. The less relience you have on global variables, the easier your code will be to test and comprehend. Ideally, functions should accept as arguments all the data that they require, and return all data that they produce. This isn't always feasible, but it's a good design choice to pick unless you have a good reason to rely on globals (like board) and side-effects (like print).

Now that I'm on my full computer, I'm able to take a better look at the code and play with it a little more.

First, here's the enum usage that I was referring to. Ignore my previous suggestion for solve. I realized that an enum wasn't really appropriate there (I'll show my alternate suggestion after). Basically, BoardSquare represents the total possible states of each square on the board, along with the string representations that they have:

from enum import Enum

class BoardSquare(Enum):  # A square on the board can either be a queen, or an empty space
    QUEEN = "Q"
    EMPTY = " "

With that, I decided to use some slightly more advanced type hinting and created an alias for the board:

from typing import List

Board = List[List[BoardSquare]]  # A Board is a list of lists of board squares

This, combined with the enum ensures that nothing except a QUEEN or EMPTY is ever put into a board. Attempting to do so will cause a warning. This helps prevent typos:

board: Board = [[BoardSquare.EMPTY] * side_length for _ in range(side_length)]
board[1][2] = "SOME INVALID DATA"  # Causes an "Unexpected types" warning

And here's my format_board that I came up with:

# A helper to neaten up format_board
def _format_row(row: List[BoardSquare]) -> str:
    return '| ' + ' | '.join(square.value for square in row) + ' |'  # .value is the string defined in the enum

def format_board(board: Board) -> str:
    """ Formats the board as a string """
    board_length = len(board)  # Instead of relying on the global SIZE, I'd just compute it
    print_side_length = 3 * (board_length - 1) + board_length + 4

    top_bottom_str = '-' * print_side_length  # Might as well save this instead of writing the same thing twice.

    # I'll admit, this got a little more convoluted than I thought it would. It's just nested called to `join `though.
    return top_bottom_str + "\n" \
           + '\n'.join(_format_row(row) + '\n' + top_bottom_str for row in board)

Yes, as the comments note, this got a little longer than I though it would. The need to translate the enum into a string using the generator expression necessitated breaking off the formatting of each row into its own function for readability.

After going around and touching up some other stuff (see the comments), here's the full code that I ended up with:

from typing import List
from enum import Enum

class BoardSquare(Enum):  # A square on the board can either be a queen, or an empty space
    QUEEN = "Q"
    EMPTY = " "

Board = List[List[BoardSquare]]  # A Board is a list of lists of board squares

# Make it easier to create a new board for testing purposes
def new_board(side_length: int) -> Board:
    return [[BoardSquare.EMPTY] * side_length for _ in range(side_length)]

# A helper to neaten up format_board
def _format_row(row: List[BoardSquare]) -> str:
    return '| ' + ' | '.join(square.value for square in row) + ' |'  # .value is the string defined in the enum

def format_board(board: Board) -> str:
    """ Formats the board as a string """
    board_length = len(board)  # Instead of relying on the global SIZE, I'd just compute it
    print_side_length = 3 * (board_length - 1) + board_length + 4

    top_bottom_str = '-' * print_side_length  # Might as well save this instead of writing the same thing twice.

    # I'll admit, this got a little more convoluted than I thought it would. It's just nested called to `join `though.
    return top_bottom_str + "\n" \
           + '\n'.join(_format_row(row) + '\n' + top_bottom_str for row in board)

def print_board(board: Board) -> None:
    """ Prints the board """
    print(format_board(board))

def is_valid(row: int, col: int) -> bool:
    """ Returns if a cell index is valid """
    return 0 <= row < GLOBAL_SIZE and 0 <= col < GLOBAL_SIZE

def is_safe(row: int, col: int) -> bool:
    """ Checks if the given index position is safe """
    # Checks if the column is safe
    for i in range(GLOBAL_SIZE):
        if i != row and global_board[i][col] != BoardSquare.EMPTY:
            return False

    # Checks if the row is safe
    for j in range(GLOBAL_SIZE):
        if j != col and global_board[row][j] != BoardSquare.EMPTY:
            return False

    # Checks if the diagonals are safe
    for k in range(GLOBAL_SIZE):
        if is_valid(row + k, col + k) and global_board[row + k][col + k] != BoardSquare.EMPTY or \
           is_valid(row - k, col + k) and global_board[row - k][col + k] != BoardSquare.EMPTY or \
           is_valid(row + k, col - k) and global_board[row + k][col - k] != BoardSquare.EMPTY or \
           is_valid(row - k, col - k) and global_board[row - k][col - k] != BoardSquare.EMPTY:

            return False

    return True

def backtrack(row=0, total=0) -> int:  # I changed this to int. It was bool before, but that was wrong
    """ Backtracks and fills checks for every possible combination """
    # If all rows are safely filled with queens
    if row == GLOBAL_SIZE:
        # print_board(global_board)  # Uncomment the code to print the current solution
        # input('Enter to continue... ')
        return 1

    for col in range(GLOBAL_SIZE):
        # If the current index is safe, check for the next row
        if is_safe(row, col):
            global_board[row][col] = BoardSquare.QUEEN  # Use the enums values here instead
            total += backtrack(row + 1)
            global_board[row][col] = BoardSquare.EMPTY

    return total

def report_solution() -> None:
    """ Calls backtrack and prints number of solutions """
    total = backtrack()

    print()

    if not total:
        print('No possible solution was found')

    elif total == 1:
        print('There is a total of 1 solution')

    else:
        print(f'There are a total of {total} solutions')

if __name__ == '__main__':
    GLOBAL_SIZE = int(input('Enter the size of the board: '))

    global_board = new_board(GLOBAL_SIZE)

    report_solution()


A little math goes a long way.

ngrams :: Int -> [a] -> [[a]]
ngrams n l = take (length l - (n - 1)) . map (take n) . tails $ l


Outwith the improved error handling as per the comments, another improvement on this be to write the hook using a more synchronous approach e.g.

#.git/hooks/prepare-commit-msg
#!/usr/bin/env node

const { readFileSync, writeFileSync } = require('fs')
const { execSync } = require('child_process')
const COMMIT_EDITMSG = process.argv[2];

const stdout = execSync('git symbolic-ref --short HEAD');
const message = readFileSync(COMMIT_EDITMSG, 'utf-8');
writeFileSync(COMMIT_EDITMSG, `${stdout.replace(/(-|_).*/, '')} ${message}`.replace(/\n/, ''));

This completely eliminates the need for callbacks and, naturally, if an error occurs the commit should be blocked - it's also a lot more succinct and easier to read.


Bernstein polynomial type for quadratic clipping

The below code uses Julia 1.0.  Full code as a Pkg3 project is available here.

Preliminaries

There's enough code for it to get its own module.  This also makes testing easier.

module Bernstein

using Polynomials

import Base: convert, promote_rule, show
import LinearAlgebra: dot, norm
import Polynomials: poly

Since we're in a module, we must define the exported things.  Since most of the things is just
overloaded methods, only the type remains.

export BernsteinPoly

You do this check so often, we can factor it out.  Alternative: using a separate type
for intervals.

macro checkinterval(α, β)
    :(@assert $(esc(α)) <= $(esc(β)) "Invalid interval")
end

Parametrization by a constrained type is better than fields of an abstract type.  But in the case of n and i, concrete Ints make more sense, since they represent natural numbers
always (this makes conversions below easier).
And I'm calling it BernsteinPoly, since it is a variant of Poly.

struct BernsteinPoly{T<:Number}
    n::Int
    i::Int
    α::T
    β::T
end

BernsteinPoly(n, i) = BernsteinPoly(n, i, 0.0, 1.0)

Just implementing show using print is the recommended way for custom pretty-printing. Here, we can reuse Polynomials.printpoly for nicer and more consistent formatting:

function show(io::IO, b::BernsteinPoly)
    print(io, "BernsteinPoly(")
    Polynomials.printpoly(io, poly(b))
    print(io, ")")
end

Conversions

get_p was essentially the conversion from BernsteinPoly to Poly.  We can replace this
by the implementation of proper convert methods.  The default parameters are unnecessary,
since already occuring defaulted in the BernsteinPoly constructor.

function convert(::Type{Poly{S}}, b::BernsteinPoly) where {S<:Number}
    n, i, α, β = b.n, b.i, convert(S, b.α), convert(S, b.β)
    @checkinterval α β

    return (binomial(n, i)
            * poly(fill(α, i))     # `fill` instead of list comprehension
            * poly(fill(β, n - i))
            * (-1)^(n - i)
            / (β - α)^n)
end

This allows you to just say convert(Poly, b), automatically reusing the inner type of b

convert(::Type{Poly}, b::BernsteinPoly{T}) where {T<:Number} =
    convert(Poly{T}, b)

While we're at it: conversion between different BernsteinPoly values

convert(::Type{BernsteinPoly{S}}, b::BernsteinPoly) where {S<:Number} =
    BernsteinPoly(b.n, b.i, convert(S, b.α), convert(S, b.β))

If we're handling different representations, we sometimes need to determine the "most general"
form, which is called promotion:

promote_rule(a::Type{BernsteinPoly{S}}, b::Type{Poly{T}}) where {S<:Number, T<:Number} =
    Poly{promote_type(S, T)}

promote_rule(::Type{BernsteinPoly{S}}, ::Type{BernsteinPoly{T}}) where {S<:Number, T<:Number} =
    BernsteinPoly{promote_type(S, T)}

Also add a method to the poly smart constuctor, which is now trivial:

poly(b::BernsteinPoly) = convert(Poly, b)

Linear Algebra

Now to the linear algebra part.  We could add methods to dot and norm from LinearAlgebra:

function dot(p::Poly{T}, q::Poly{T}, α = zero(T), β = one(T)) where {T<:Number}
    @checkinterval α β
    polyint(p * q, α, β)
end

And the norm induced by that inner product:

function norm(q::Poly{T}, α = zero(T), β = one(T)) where {T<:Number}
    @checkinterval α β
    √dot(q, q, α, β) / (β - α)
end

But such "overloads from outside" are frowned upon.  As of writing this, there's a norm method
in Polynomials, but not dot.  There's an issue about that; basically, dot is not
unique, hence we need to specify the intervals each time here.

For Bernstein polynomials, on the other hand, the inner product is defined uniquely, if I
understood correctly.

function dot(b::BernsteinPoly{T}, q::BernsteinPoly{T}) where {T<:Number}
    @checkinterval b.α q.α
    @checkinterval b.β q.β
    m, i, n, j, α, β = b.n, b.i, q.n, q.i, b.α, b.β
    (β - α) * binomial(m, i) * binomial(n, j) / ((m + n + 1) * binomial(m + n, i + j))
end

And the induced norm, as before.

function norm(b::BernsteinPoly)
    √dot(b, b) / (b.β - b.α)
end

As the last remaining question, how to do cross-type inner products.  If dot is defined for
Poly as written above, we can use dot(promote(p, q)..., α, β).  But it's difficult to get
that working as a method.  I tried

dot(p::Union{Poly{T}, BernsteinPoly{T}}, q::Union{Poly{T}, BernsteinPoly{T}},
     α = zero(T), β = one(T)) where {T<:Number} =
     dot(promote(p, q)..., α, β)

but that doesn't work.  It's probably not recommended to do that anyway.  Use promote
explicitely where necessary.

Example output

julia> B = BernsteinPoly(3, 2)
BernsteinPoly(3.0*x^2 - 3.0*x^3)

julia> Q = BernsteinPoly(4, 3)
BernsteinPoly(4.0*x^3 - 4.0*x^4)

julia> using LinearAlgebra

julia> dot(B, Q)
0.07142857142857142

julia> norm(B)
0.29277002188455997

end # module


Handler for an Android form to calculate a cross product

I expect x/y 1-3 are textfields, though not enough context to be entirely certain, going from that assumption:

Create a helper method to check for value:

private boolean hasValue(TextField field) {
    return !field.getText().toString().isEmpty();
}

Store all textfields in an array.
Loop through and validate each one.

for (TextField field : textFields) {
   if (!hasValue(field)) {
      field.setError("needs value");
      field.requestFocus();
   }
}

Depending on your needs, I would apply this to use break, and perhaps apply it as a boolean returning method that ensures a validated state before continuing application logic.

Once the validation is done and completed (why a boolean returning method for step 3 could be helpful), proceed with the application logic.


Movie repository for storing movies based on country

One thing - this design is based on a false premise - that there is only ever a single title within a given country. See for example this movie which has 3 USA titles (albeit only one, final, official title). This can be fixed by changing the Country key of the hash map to a TitleType (which will often be just a country).

Another problem is that Movie isn't really an object - it doesn't implement any member functions. In fact, your RottenTomatoesTitleFinder works by directly manipulating Movie properties rather than calling Movie member functions. This is a violation of basic OO principles.


You could use the following solution unless it's important to call initialize in "create_author".

# spec/helpers/create_author.rb
module CreateEntity
  def create_entity(klass, params = {}, defaults = {})
    opt = defaults.merge(params)

    entity = klass.allocate
    opt.each do |key, value|
      entity.instance_variable_set("@#{key}", value)
    end
    entity
  end

  def create_author(params = {})
    create_entity(Author, params, {
      name: "Ford",
      filename: "Ford",
      website: 'www.ford.com'
    })
  end
end

create_author(name: "Ford 1")


Handling a text field and submit button with Ajax

There are two schools of thought

Programmatic
Declarative

Your example here is programmatic, where JavaScript is binding events after the DOM load. The problem I have with programmatic is, using your words, although it "keeps the behavior away from the markup" it moves the markup into the behavior. The interface that is needed to reuse the same JavaScript is now tied to what is defined on the page. Using declarative, your example being onclick="something(args);", I can more easily follow a Model View Presenter (MVP) pattern where the view simply forwards all events to the Presenter to perform the business logic.

Here the events can be organized into a class object to remove them from the global namespace. Scope can be controlled by passing in the model as a parameter.

presenter.js

function Presenter(parameter) {

  // private variables
  var myVar;

  // public method
  this.submit = function() {
  };

  // private method
  function doSomething() {
  }
}

page.html

...
<script type="text/javascript" src=".../presenter.js"></script>
<script type="text/javascript">
  var presenter = new Presenter(...);
</script>
...
<button onclick="presenter.onButtonClick();">Click me</button>


The functionality you have implemented in your “compact” is generally known as white-space normalization.

Get rid of redundant functions

You have a lot of functions. While breaking complicated logic up into manageable bits is a good thing, there is also a point where it becomes too much and hurts maintainability rather than helping it.

For example, the only use of ltrim_white is in trim_white which consists of a single line calling that function. You could have equally well put all the code into trim_white directly. ltrim_white also is a misnomer because unlike its name suggests, it trims white-space from both sides, not just from the left.

const char *skip_space(const char *str, int direction)
{
    if (direction == 1) {
        while (isspace(*str)) { ++str; }
    } else if (direction == 0) {
        while (isspace(*str)) { --str; }
    }
    return str;
}

This function doesn't really buy you anything. Making a function call

s = (char *) skip_space(s, 1);

isn't really simpler than writing

while (isspace(*s)) ++s;

directly. And the latter form saves you the headache figuring out what that 1 as second parameter means. As a bonus, it saves a branch and avoids the const trouble. If you really want a dedicated function, provide skip_space_forward and skip_space_backward instead of introducing the second parameter.

Make auxiliary functions static

Those auxiliary functions that you determine are in fact useful and should be kept, should still be private to your implementation and not pollute the global name-space. Therefore, you should declare them static. As a nice bonus, this might also make your code run faster (for free).

Put the standard library to good use

The <string.h> standard library header provides highly optimized functions for dealing with memory. Use them. In particular, memmove and strlen will come in handy.

Be const-correct

As you have already realized yourself, the adding and removing of const has become a total mess. You should only add const where you can, not at all cost. It is far better to have an internal pointer being not const even if you don't need to modify the pointed-to object than it is to repetitively cast const away. Once you start casting, const doesn't buy you anything in terms of code correctness.

If you have a function like skip_space, that takes a pointer to a buffer and returns a pointer into that buffer without modifying the buffer, it is good to keep the buffer const. Unfortunately, when you call skip_space with a non-const pointer, what you get back is always const and you cannot use the pointer to write through it even though you know it would be safe. This can be solved without a cast while still keeping the buffer skip_space operates on const, though: use the returned pointer to compute an index and use that one!

char buffer[] = "the quick brown fox";         // mutable buffer
const char *const p = skip_space(buffer, 1);   // pointer to const
const ptrdiff_t i = p - buffer;                // just an integer
buffer[i] = 'X';                               // perfectly fine now

If you have a decent compiler, it should be able to optimize the additional arithmetic away while still being able to verify the const-correctness of your code.

Don't over-generalize

NUL terminated character strings are so prevalent throughout C that you can safely assume the convention is here to stay. By spelling out '\0', you make your code actually more readable than by using a constant like TERMINATOR.

If you really want generality, make the caller pass in a pair of pointers. (If you have ever used the C++ <algorithm> standard library, this will be very familiar to you.) Then your function also works with arrays that are not terminated at all. You can provide a convenience function that only accepts a single pointer (that has to point to a terminated array in this case, of course) and uses rawmemchr (if you have it) or strlen to find the end. Then it calls the generic two-argument version.

Actually, a more useful generalization would probably be to accept a function pointer to use in place of isspace. Such indirect calls can have a performance penalty, though.

Consider pointer arithmetic

Instead of &p[n - i] you can just write p + n - i. I find this much more readable.

Modify pointers with care

Your trim_white function trims space from the beginning by simply adding an offset to the pointer. While this is super-fast, there is a big downside. If I call your function with a pointer that I obtained through malloc, I still have to keep the original pointer along with the pointer to the trimmed buffer. I need the former to pass it to free when I no longer need the string. I'm sure I will confuse them all the time.

Instead of advancing the start pointer, you could actually move the bytes of the string to the beginning. While this might seem costly at first, note that it doesn't actually increase the asymptotic complexity of your function. You already do at least one linear traversal (via strlen) and in the worst case (string is all-white-space) a second one finding the cutoff points. So adding a third one is not that bad. Actually, since you only need to move those bytes that are not white-space, the moving cost balances with the testing cost so you traverse the string exactly twice (regardless of its data) and the worst-case cost remains the same.

strlen             |---------------------------------------------------->|
skip_forward       |------------------->                                 |
skip_backward      |                                           <---------|
data               |␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣The␣quick␣brown␣fox␣...␣␣␣␣␣␣␣␣␣␣|
memmove            |                    <----------------------          |

Be sure to move the bytes with memmove rather than memcpy so it will be valid to pass the same buffer as input and output. (memcpy may only be used if the buffers are guaranteed to not overlap.)

Let the caller decide how to allocate memory

A white-space trimming / normalization function can be useful in a lot of contexts even when dynamic memory is not available or desirable. Allocating memory should not be one of your function's concerns. Instead, have the caller pass in a buffer where you will place the result into.

Since trimming / normalizing white-space can reduce but never enlarge the length of a string, a caller can easily determine the needed size of the buffer upfront by passing a buffer as long as the input string. They can even pass the same pointer twice and trim / normalize the string in-place! If the buffer was dynamically allocated and the string contained a lot of white-space, the caller might decide to realloc it afterwards so to give back the now-unused memory. Or maybe they have other smart options available. Again, your function should not be concerned with this. String manipulation already is a full-time job.

If you let the caller pass in the source and destination buffer, you don't have to return it any more. Instead, you can return something more interesting. For example, a pointer to the end of the result string. This could be useful if the caller wants to know the length of the new string. Having the pointer to its end, they can do so with a single subtraction rather than having to loop over the bytes (aka call strlen).

Recognize state machines

Some algorithms can be written in a more compact way if you think of them as state machines. Normalizing white-space is such an algorithm. It iterates over all characters of the input from left-to right and performs an action on each character depending on its internal state. There are three states.

PRE where all we have seen so far is white-space. As long as we continue to see white-space, we do nothing. Once we see a character that is not white-space, we copy it to the output buffer and switch to the
INTRA state where the last character we have seen was not white-space. If we see another white-space character, we copy it to the output buffer and remain in the INTRA state. If we encounter a white-space character, we transition into the
INTER state where the last character we have seen was white-space but we have also already seen non-white-space characters before. If we see a white-space character in this state, we do nothing. If we see a non-white-space character, we first append a single blank to the output buffer and then the current character; then we go back into the INTRA state.

Note that the only time we actually do something when we see white-space is in the INTRA state.

Not only is implementing the algorithm as such a state machine simpler and more elegant, it will also be more performant because we only iterate over each (the input and the output) buffer exactly once from left to right. Caching hardware loves such memory access and will honor it with amazing speed.

Put it all together

Combining all of the advice from this review, I'd suggest you'll end up with an implementation like this.

For trimming…

char *
trim_space(const char *const src, char *const dst)
{
  size_t first = 0;
  size_t last = strlen(src);
  size_t length = last - first;;
  if (length > 0)
    {
      while (isspace(src[first]))
        ++first;
      while ((last > first) && isspace(src[last - 1]))
        --last;
      length = last - first;
      memmove(dst, src + first, length);
    }
  dst[length] = '\0';
  return dst + length;
}

…and for normalizing white-space.

char *
normalize_space(const char * src, char * dst)
{
  typedef enum { states_pre, states_intra, states_inter } states;
  states state = states_pre;
  int c;
  while ((c = *src++) != '\0')
    {
      if (isspace(c))
        {
          if (state == states_intra)
            state = states_inter;
          continue;
        }
      switch (state)
        {
        case states_pre:
          *dst++ = c;
          state = states_intra;
          break;
        case states_intra:
          *dst++ = c;
          break;
        case states_inter:
          *dst++ = ' ';
          *dst++ = c;
          state = states_intra;
          break;
        }
    }
  *dst = '\0';
  return dst;
}


Validating username, password, and email in PHP

May this below class will help you.  Put this Valiation class in file named as Validation.php file.

<?php
/**
 * This class will provide server side validation for different rules with custom
 * provided message for respective rule.
 *
 * @author: Alankar More.
 */
class Validation
{
    /**
     * Posted values by the user
     *
     * @var array
     */
    protected static $_values;

    /**
     * Rules set for validation
     *
     * @var array
     */
    protected static $_rules;

    /**
     * Error messages
     *
     * @var array
     */
    protected static $_messages;

    /**
     * To send response
     *
     * @var array
     */
    protected static $_response = array();

    /**
     * For storing HTMl objects
     *
     * @var array
     */
    protected static $_elements;

    /**
     * Html object
     *
     * @var string
     */
    protected static $_inputElement;

    /**
     * Value of Html object
     *
     * @var mixed (string|boolean|integer|double|float)
     */
    protected static $_elementValue;

    /**
     * Name of validation rule
     *
     * @var string
     */
    protected static $_validationRule;

    /**
     * Value of validation rule
     *
     * @var mixed (string|boolean|integer|double|float)
     */
    protected static $_ruleValue;

    /**
     * Initializing class
     *
     * @param array $inputArray
     * @param array $values
     */
    public static function _initialize(array $inputArray, array $values) {
        self::$_values = $values;
        self::$_response = array();

        self::generateArrays($inputArray);
        return self::applyValidation();
    }

    /**
     * Separating rules and values
     *
     * @param array $input
     */
    public static function generateArrays(array $input) {
        self::$_messages = $input['messages'];
        self::$_rules = $input['rules'];
    }

    /**
     * Applying validation for the form values
     *
     */
    public static function applyValidation() {
        foreach (self::$_rules as $rk => $rv) {
            $_element = self::$_rules[$rk];
            if (is_array($_element)) {
                foreach ($_element as $key => $ruleValue) {
                    if (!self::$_elements[$rk]['inValid']) {
                        $method = "_" . $key;
                        self::$_inputElement = $rk;
                        self::$_elementValue = self::$_values[$rk];
                        self::$_validationRule = $key;
                        self::$_ruleValue = $ruleValue;

                        self::$method();
                    }
                }
            }
        }

        if (count(self::$_response) == 0) {
            self::$_response['valid'] = true;
        }

        return self::$_response;
    }

    /**
     * Method to check wheather the input element holds the value.
     * If not then assingn message which is set by the user.
     *
     */
    protected static function _required() {
        if (self::$_ruleValue) {
            if (trim(self::$_elementValue) == NULL &&
                strlen(self::$_elementValue) == 0) {
                self::setErrorMessage("Field Required");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * Maximum length of input
     *
     */
    protected static function _maxLength() {
        if (self::$_ruleValue) {
            if (strlen(trim(self::$_elementValue)) > self::$_ruleValue) {
                self::setErrorMessage("Enter at most " . self::$_ruleValue . " charachters only");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * Minimum length of input
     *
     */
    protected static function _minLength() {
        if (self::$_ruleValue) {
            if (self::$_ruleValue > strlen(trim(self::$_elementValue))) {
                self::setErrorMessage("Enter at least " . self::$_ruleValue . " charachters ");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * Allow alphabets only
     *
     */
    protected static function _number() {
        if (self::$_ruleValue) {
            $str = filter_var(trim(self::$_elementValue), FILTER_SANITIZE_NUMBER_INT);
            if (!preg_match('/[0-9]/', $str)) {
                self:: setErrorMessage("Enter numbers only");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * Allow alphabets only
     *
     */
    protected static function _alphabetsOnly() {
        if (self::$_ruleValue) {
            $str = filter_var(trim(self::$_elementValue), FILTER_SANITIZE_STRING);
            if (!preg_match('/[a-zA-z]/', $str)) {
                self:: setErrorMessage("Enter alphabates only");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * Allow alphabets and numbers only
     *
     */
    protected static function _alphaNumeric(){
        if (self::$_ruleValue) {
            $str = trim(self::$_elementValue);
            if (!preg_match('/[a-zA-z0-9]/', $str)) {
                self:: setErrorMessage("Alphanumeric only");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * To check enter email is valid
     *
     */
    protected static function _email(){
       if (self::$_ruleValue) {
            $str = filter_var(trim(self::$_elementValue), FILTER_VALIDATE_EMAIL);
            if (!$str) {
                self:: setErrorMessage("Enter valid email");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * To check enter url is valid
     *
     */
    protected static function _url(){
       if (self::$_ruleValue) {
            $str = filter_var(trim(self::$_elementValue), FILTER_VALIDATE_URL);
            if (!$str) {
                self:: setErrorMessage("Enter valid URL");
                self::setInvalidFlag(true);
            } else {
                self::setInvalidFlag(false);
            }
        }
    }

    /**
     * Setting invalid flag for every element
     *
     * @param boolean $flag
     */
    private static function setInvalidFlag($flag) {
        self::$_elements[self::$_inputElement]['inValid'] = $flag;
    }

    /**
     * Setting error message for the input element
     *
     * @param string $message
     */
    private static function setErrorMessage($message) {
        if (self::$_messages[self::$_inputElement][self::$_validationRule]) {
            $message = self::$_messages[self::$_inputElement][self::$_validationRule];
        }
       array_push(self::$_response, ucfirst($message));
    }
}

You can use this class in your application as below:

<form name="frmTest" id="frmTest" action="" method="POST">
    <input type="text" name="first_name" id="first_name" value = "" />
    <button name="submit" value="Submit" type="submit" >Submit</button>
</form>

<?php
require_once 'validation.php';
// Rules specification.
$rules = array('method' => 'POST',
    'rules' => array('first_name' => array('required' => true)
    ),
    'messages' => array('first_name' => array('required' => 'Please enter first name')
    )
);

$userPostedData = $_POST;
$response = Validation::_initialize($rules, $userPostedData);

// if some error messages are present.
if (!$response['valid']) {
    // it will give you the array with error messages.
    echo "<pre>";
    print_r($response);
} else {
    // all applied validations are passed. You can deal with your submitted information now.
    echo "<pre>";
    print_r($_POST);
}
?>


File Exists Script Task for SQL Server SSIS

Yes, it's okay. If you need to catch any exception then you should essentially catch them all.

The reason you typically avoid this and use the most concrete exceptions possible is to provide exception-specific behaviour: an accurate log message or a different continuation once it has been logged.

If all your exceptions are handled the same way then you can just use the catch-all. Note that you can always add a specific handler afterwards because the catch clauses are evaluated linearly.


Convert the from to a single unit, and convert that single unit to to. You don't have to compute conversions for every single pair.


Finding objects with even references tidier

I'm not sure if you're tied to having the method signature public static ArrayList<Integer> evenList(ArrayList<Integer> tList) and if you have to use the deepClone method you've got here, but if you aren't tied down to these restrictions, there are cleaner ways of doing this.

Firstly, one of the main points of recursion is using the stack to store state - this doesn't seem to really come through in your example. Let's think about the problem a bit: we want to go over each element in our list, adding that element to another list if the index of that element is even. How would we do this in "normal" code? Well, we'd just loop over the List with a for loop, probably:

(Note: I use List<Integer> here instead of ArrayList<Integer>. This may not make sense to you yet - if so, just mentally replace every List<Integer> with ArrayList<Integer>.)

public static List<Integer> evenList(List<Integer> tList)
{
    List<Integer> result = new ArrayList<Integer>();
    for(int i = 0; i < tList.size(); ++i) {
        if(i % 2 == 0) {
            result.add(tList.get(i));
        }
    }
    return result;
}

So converting this to recursive code, what state do we store in the function that we can store on the stack instead? Well, both the result and the index, i. So instead of creating a new List that we return, let's pass both of those in as parameters instead:

public static void evenList(List<Integer> tList, List<Integer> result, int index)

So, with this recursive method, how will we know when to stop? Well, exactly like in our for loop: when our index is at tList.size():

public static void evenList(List<Integer> tList, List<Integer> result, int index)
{
    if(index < tList.size()) {
       ...
    }
}

Ok, so what about the logic? Well, it hasn't really changed much - we still want to do the exact same thing, that is, if index is even, add the element at that index to our result list:

public static void evenList(List<Integer> tList, List<Integer> result, int index)
{
    if(index < tList.size()) {
        if(index % 2 == 0) {
            result.add(tList.get(index));
        }
    ...
}

Now, we need a call to the function itself (otherwise it wouldn't be recursive!), but what parameters do we pass through? Well, we always need tList, so that should go through. We want to keep adding to the same result, so that should go through. However, our index needs to change - we want to test the next element - so that should be ++index. So our final function looks like:

public static void evenList(List<Integer> tList, List<Integer> result, int index)
{
    if(index < tList.size()) {
        if(tList.get(index) % 2 == 0) {
            result.add(tList.get(index));
        }
        evenList(tList, result, ++index);
    }
}

I'm not really sure why your professor has you using clone methods here - it's really inefficient. Every single recursive call, you call deepClone on the List you pass in - this is a lot of wasted effort.

In fact, if we were being really clever here, we would see that every second element gets added to our return list, so we can skip one of the if checks:

public static void evenList(List<Integer> tList, List<Integer> result, int index)
{
    if(index < tList.size()) {
        result.add(tList.get(index));
        index += 2;
        evenList(tList, result, index);
    }
}

Of course, this only works properly when the user passes in an even initial value, presumably 0. So let's make sure that happens. Let's make this method private and supply the starting index:

private static void evenList(List<Integer> tList, List<Integer> result, int index)
{
    if(index < tList.size()) {
        result.add(tList.get(index));
        index += 2;
        evenList(tList, result, index);
    }
}

public static void evenList(List<Integer> tList, List<Integer> result)
{
    evenList(tList, result, 0);
}

If you are tied to the original method signature, well, I've typed a lot of stuff for not much good I suppose, although I'd have to question why your professor had made you do it this way.


You are using global variables and connecting them with the functions StateFalse and StateTrue. It would be better to read and write the configuration options to a file.

def set_option(value):
    with open(CONFIG_FILE,"w+") as f:
        f.write(value)

def get_option():
    with open(CONFIG_FILE) as f:
        return f.read() == "True"

Where CONFIG_FILE is a filename of your choice that you choose to store the "state" (maybe you should find a better name).


I just posted on your other post about this, use:

$("input[type=checkbox]:checked:not(.checkall)")

This is the 'regular' way to check for input tags of a particular type, it's much clearer than your way. I'm not sure what the significance of the .checkbox class is but it seems like it's not necessary to my.

I also recommend you cache your check boxes in a variable and search that multiple times. That way you're only searching the check boxes each time instead of the whole DOM.

// in document ready
var checkboxes = $('input[type=checkbox]');

// When you need to find the checked check boxes
var checked = checkboxes.find(':checked:not(.checkall)');


Pick the best combination of n choose k models

comments

comments should explain why you do something, not what you do. # Append R-Squared TO R-Squared list adds nothing of value. On the contrary, it uses vertical space, and if ever you change something of the code you will need to change the coàmments as well

# This function takes in a subset of a dataframe representing independent
# variables (X) and a column for dependent variable (Y). This function fits
# separate models for each possible combination of the k predictors (which is
# based on the column length of X) and then select the best subset. The
# resulting output is a dataframe.

could be the docstring of the method if it were correct. This function does not return a DataFrame, but only prints the results

functions

Now you have 1 monster function that:
- calls the test
- aggregates the values
- displays the results

Better would be to split this

getting the results

instead of having to append the results to 4 lists, I would extract this to a generator that yields a dict and then use something like  DataFrame.from_records to combine this.

powerset

what you do here:

for k in range(1, len(X.columns) + 1):
        # Looping over all possible combinations: from 11 choose k
        for combo in itertools.combinations(X.columns,k):

looks a lot like the powerset itertools-recipe, so let's use that one:

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))

def generate_combo_comparisons(X, Y):
    for combo in powerset(X.columns):
        if not combo:  # the first combo is empty
            continue
        RSS, R_squared = fit_linear_reg(X[list(combo)], Y)
        yield {
            "No_of_Features": len(combo),
            "RSS": RSS,
            "R-Squared": R_squared,
            "Features": combo,
        }

To get the maximum indices of each group, you can use groupby.idxmax

You add columns 'min_RSS'  to the original DataFrame. Better here would be to generate a new summary DataFrame

def subset_results(X, Y):
    df = pd.DataFrame.from_records(
        data=list(generate_combo_comparisons(X, Y)),
        index=["No_of_Features", "RSS", "R-Squared", "Features"],
    )

    summary = df.groupby("No_of_Features")["R-Squared"].agg(
        {"RSS": "min", "R-Squared": "max"}
    )
    df_min = df.loc[df.groupby("No_of_Features")["RSS"].idxmin()]
    df_max = df.loc[df.groupby("No_of_Features")["R-Squared"].idxmax()]
    return df, df_min, df_max, summary

And then you can pass these results on to the plotting function


Saving rcx is usually not necessary, it is not callee-save in common calling conventions. On Linux (and similar) rdi also does not need to be saved, I guess you're using that since the Win64 calling convention does not pass an argument in rdi. You can save them anyway if you want, which can be useful if you're using custom calling conventions. Saving an even number of registers makes the stack not-16-aligned though, you will probably get away with that now, but for example if you call some function that uses XMM registers it may save them at locations that it assumes are aligned (and there are some other cases where it causes trouble).

xor rcx, rcx
mov rcx, -1

The xor is not useful, rcx does not need to be zeroed before overwriting it for correctness reasons, and simply mov-ing into a 64 (or 32) bit register already has no dependency on the previous value. By the way, when you do want to zero a 64bit register, you can use a 32bit xor since writing to the low 32 bits of a register zeroes out the top half of the 64 bit register. There is not really an immediate performance difference, but using the 32bit version often lets you save the REX prefix, unless of course one of the "numbered registers" is an operand.

Because -x - 1= ~x + 1 - 1 = ~x (using the definition of two's complement, -x = ~x + 1) and you don't use the flags set by the sub,

neg rcx
sub rcx, 1
mov rax, rcx

is equivalent to:

not rcx
mov rax, rcx

So all combined, this function could be simplified slightly to (assuming saving rdi and rcx is useful):

strlen:
    push rdi
    push rcx
    mov rcx, -1
    xor eax, eax
    repne scasb
    not rcx
    mov rax, rcx
    pop rcx
    pop rdi
    ret


A recursive_transform for std::array with various return type

Ensure you pass by const reference consistently
The main problem with your code was that you didn't make the std::array overload take the input by const reference:
auto recursive_transform(std::array<T, S>& input, const F& f)

Just add const! See this Godbolt link with the nested std::arrays working.
Prefer using std::begin() and std::end()
It doesn't really matter if you only want to support containers from the standard library, but when writing templates, prefer using std::begin() and std::end() instead of ->begin() and ->end(). The advantage is that if you are using a non-standard container somewhere that doesn't provide begin() and end() member functions, it will still be possible to overload the out-of-class std::begin() and std::end() functions to add iterator support to that class. If you use it in your algorithm templates, then your algorithms will also support those non-standard classes.


Is this a correct implementation of quicksort in C?

The most valuable feature of quicksort is that it sorts in-place, without a temporary array. The average space complexity quicksort is logarithmic, whereas the one of your solution is linear. The time complexity is also affected by the copying from temporary back to original.

NB: If you can afford a linear temporary, don't use quicksort. Mergesort will win hands down: it doesn't have a worst case, and besides it is stable.
Choosing middle element for the pivot, while harmless, doesn't avoid the worst case. The performance of the quicksort is affected not by where the pivot is chosen, but by where it lands after partitioning. Worst case arises when they consistently land near the edges of the array.
I don't see the need to treat left of pivot and right of pivot separately:

Swap the pivot with the first element (`array[0]` now holds the pivot)
Partition the entire [1..length) range in one pass
Swap the `array[0]` (which holds the pivot) with `array[length_small]`.

A length of the array should be size_t. There is no guarantee that unsigned int is wide enough to represent a size of a very large array.
The code before the recursive call implements an important algorithm, namely partition and deserves to be a function of its own. Consider

void quicksort(int *array, size_t length)
{
    if (length <= 1) {
        return;
    }
    size_t partition_point = partition(array, length);
    quicksort(array, partition_point);
    quicksort(array + partition_point + 1, length - partition_point - 1);
}

Further down, you may want to implement two improvements:

Recursion cutoff: when the array becomes small enough, insertion sort performs better
Tail call elimination (not really necessary, the C compilers are good in it)


I think you should use Concat instead of StringBuilder:

public static string ToPascalCase(this string s)
{
    var words = s.Split(new[] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries)
                 .Select(word => word.Substring(0, 1).ToUpper() +
                                 word.Substring(1).ToLower());

    var result = String.Concat(words);
    return result;
}

This solution should not be as fast as manually looping through the original string, but I think it is much easier to read and follow. Unless you do those convertions like 1000000 times per second, you should not complicate things.


Interesting question,

I think the first thing to do is read this.

You could replace this:

if (req.url.indexOf(API_PATH) == 0){
  //Lots of code
}else{
  next();
}

To

if (req.url.indexOf(API_PATH) != 0){
  next();
  return;
}
//Lots of code,with one less level of indentation

This early exit makes the rest of the code look less busy.

Furthermore, in cases like this

req.logger.log('error', 'Error authenticating', {
  error: {
    message: e.message,
    stack: e.stack
  }
});

You should notice that the object you build has the exact same property names as in the e object, you might as well do the the far cleaner

req.logger.log('error', 'Error authenticating', { error: e });

On a side note, I would also log invalid log-ins, this way you can detect when someone might be trying to hack in to your system.

You can remove some of the arrowness here as well:

                    .then(function(pnpUserIdResult){
                        pnpUserId = pnpUserIdResult;
                        return user.findByPnpID(pnpUserIdResult);
                    })
                    .then(function(userData){

                        if(userData._id){
                            return storeUserIdInRequest(req, next, userData._id.toString());
                        }else{
                            var newUser = {
                                pnpId: pnpUserId,
                                radius: 1000
                            };
                            return user.create(newUser)
                                .then(function(userData){
                                    return storeUserIdInRequest(req, next, userData._id);
                                });
                        }

I am not sure why you need 2 then's, so I will just merge them.

                    .then(function(pnpUserIdResult){
                        pnpUserId = pnpUserIdResult;
                        var userData = user.findByPnpID(pnpUserIdResult);
                        if(userData._id){
                            return storeUserIdInRequest(req, next, userData._id.toString());
                        }
                        return user.create({
                            pnpId: pnpUserId,
                            radius: 1000
                        }).then(function(userData){
                            return storeUserIdInRequest(req, next, userData._id);
                        });

From a naming perspective;

I get really annoyed by the pnp acronym all over the place, it should be established on top that this for pnp and then you can just go with user and userId or user.id
paynopain <- this is a meaningless name, why would it have getIdFromAccessToken?
var user = new User(req.logger);, whatever user is here, it does not represent a user since you only use it for findByPnpID..
radius: 1000, what does radius mean for a user ? What does 1000 mean ?

Finally, for storeUserIdInRequest (which lies about what it does), you dont have to wait for the cache to be set, you can simply (and this should be faster) do

function storeUserIdInRequest(req, next, userId){
  cache.write('pnpToken:' + req.params.pnp_access_token, userId, {
      expire: 60 * 60 //1 hour in seconds
  });
  req.userId = userId;
  req.logger.setExtra({
    userId: userId
  });
  next();
}


Mapping DNA nucleotides into two-dimensional coordinates

First of all I'd like to say that your code is fast. From studying it, the major bottlenecks that I've found come from the input being a string, and from converting to numpy arrays and back.

Since what you're doing is a kind of cumulative sum with some alterations, I'd go with numpy.cumsum. It's a bit tricky to get everything in place, but the calculations of the actual sequence is actually not the major bottleneck. From what I've seen, the solution I came up with is about twice as fast, and 75% of the time is used to convert the string input to something useful, which in this case is a numpy array representing the character index in the string "ATCG" for each character in the input string.

def transform_fast(seq, d):
    l = len(seq)
    x = np.linspace(0, l, 2 * l + 1, dtype = np.float32)
    y = np.zeros(2* l + 1, dtype = np.float32)

    atcg = np.array([d[x] for x in seq], dtype = np.int8)

    a = (atcg == 1).astype(np.int8)
    t = (atcg == 2).astype(np.int8)
    c = (atcg == 4).astype(np.int8)
    g = (atcg == 8).astype(np.int8)
    ac = a - c
    tg = -t + g

    cum_sum = np.concatenate((
        np.array([0]),
        np.cumsum(tg[:-1])
    ))

    y[1::2] = cum_sum + 0.5*(ac + tg)
    y[2::2] = cum_sum + tg

    return x, y

In the function above, the argument d is a dictionary which looks like:

d = {
    "A": 1, "T": 2, "C": 4, "G": 8,
    "U": 0, "W": 0, "S": 0, "M": 0,
    "K": 0, "R": 0, "Y": 0, "B": 0,
    "D": 0, "H": 0, "V": 0, "N": 0, "Z": 0
}

The only difference compared to your solution is that this returns numpy arrays rather than lists. If this doesn't suit your use case, you can convert them to lists. However, this will slow down the overall performance significantly.

The code above also does not handle the non-ATCG characters in the input string. However, I think that you'll be able to follow the code and implement that in a similar fashion.

Benchmark with random input string of length 10^3
transform(seq): 0.45ms
transform_fast(seq): 0.24ms
Speedup factor: 1.82

Benchmark with random input string of length 10^6
transform(seq): 388.42ms
transform_fast(seq): 133.40ms
Speedup factor: 2.91

EDIT: I found that the np.fromiter(map(...)) that was previously used was unnecessary, and replaced it. This increased performance, benchmarks have been updated. I also found that -t + g was used thrice, and saved the result to a variable. I also switched x and y to be np.float32 arrays, as that improved performance slightly.

It should be noted that the approach above uses more memory than your original approach, which could be a problem for large enough sequences. On my machine (16GB RAM) I couldn't get the result for a sequence of length \$10^8\$, as I ran out of memory.

For the sake of curiosity, here are the benchmarks for when the input string is parsed into a numpy array before transform_fast, which could be used if the input sequences are reused often (these benchmarks haven't been updated, but should remain roughly the same):

Benchmark with random input string of length 10^3
transform(seq): 0.42ms
transform_fast(seq): 0.13ms
Speedup factor: 3.15

Benchmark with random input string of length 10^6
transform(seq): 380.23ms
transform_fast(seq): 37.23ms
Speedup factor: 10.21


Simple PHP inheritance using an abstract class

I think the true problem is that the method shouldn't be static at all.

You should think about static methods as namespaced functions. They logically belong in the same category as the class they're defined on, but they do not actually operate on objects of that class. This means that their use (at least proper use) actually comes up a lot less than you'd think it would.

Typically static methods tend to be utility functions and this is for good reason. Utility methods are basically the only thing that don't have state, and things with state shouldn't be static. As a result of this, if a method is static, it should be idempotent.

Another concern in usability. Having a static method exist on a class hierarchy rather than just the top level ends up in a rather odd situation. Consider code consuming your Pet hierarchy. Obviously this hierarchy exists for the sake of polymorphism, so we can assume that your code takes objects by type Pet. Guess what? This makes calling getEdibleFoods incredibly unwieldy.

function doSomethingWithPetFoods(Pet $pet) {
    // How in the world do I call getEdibleFoods?
    // get_class($pet)::getEdibleFoods? Ew.
}

Don't forget that static methods also equal strong coupling (conveniently, you typically don't care if your coupled to a utility method). It's a bit hard to illustrate with a non-contrived example, so you'll have to bear with me.

function calculateSalesPrice($price, $tax) {
    return Math::round($price * (1 + $tax), 2); // Round to 2 digits
}

What could be wrong with this? It's just a simple round. The problem is that the code is now coupled to a very specific round. What if the United States demands that sales prices be rounded up to the nearest penny, and Argentina dictates that sales prices be rounded down to the nearest penny.

While this is a rather contrived example and its relevence to your code is rather limited, it's worth remembering.

Another problem is that you're (probably) not asking "what do cats eat?" when you call it. You're asking "what does this cat eat." It's a subtle difference, but an important one. What if two dogs eat different things? Or what if a certain cat is allergic to fish? This is why you have to be incredibly sure that a static method has absolutely not relation to state.


Your answers table doesn't actually have an answerID, which is later referenced in your answer comments.

Your link tables for comments, I would have a primary key assigned that is separate from the answerid, since you don't want a composite key between answerID and comment (Think about updating/removing post logic). Apply the same to question comments.

Consider storing users against questions/answer submissions, otherwise, how will you know who posted it? Think about edit functionality too, do you want to audit changes?


Can people understand my form validation code?

Can people understand my code?

Its certainly not bad code - but I believe there are some things you can do which will improve the speed with which people like me can grasp what it is doing (and why).

Comments

Some people think well-written code needs no comments. I don't fall into that camp. Looking at your code I see the following:

Total number of comments is 2

Total number of helpful comments is 1

Total number of comments describing goal of sections of code is 0

Languages like Java have JavaDoc, which are comments in the code from which you can automatically produce documentation. If you've ever tried to re-use code that has no documentation you'll know how useful it is. If you've ever had to maintain documentation that is separate from code you'll know what a pain that is. Innaccurate documentation is worse than none.

So I believe it is best to put documentation into code. Ideally in a form from which documentation can be produced.

I like to treat every function/method I write as if it were one I would put into a library and re-use. To me this means it needs comments that document its purpose, interface and any quirks.

Magic Numbers

You have a lot of magic numbers, e.g. 48 and 57. These should be either

explained in comments
replaced by constants with meaningful names (e.g. ASCII_0, DIGIT_0 ...)
replaced by functions

The latter may be best, especially if you (or anyone else) want this code to work with character sets other than ASCII.

Meaningful names

 function myFunction()

I feel you may be underestimating the usefulness of meaningful names as an aid to other's understanding. I'd try to find a more helpful name that helps others understand the purpose of the the function and what it returns.

Writing for comprehension

You use the ternary operator. Often this is used for assignment. If you use if for assignment but in an unusual way you may momentarily confuse readers.

Unless you need conciseness, it can sometimes be clearer to use a conventional if-then-else form instead.

Wouldn't

document.all ? k = e.keyCode : k = e.which;

be clearer as

k = document.all ? e.keyCode : e.which;

Because the main purpose seems to be to assign a value to k. The earlier style is one I might use if the main point is to call a function and, as an afterthought, evaluate its's success or failure. I think in this case it moves the reader's focus to the wrong place.

Writing portable code and avoiding browser-sniffing

The above use of the ternary operator can probably be avoided entirely. I suspect you may be interested in jQuery and replace it with

keyPressed = e.which

Which I find easier to read and which can be understood more rapidly.

I would at least factor out browser-dependent and/or repeated stuff into my own functions/methods and/or carefully document in comments what it is doing and why it needs to be done.

Documenting purpose

  What I'm trying to achieve in my code is  ...

As I mentioned above, I believe it is very useful to have this described in comments in the code itself (others may disagree). From it's inclusion in your question you evidently believe this helps readers understand the following code. Therefore I'd put it into the code as a comment.


I think there are generally two improvements you can make:

Leverage the GDK (probably what you're most interested in)
Refactor the code to make it testable.

First, here's the code:

def map =
"""01001E
010110
000P00
1100J1
S00111""".split('\n')

def path = findPath(map)
println "path: $path"

assert path == 'RFFLFRFMFLFRFLFF'

def findPath(map) {
    /**
     * Validate the map.
     */
    map.with {
        def size = getAt(0).size()
        def invalidRows = it.findAll { row -> row.size() != size }

        if(invalidRows) throw new IllegalArgumentException("The map $it contains the following invalid rows: $invalidRows")

        it.join().split('').countBy { it }.with { counts ->
            if(counts.S > 1) throw new IllegalArgumentException("The map $it contains multiple start positions.")
            if(counts.E > 1) throw new IllegalArgumentException("The map $it contains multiple end positions.")
            if(!counts.S) throw new IllegalArgumentException("The map $it is missing the start position.")
            if(!counts.E) throw new IllegalArgumentException("The map $it is missing the end position.")
        }
    }

    /**
     * Get the start and end locations.
     */
    def (startLocation, endLocation) = { markers ->
        def locations = markers.clone()

        map.eachWithIndex { it, y ->
            markers
                .collectEntries { marker -> [(marker): it.indexOf(marker)] }
                .each { marker, x ->
                    def index = locations.indexOf(marker)

                    if(x != -1) locations[index] = [x: x, y: y]
                }
        }

        return locations
    }(['S', 'E'])

    /**
     * Find the valid path, if possible.
     */
    def validPath = testMove(startLocation.x, startLocation.y, map, [])
    if (!validPath) throw new IllegalArgumentException("The map $map does not contain a valid path.")

    /**
     * Generate the path in the output format.
     */
    def path = validPath.collate(2, 1, false).with {
        def orintation = 0
        def builder = new StringBuilder()

        it.each { pair ->
            def first = pair[0]
            def second = pair[1]
            def chr = map[second[1]][second[0]]
            def sub = [first[0] - second[0], first[1] - second[1]]
            def newOrin = [[0, 1]: 0, [1, 0]: 1, [0, -1]: 2, [-1, 0]: 3][sub]

            builder.append ((((orintation - newOrin) == 0) ? '' : (newOrin > 0 ? 'R' : 'L')) + (chr == 'J' ? 'M' : '') + 'F')
            orintation = newOrin
        }

        builder.toString()
    }
}

def testMove(x, y, map, visited) { // visited is an array of x y pairs that we have already visited in this tree
    if (visited.contains([x, y]) || y >= map.size() || x >= map[0].size() || x < 0 || y < 0)
        return;

    def chr = map[y][x]
    def newPath = visited + [[x, y]]
    def ret

    if (chr == 'E') return newPath
    if ('J0S'.contains(chr)) {
        def locations = [
            [x: x - 1, y: y],
            [x: x + 1, y: y],
            [x: x, y: y + 1],
            [x: x, y: y - 1]
        ]

        for(location in locations) {
            ret = testMove(location.x, location.y, map, newPath)
            if(ret) return ret
        }
    }
}

Leverage the GDK

Early in the script, you have a size variable which is used to ensure all of the rows in the map are of the same length. The size variable is not used elsewhere. So to limit its scope, you can refactor the validation using Object.with(Closure):

map.with {
    def size = getAt(0).size()
    def invalidRows = it.findAll { row -> row.size() != size }

    if(invalidRows) throw new IllegalArgumentException("The map $it contains the following invalid rows: $invalidRows")

    ...
}

In addition, you can validate that the map contains only one start and end position.

map.with {
    ...
    it.join().split('').countBy { it }.with { counts ->
        if(counts.S > 1) throw new IllegalArgumentException("The map $it contains multiple start positions.")
        if(counts.E > 1) throw new IllegalArgumentException("The map $it contains multiple end positions.")
        if(!counts.S) throw new IllegalArgumentException("The map $it is missing the start position.")
        if(!counts.E) throw new IllegalArgumentException("The map $it is missing the end position.")
    }
}

You can assign the startLocation and endLocation directly, without an initial value which is then overwritten, like this:

def (startLocation, endLocation) = { markers ->
    def locations = markers.clone()

    map.eachWithIndex { it, y ->
        markers
            .collectEntries { marker -> [(marker): it.indexOf(marker)] }
            .each { marker, x ->
                def index = locations.indexOf(marker)

                if(x != -1) locations[index] = [x: x, y: y]
            }
    }

    return locations
}(['S', 'E'])

This has the additional benefit of not having side-effects.

Another improvement is to change the location Lists to Maps so that instead of startLocation[0] you can do startLocation.x. This improves readability.

To build the path String, I think using Collection.collate(size, step, keepRemainder) is better suited than Collection.inject(Closure) because it helps clarify the code's intent. inject() can be used on the output of collate(), but that would have been more trouble than it's worth due to the need to keep multiple things in context (accumulator). So I used Object.with(Closure) instead.

def path = validPath.collate(2, 1, false).with {
    def orintation = 0
    def builder = new StringBuilder()

    it.each { pair ->
        def first = pair[0]
        def second = pair[1]
        def chr = map[second[1]][second[0]]
        def sub = [first[0] - second[0], first[1] - second[1]]
        def newOrin = [[0, 1]: 0, [1, 0]: 1, [0, -1]: 2, [-1, 0]: 3][sub]

        builder.append ((((orintation - newOrin) == 0) ? '' : (newOrin > 0 ? 'R' : 'L')) + (chr == 'J' ? 'M' : '') + 'F')
        orintation = newOrin
    }

    builder.toString()
}

In addition, since in the JVM String is immutable, String concatenation can create temporary objects which the JVM must then dispose of. It's typically better to use StringBuilder.

Testability

To make the code testable, meaning that it can be executed via a method call and the output can be validated, I placed most of the code into the findPath() method. As a consequence, I converted the testMove closure into a method.

I know the challenge states If a map is invalid, STDOUT 'Invalid map.' (That includes if the map is unsolvable). However, I disagree with using the same error message for multiple problems. That's one reason I replaced these messages with insightful exceptions. The other reason is to keep the Groovy Console from exiting.