Client-side validator for contact information form (name, phone, e-mail)

Validation problems
Beware of overzealous validation. It's easy to create bugs by rejecting valid input. For example:

Some people have only one name, so the one of the name fields must be allowed to be empty.
Names often contain non-ASCII characters. Validation must not tell the user their name is invalid!
Email addresses can contain more characters than you think. For example, "Hello, world!"@localhost.localdomain is a valid address. The validity rules are complex, so if you try to implement them with a regex, you will get it wrong. Fortunately you don't need to reject all invalid addresses, only the most common mistakes. So /@/ is enough validation for practical purposes.
Phone numbers can be long, because of country codes and extensions. They can also contain characters like +-()x.

You can avoid these problems by not doing much validation. Don't do unnecessary work that creates bugs!
I wouldn't bother with the event filters at all, especially for the name, where any character should be accepted.
Style
onlyAlphabets should be called onlyLetters (it allows letters, not whole alphabets!), or onlyNameChars, since it also allows some other characters.
e.which ? e.which : e.keyCode can be simplified to e.which || e.keyCode.
This conditional...
if ((charCode == 64) ||
    (charCode == 32) ||
    (charCode >= 65 && charCode <=90) ||
    (charCode >= 97 && charCode <=122))
    return true;
    else return false;

...can be simplified to:
return charCode == 64 ||
       charCode == 32 ||
       charCode >= 65 && charCode <= 90 ||
       charCode >= 97 && charCode <= 122;

...but character codes are hard to read. It might be better to use the string form instead, via operations like String.fromCharCode and charCodeAt.
There are too many blank lines. It's OK to leave one blank line to separate sections (like a paragraph break), but (like anything that consumes lines) they reduce the amount of code that fits on one screen, they should be used only when they improve clarity enough to be worth the extra scrolling.


thanks for sharing your code.

here are my thoughts about it:

Naming

Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.

avoid single character names / abbreviations

Since the number of characters is quite limited in most languages you will soon run out of names. This means that you either have to choose another character which is not so obviously connected to the purpose of the variable. And/or you have to "reuse" variable names in different contexts. Both makes your code hard to read and understand for other persons. (keep in mind that you are  that other person yourself if you look at your code in a few month!) The same is true for (uncommon) abbreviations. You might find them being obvious today, while you're actively dealing with the problem, but You might have to "relearn" them if you worked on something else for a while.

On the other hand in Java the length of identifier names names is virtually unlimited. There is no penalty in any way for long identifier names. So don't be stingy with letters when choosing names.

Choose you names from the problem domain, not from the technical solution.

Since you provided an "academic" example there is not much of a "problem domaine" here tough. I only want to mention it for the records...

Magic numbers

your code has some magic numbers. This are literal values with a special meaning like here:

    s = new String[10];
    //Loop 10 times asking the user for a new sentence each time
    for (int i = 0; i < 10; i++){

You should introduce constants with meaningful names:

    s = new String[ARRAY_SIZE];
    //Loop 10 times asking the user for a new sentence each time
    for (int i = 0; i < ARRAY_SIZE; i++){

Single Responsibility/Separation of Concerns

In your
excample
you mix business logic with user interaction like this:

public String[] build(){
    s = new String[10];
    Scanner scanner = new Scanner(System.in);
    for (int i = 0; i < 10; i++){
         // begin user interaction
        System.out.println("Enter a new sentence: ");
        s[i] = scanner.nextLine();
         // end user interaction
    }
    return s;
}

You should separate that into specialized methods. This would give you the option to move that UI-methods in classes of their own moving your architection foreward to the Model Vew Controller (MVC) Pattern.

dependency injection

Your class has the Scanenr class as a dependency. You instantiate this dependency within a method that represents your business logic.

You'd better pass in the Scanner instance as a constructor parameter allowing you to exchange the implementation later (maybe with a mock for unittesting your code)

reduce visibility (Interface segaration principle)

All your methods are public but (i guess) non of them is ment to be called by users. By default make all your methods private unless you explicitly want them to be either accessed by other code (public) or be overridden by subclasses (protected).

useless comments

You program has lots of comments. This used to be a desired feature 20 ears ago.

You should not add comments just for formal reasons. Such comments are useless at best but usually they turn into lies as the code develops because the first coder changing the content might forget to change the comment too and the next coder refuses to change the comment because she does not know if the comment is wrong or the code...

  Could you give an example of how to accomplish what you are talking about under the section "Single Responsibility/Separation of Concerns"? – J. Tate

You could intrioduce a UI interface for your "application" like this:

interface UserInterface{
    String requestElementFromUser();
}

and an implementation for use with the commandline (most likely in its own *.java file):

class CommandLineuserInterface implements UserInterface{
    private final Scanner commandlineInput;
    private final PrintWriter commandlineOutput;
    CommandLineuserInterface(Scanner commandlineInput, PrintWriter commandlineOutput){
      this.commandlineInput= commandlineInput;
      this.commandlineOutput= commandlineOutput;
    }
    @Override
    public String requestElementFromUser(){
        commandlineOutput.println("Enter a new sentence: ");
        return commandlineInput .nextLine();
    }
}

In your code you would inject an instance of this to your class instanc:

public static void main(String[] args){
    ArrayBuilder AB = new ArrayBuilder(new CommandlineUserInterface(new Scanner(System.in), System.out));

Store that in you app:

public class ArrayBuilder{
    //Initialize an array
    public String[] s;
    private final UserInterface userInterface;
    public ArrayBuilder(UserInterface userInterface){
       this.userInterface= userInterface;
    }

and use that in your code:

   for (int i = 0; i < 10; i++){
        s[i] = userInterface.requestElementFromUser();
   }

The benefit here is that you easily can change the implementation of UserInterface to get the elements from a database, a web service or any even a graphical dialog without ever touching this code again.
The only existing code to change is your main method. But tha't OK since the major responsibility of main is constructing the applications object tree.


Folder browser dialog to remember recent folder. Which method is better?

Extensions are good when you want to re-use this logic in multiple places. As it seems to be the case, i would go with the second method. Generally it is a good practice to avoid code duplication where possible.

The only possible issue i see is that those two methods have different behaviours: first method saves settings after checking the length, while the second method does this before checking. I'm not sure if that is important (can you even get an empty string from this dialog if you press "ok"?).

EDIT:

You can also overload this static method to use lambdas. For example:

public static class FolderBrowserDialogExtensions
{
    public static DialogResult ShowDialog(this FolderBrowserDialog dialog, ApplicationSettingsBase settings, string key)
    {
        return dialog.ShowDialog(settings[key].ToString(),
                                 path => {
                                             settings[key] = dialog.SelectedPath;
                                             settings.Save();
                                         });
    }

    public static DialogResult ShowDialog(this FolderBrowserDialog dialog, string defaultValue, Action<string> onAccept)
    {
        dialog.SelectedPath = defaultValue;
        var result = dialog.ShowDialog();
        if (result == DialogResult.OK)
        {
            // check for null, if needed
            onAccept(dialog.SelectedPath);
        }
        return result;
    }
}

Then you can stick to your Settings class:

dialog.ShowDialog(Settings.RecentFolder, path => Settings.RecentFolder = path);


LeetCode - Weekly Contest 213 - Kth Smallest Instructions

A review of your current code
class Solution uses the fields
String res = string.Empty;
int count = 0;
int K;

to pass information around between the “main” KthSmallestPath() function and the FindAllPaths() helper function. That makes the logic difficult to understand. Even worse, it causes wrong results if the function is called more than once:
String res1 = sol.KthSmallestPath(new int [] { 2, 3 }, 5);
// HVHVH (correct)
String res2 = sol.KthSmallestPath(new int [] { 2, 3 }, 1);
// VVHHH (wrong)

Try to pass all information as function arguments. If that is not possible, make sure to reset all the commonly used fields at the start of the function.
The horizontal and vertical spacing is not consistent: There should be spaces around the operator in
K=k;

and I suggest to always use curly braces with if-statements, e.g. here:
if(count == K)   return;

Finally, I had to think twice about the element of the given destination array correspond to rows/columns and to horizontal/vertical steps. Assinging these values to local variables with an explaining comment can make this more clear:
int vRem = destination[0]; // destination row = # of vertical steps
int hRem = destination[1]; // destination column = # of horizontal steps

A better approach
In the “worst case”
String res = sol.KthSmallestPath(new int [] { 15, 15 }, 155117520);

your code builds recursively \$ \binom{30}{15} = 155117520\$ strings. This is a case where the “brute force” method simply does not work, and one has to find something more efficient.
In fact it is possible to find the k-th smallest permutation of a string with N characters in O(N) time and with O(N) memory, see for example

Finding the n-th lexicographic permutation of a string on Mathematics Stack Exchange,
Find n-th lexicographically permutation of a string | Set 2 on GeeksforGeeks.

The idea is to compute at every step how many permutations start with an H and how many start with a V and then choose the next letter accordingly.
As an example, compute the 5-th permutation of HHHVV.

There are \$ \binom{5}{2} = 10 \$ permutations, and  \$ \binom{4}{2} = 6 \$ start with H. Since  \$ 5 \le 6 \$ the first letter must be H, and it remains to compute the  5-th permutation of HHVV.

Next, there are \$ \binom{4}{2} = 6 \$ permutations of HHVV, and  \$ \binom{3}{2} = 3 \$ start with H. Since \$ 5 > 3 \$ the next letter must be V, and it remains to compute the second permutation of HHV.

This process is repeated until no Hs are left, and the remaining positions are filled with V.

Here is a possible implementation, using a recursive helper function:
public class Solution {

    // From https://rosettacode.org/wiki/Evaluate_binomial_coefficients#C.23
    static int binomial(int n, int k)
    {
        if (k > n - k)
        {
            k = n - k;
        }

        int c = 1;
        for (int i = 0; i < k; i++)
        {
            c = c * (n - i);
            c = c / (i + 1);
        }
        return c;
    }

    /*
     * Returns the `k`-th permutation of a string with `numH` 'H's and
     * `numV` 'V's in lexicographic order.
     */
    static string KthPermutation(int numH, int numV, int k)
    {
        if (numH == 0)
        {
            return new String('V', numV);
        }
        else
        {
            // Number of permutations starting with 'H':
            int c = binomial(numH + numV - 1, numV);
            if (k <= c)
            {
                return 'H' + KthPermutation(numH - 1, numV, k);
            }
            else
            {
                return 'V' + KthPermutation(numH, numV - 1, k - c);
            }
        }
    }

    public string KthSmallestPath(int[] destination, int k)
    {
        int numV = destination[0]; // destination row = # of vertical steps
        int numH = destination[1]; // destination column = # of horizontal steps
        return KthPermutation(numH, numV, k);
    }
}

It computes
String res = sol.KthSmallestPath(new int [] { 15, 15 }, 155117520);

in 0.6 milliseconds on my MacBook (using Mono).


C++ My implementation of a simple sum type (variant)

Construction and destruction of non-trivial types

Unfortunately, your class does not really support non-trivial types, because your class copies the representation of the supplied values and instead of invoking the proper copy constructor.  In other words, you create no object in the Either class, so the behavior of reinterpret_casting the storage and calling the destructor is undefined.

Interestingly, you store the destructor function object but never actually call it, so the class ends up working for trivial types, which do not require invocations to the corresponding constructor or destructor.  However, making your code work by letting two errors cancel out each other is not really a good idea.

The copy and move semantics of your class is also broken.  We'll try to fix this problem later.

Use of runtime type information (typeid)

The usage of typeid is a bit overkill here and not optimal, because it forces the user to pass exactly the same type as one of the stored types, disallowing conversions.  In fact, simply storing an index seems to suffice.

std::variant uses overload resolution to deduce the type, which is hard to implement.  You may consider supporting in_place construction.  (On the other hand, std::variant is typically implemented with unions because of constexpr requirements.)

The storage

using Bigest = std::conditional_t<sizeof(T1) <= sizeof(T2), T1, T2>;
alignas(sizeof(Bigest)) std::byte storage[sizeof(Bigest)];
std::optional<std::type_index> conatinedType;
std::function<void(std::byte*)> destructor;

Consider using std::aligned_storage.  As I said above, we can simply store an index.

using storage_type = std::aligned_storage_t<std::max( sizeof(T1),  sizeof(T2)),
                                            std::max(alignof(T1), alignof(T2))>;
storage_type storage;
std::size_t index;

For valueless variants, we can provide a special index:

static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();

The constructors

The default constructor of std::variant default-constructs the first alternative type.  You can go into the valueless state instead:

Either() noexcept
    : index{npos}
{
}

Here's how you'd support in place constructors:

template <std::size_t I, typename... Args>
explicit Either(std::in_place_t<I>, Args&&... args)
{
    construct<I>(std::forward<Args>(args)...);
}

template <std::size_t I, typename U, typename... Args>
explicit Either(std::in_place_t<I>, std::initializer_list<U> ilist, Args&&... args)
{
    construct<I>(ilist, std::forward<Args>(args)...);
}

where the private member function template construct is defined like

template <std::size_t I>
struct alternative_type {
    static_assert(I < 2);
    using type = std::conditional_t<I == 0, T1, T2>;
};
template <std::size_t I>
using alternative_type_t = typename alternative_type<I>::type;

// not exception safe
template <std::size_t I, typename... Args>
void construct(Args&&... args)
{
    index = I;
    ::new (static_cast<void*>(&storage))
        alternative_type_t<I>(std::forward<Args>(args));
}

Special member functions

As I said before, you need to implement the copy/move/destruction operations.  Here's the copy constructor for example: (SFINAE and explicit issues are omitted for simplicity.)

Either(const Either& other)
{
    if (other.index == 0) {
        construct<T1>(other.get<0>());
    } else if (other.index == 1) {
        construct<T2>(other.get<1>());
    } else {
        index = npos;
    }
}


Generating packing slips depending on product type

Indentation
Yours is highly inconsistent. It's best to use an autoformatter to ensure that this remains sane and consistent.
Property boilerplate
This:
            private int productId;
            public int ProductId
            {
                get
                {
                    return productId;
                }
                set
                {
                    productId = value;
                }
            }

is both very Java and unnecessary given the syntactic sugar that C# has supported for several years:
public int ProductId { get; set; }

Factory?

How can I avoid instantiating PackingSlip here

Why do you want to avoid instantiating it? Is it because PhysicalProduct is supposed to be an abstract class as well? If so, you are correct to want to avoid assigning an instance in the abstract class, since your assignment in the BookProduct constructor will overwrite this value.
There are several approaches you can follow. One is to make the top-level constructor accept an instance of IPayment, and to pass a new instance via base().
Another approach is to make the abstract base class a generic, where the generic type is forced to implement IPayment. The abstract class would not need to accept a new instance, and would be able to construct its own instance so long as the new constraint is imposed.
Redundant base call
This:
    public BookProduct():base()

should not need to explicitly call base.
MakePayment
One of two things has happened here. Either you've omitted a bunch of code, which would technically make this section of the question off-topic; or MakePayment is both misnamed and mischaracterized as a function. If the latter, make it a get-only property and rename it to something like Description.


Right, you're only manipulating the model, updating the model about a change (thus) updating it in the controller is perfectly fine, and it's what the controller does.
del_item should be in the controller too, you are correct. That's where it belongs.
Using the index to deleting the item is dangerous, what I'd do is pass this as a function and then use an indexOf to locate the element you're deleting and delete that.

If I may ask, why are your display items in a directive in the first place and not in the DOM? You could use an ng-repeat in the DOM to repeat the items instead and drop the directive altogether.

Directives are useful for code reuse, are you reusing this spefici component in a lot of other places through out your code? Behaviors affecting your models and not just your presentation logic should probably not be in the directive to begin with (like del_item in your example), a directive should encompass presentational behavior and not business logic.


Better "find and highlight" implementation in HTML element

Let's start by optimising your code.  Simply said, loops are the danger here.

A while loop can be quicker than a for loop, especially in cases like this. Get the length once.
Avoid looking into arrays.  Do word = words[i] once, which is much faster.
You are joining in every iteration. You should join once only after you have updated your array.
I guess the empty else isn't done yet.

var s = document.querySelector('input[type="search"]'),
    p = document.querySelector('p'),
    find = function(){
        var words = p.innerText.split(' '),
            i = words.length,
            word = '';

        while(--i) {
            word = words[i];
            if(word.toLowerCase() == s.value.toLowerCase()){
                words[i] = '' + word + "";
            }
            else{

            }
        }

        p.innerHTML = words.join(' ');
    }

s.addEventListener('keydown', find , false);
s.addEventListener('keyup', find , false);

Last but surely not least, the page you want to read.


Can this sampling code be vectorized or optimized?

Yes, it is possible to vectorize the code. Does that make it faster? That depends on the spread of values in your data Y.

Computing the scale parameter can be vectorized without issues and should be faster.

For the shape parameter - I haven't read the papers - you seem to use something that looks quite similar to rejection sampling. You compute a probability distribution tbl over NxJ, then draw Y[n, j] many samples from a uniform distribution and check how often you land within tbl[n,j]. shape is then the sum of "hits" along N.

The naive approach to vectorizing this would be to draw the same amount of samples for each Y[n, j]. In this case at least max(Y) many. This can create a lot of overhead if your data has a few really large values but otherwise small ones. If the values are fairly close together, this will make things faster. If you have a way to quickly (pre-)generate large quantities of uniform numbers this limitation doesn't matter.

Here is the code:

def sample_r_vec(Y, P, R, e0=1e-2, f0=1e-2, random_numbers=None):
    """Sample negative binomial dispersion parameter `r` based on
    (Zhou 2020). See:

    - http://people.ee.duke.edu/~mz1/Papers/Mingyuan_NBP_NIPS2012.pdf
    - https://mingyuanzhou.github.io/Softwares/LGNB_Regression_v0.zip
    """

    if random_numbers is None:
        random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))

    # compute shape
    Y_max_vec = np.arange(np.max(Y) + 1).reshape((-1, 1))
    R_vec = R.reshape((1, -1))
    tbl = (R_vec / (R_vec + Y_max_vec))
    tbl = tbl.reshape((*tbl.shape, 1))
    N_vec = np.arange(Y.shape[0]).reshape(-1, 1)
    J_vec = np.arange(Y.shape[1]).reshape(1, -1)
    sum_hits = np.cumsum(random_numbers <= tbl.T, axis=2)[N_vec, J_vec, Y - 1]
    sum_hits[Y == 0] = 0
    shape = e0 + np.sum(sum_hits, axis=0)

    # compute scale
    maxes = np.maximum(1 - P, -np.inf)
    scale = 1. / (f0 - np.sum(np.log(maxes), axis=0))

    # sample
    R = np.random.gamma(shape, scale)
    R[R < 1e-7] = 1e-7
    return R

Edit: Based on the comment, I did find a different bug that is now fixed.

Edit: Demonstration that both versions perform equally.

Firstly, we need a different test to assert equality of the code; try assert(sample_r(Y, P, R) == sample_r(Y, P, R)) and you will quickly see the problem. There are many reasons why a different test is needed: (1) sample_r and sample_r_fast return vectors and not scalars. The truth value of a vector is undefined (numpy also warns for that). (2) your code (sample_r) modifies R in place, which means that the input to sample_r_fast will be different to the input of sample_r. Logically, the outputs will differ due to the unwanted side effect. (3) Both functions are expected to create random samples and compute results based on that. assert tests for exact equality and will hence fail even if both versions are correct. Providing the same random seed won't be enough either, because the order in which the samples are used may differ, which will change the results. (4) This is a numerics problem; even in the deterministic part of the code it is only accurate up to a tolerance. (5) The code estimates parameters for a distribution and then samples once from the estimated distribution; these samples are then compared. If we want to know whether or not the two versions estimate the same distributions it seems much more efficient to directly compare the parameters.

To fix all of this, I modified the code in the following way:

Added an optional parameter to the function that can be used as random numbers; generate them if none.
Made sure the same random numbers are used for comparisons each time.
Removed the sampling of R at the end and instead return the estimated shape and scale directly.
It is also nice to test if the new code is actually faster, so I added a speed test (excluding RNG).

My full script looks like this:

import numpy as np

def sample_r(Y, P, R, e0=1e-2, f0=1e-2, random_numbers=None):
    """Sample negative binomial dispersion parameter `r` based on
    (Zhou 2020). See:

    - http://people.ee.duke.edu/~mz1/Papers/Mingyuan_NBP_NIPS2012.pdf
    - https://mingyuanzhou.github.io/Softwares/LGNB_Regression_v0.zip
    """

    if random_numbers is None:
        random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))

    A_vec = np.zeros_like(R)
    B_vec = np.zeros_like(R)
    J = Y.shape[1]
    for j in range(J):
        L = crt_sum(Y, R, j, random_numbers)
        A = e0 + L
        A_vec[j] = A

        # `maximum` is element-wise, while `max` is not.
        maxes = np.maximum(1 - P[:, j], -np.inf)
        B = 1. / (f0 - np.sum(np.log(maxes)))
        B_vec[j] = B

        # R[j] = np.random.gamma(A, B)
    # `R` cannot be zero.
    # inds = np.isclose(R, 0)
    # R[inds] = 0.0000001
    return A_vec, B_vec

def crt_sum(Y, R, j, random_numbers):
    """Sum independent Chinese restaurant table random variables.
    """

    Y_j = Y[:, j]
    r   = R[j]
    L   = 0
    tbl = r / (r + np.arange(Y_j.max()))
    for n_idx, y in enumerate(Y_j):
        if y > 0:
            relevant_numbers = random_numbers[n_idx, j, :y]
            inds = np.arange(y)
            L += (relevant_numbers <= tbl[inds]).sum()
    return L

def sample_r_vec(Y, P, R, e0=1e-2, f0=1e-2, random_numbers=None):
    """Sample negative binomial dispersion parameter `r` based on
    (Zhou 2020). See:

    - http://people.ee.duke.edu/~mz1/Papers/Mingyuan_NBP_NIPS2012.pdf
    - https://mingyuanzhou.github.io/Softwares/LGNB_Regression_v0.zip
    """

    if random_numbers is None:
        random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))

    # compute shape
    Y_max_vec = np.arange(np.max(Y) + 1).reshape((-1, 1))
    R_vec = R.reshape((1, -1))
    tbl = (R_vec / (R_vec + Y_max_vec))
    tbl = tbl.reshape((*tbl.shape, 1))
    N_vec = np.arange(Y.shape[0]).reshape(-1, 1)
    J_vec = np.arange(Y.shape[1]).reshape(1, -1)
    sum_hits = np.cumsum(random_numbers <= tbl.T, axis=2)[N_vec, J_vec, Y - 1]
    sum_hits[Y == 0] = 0
    shape = e0 + np.sum(sum_hits, axis=0)

    # compute scale
    maxes = np.maximum(1 - P, -np.inf)
    scale = 1. / (f0 - np.sum(np.log(maxes), axis=0))

    return shape, scale

if __name__ == "__main__":
    def sigmoid(x):
        return 1 / (1 + np.exp(-x))

    np.random.seed(1337)

    N = 100
    J = 10
    Y = np.arange(N*J, dtype=np.int32).reshape(N, J)
    P = sigmoid(np.random.random((N, J)))
    # use test case from comments
    R = np.ones(J, dtype=np.float32); R[J-1] = 5000
    random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))

    shape_normal, scale_normal = sample_r(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers)
    shape_vec, scale_vec = sample_r_vec(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers)

    assert np.all(np.isclose(scale_normal, scale_vec))
    assert np.all(np.isclose(shape_normal, shape_vec))

    #speed test
    import timeit
    t1 = timeit.timeit(lambda: sample_r(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)
    t2 = timeit.timeit(lambda: sample_r_vec(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)
    print(f"Original version total time {t1:.2f}. Vector Version total time {t2:.2f}.")

    N = 1000
    J = 10
    Y = 100*np.ones(N*J, dtype=np.int32).reshape(N, J)
    P = sigmoid(np.random.random((N, J)))
    R = np.arange(J)+1
    random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))
    t1 = timeit.timeit(lambda: sample_r(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)
    t2 = timeit.timeit(lambda: sample_r_vec(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)
    print(f"Original version total time {t1:.2f}. Vector Version total time {t2:.2f}.")

Note that this now has a python 3.7+ dependency due to format strings in the functional test, the relevant code does not have that dependency.

Output:

Original version total time 1.29. Vector Version total time 1.05.
Original version total time 8.55. Vector Version total time 0.98.

I did the following modifications to your code: To return the estimated parameters, I am stacking them up in a vector as they are being computed. To deal with the random sampling, I generate a whole bunch of random numbers (Y.max() many) for each Y[n, j], and then select the first y=Y[n,j] of them. This is the same idea I used to vectorize the code; it 'wastes' Y.max() - Y[n, j] many random samples at each step, because the code generates them but then doesn't use them; it's a trick to match the shapes for vectorization. This is the main reason why the vectorized version will only be faster if you either (1) pre-generate the random numbers, or (2) have a situation where the different Y[n, j] don't differ too much, so that generating the 'waste' doesn't take more time than is saved by hardware acceleration.

I hope this explains what is going on.

PS: Please, please use informative variable names for code in the future. L,n,j,A,B, ect. are not wise choices if others are to read your code or if you try to understand it 3 years from now.


Find the sum of prime numbers below 2 million

There are several issues, but here goes. Firstly, your indentation is all wonky. Some of this may be due to trying to input stuff here, but either way, indentation helps legibility.

Next, the biggest thing you can change to speed thing up is to replace for (int i = 2; i < n; i++) with for (int i = 2; i*i <= n; i++). This works because if \$a \cdot b = n\$, one of them is at most the square root of \$n\$. This change will probably make your code fast enough on its own.

That said, the much better solution to this type of problem is to use a prime sieve such as the Sieve of Eratosthenes which will generate all of the primes less than 1,000,000 faster by using addition and multiplication instead of modulo operations which are slower.


Optimize a generic foreach method that converts Datatable to my object using Reflection

A few points tickle:

Why is it a static method?
None of the comments are helpful. Good comments say why, not what. I'd remove them all.
Bracing is inconsistent. Consider:

if (!(dr[propertyInfo.Name] is DBNull))
    propertyInfo.SetValue(ob, dr[propertyInfo.Name]);

And then:

if (!(dr[primaryKey] is DBNull))
{
    propertyInfo.SetValue(ob, dr[primaryKey].SafeToInt());
}

I prefer the latter, as explicit scopes are always less error-prone.
Naming is also inconsistent. You call a PropertyInfo, propertyInfo (♥++)... but then you have a List<T> that you call lst instead of list - although since that's the method's return value I'd just call it result.
Return value should probably be exposed as an IEnumerable<T> - it's your method's job to add items to that list, not the client code's. Right?

If you can return an IEnumerable<T>, then you can yield return ob, and drop the lst altogether.

Instead of using reflection to create an instance of T, I would use a : new() generic type constraint to ensure T has a parameterless constructor, and create the instance like this instead:

var ob = new T();

There is no generic type constraint at all, so technically this call would be valid:

var foo = WhateverTheClassIs.BindDataList<int>(dt, "Id");

I would consider changing the signature to include a class generic type constraint that ensures T is a reference type:

public static List<T> BindDataList<T>(DataTable dt, string primaryKey)
    where T : class, new()

ob is an awful name. I understand the intent was to call it object and that would have clashed with System.Object - I would rather see @object than ob, to tell you the truth. But instance is probably a better fit.
dr could be called row instead.


Selective autorotation in a UINavigationController

First of all you could skip storing the current view controller in a variable. And instead of checking for the correct class you could delegate your shouldAutorotateToInterfaceOrientation: to the current visible one in the navigation controller.

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // assumes you've got access to the navigation controller here
    UIViewController *visibleController = navigationController.visibleViewController;

    return [visibleController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}


Naming Conventions

According to the official Python style guide, class names should be in PascalCase:

No:
    class my_class():
Yes:
    class MyClass():

In your case, I would capitalize the entire xlsx because it is an acroynm:

class XSLXExtend():

There also seems to be some redundancy in some of your names:

# worksheet_name_worksheet?
self.ws_name_worksheet

This next point may be speaking on an intentional design measure, but I would take a look at what properties are supposed to be 'public' and which are meant to be 'private'. Even though Python doens't truly have private variables, it is still convention to use a single underscore ('_') at the start of any intended private variables.

self._i_should_be_private = 'No touching!'

Some of your names are misleading:

# Wait. This stores the actual Workbook not its name?
self.xlsx_name = Workbook(name)

Structure

I am not a big fan of declaring instance variables outside of the __init__ method. In lieu of this, I would refactor your create_format() method as such:

def create_format(self, color, size):
    format = self.xlsx_name.addFormat()
    format.set_font_size(size)
    format.set_bold()
    format.set_color(color)
    format.set_border()
    format.set_center_across()
    format.set_align('center')
    format.set_rotation(90)

    return format

Then just put this line in the __init__ method: self.format = create_format('blue', 12).

Also, you have an accessor method (which is nice) for xlsx_name. However, in your code that actually uses your classes, you just directly access it:

# Why even have `get_xlsx_name()` if you don't use it?
red_format = report_xlsx.xlsx_name.add_format(...)

The same goes for your create_format() method. You use it once in __init__ but don't when you actually use your class. You skip straight to the Workbook:

red_format = report_xlsx.xlsx_name.add_format({'bg_color': '#FF0000'})

Essentially you are circumventing all the work you did wrapping the Workbook class in another class.

Since your xlsx_extend class is supposed to store data about and manipulate a Workbook why not store all of the formats there? Here is what I would do:

class XLSXExtension(object):
    def __init__(self, name):
        self.xlsx_name = Workbook(name)
        self.formats = {}

        self.create_format('blue', 'blue')

    def create_format(self, name, color, size=12):
        format = self.xlsx_name.addFormat()
        format.set_font_size(size)
        format.set_bold()
        format.set_color(color)
        format.set_border()
        format.set_center_across()
        format.set_align('center')
        format.set_rotation(90)

        self.formats[name] = format

    def __getattr__(self, key):
        try:
            return self.formats[key]
        except KeyError:
            print('Format "{}" not found.'.format(key))

report_xlsx = xlsxutils.xlsx_extend("report.xlsx")
report_xlsx.create_format('red', '#FF0000')
report_xlsx.create_format('green', '#99CC32', 24)

report_worksheet = xlsxutils.xlsx_sheet(report_xlsx, "Report")
report_worksheet.text_condition_format(1, 1, row, col, 'P', report_xlsx['green'])
report_worksheet.text_condition_format(1, 1, row, col, 'F', report_xlsx['red'])


Don't use wildcard imports

I know that most tkinter tutorials show you to do from tkinter import *, but they are wrong. PEP8 recommends not use use wildcard imports, and I think that's especially true with tkinter.

Instead, use import tkinter as tk, and then prefix all tk classes with tk.. For example:

master = tk.Tk()
...
label1 = tk.Label(master, text="Working Time", bg='white')

You are using after incorrectly

This statement does not do what you think it does:

master.after(1000, label5.config(text=i))

The above is exactly the same as this:

result = label5.config(text=i)
master.after(1000, result)

My advice is to always have after call a function. So, write a function that takes two arguments, a label and a value, and updates the label with a value. Then, use after to call that function.

def update_label(label, value):
    label.configure(text=value)
...
master.after(1000, update_label, label5, i)

Give your widgets explicit masters / parents

Instead of this:

button1=Button(text='Window Color', command=window_color)

Do this:

button1=Button(master, text='Window Color', command=window_color)

While tkinter will use the default root window if you leave it out, PEP8 says that explicit is better than implicit. Plus, it makes it clear what your intentions are. Otherwise, someone reviewing your code might wonder if you're intentionally putting the widget in the root window or if it's a bug.

Remove useless code

I don't know what you think this is doing, but whatever that is, it's probably not doing it. You can remove this line of code:

master.after(1000, None)


Join strings with different delimiters and some possibly empty strings

It doesn't look too bad to me; I'd make a few changes.

def my_join(major, minor, patch=None, prerelease=None,
            build=None, revision=None):
    version_parts = ['.'.join((major, minor, patch or ''))]

    if prerelease:
        version_parts.append('-%s' % prerelease)
    if build:
        version_parts.append('+b%s' % build)
    if revision:
        version_parts.append('.%s' % revision)

    version = ''.join(version_parts)

    return version

Instead of building the string piece-by-piece, this code adds the needed parts to a list which is then joined at the end. I also removed the overpowered call to filter, and instead used or to make the patch value be '' if patch is False-ish, as it would be if patch is None.


Review and Complexity
This answer is in two parts.

A review of the code and a rewrite based on the review. There are what might be bugs. This addressed in the second part.
A look at complexity, how to reduce complexity. An example function is given with lower complexity.

Review

Do not use un-delimited code blocks eg if (copA.length == 1) return res = copA[0]; should be if (copA.length == 1) { return res = copA[0]; }

Use === (Strict equality) rather than == (Equality) The same would apply for !== (Strict inequality) rather than != (Inequality)

Avoid using for...in without checking if the key is a property or index of the array/object you are iterating. Use for...of for arrays and if the item being iterated is an object use Object.keys to create an array of property names.

Use const for variables that do not change. Eg the array copA never changes and should be a const.
On the same point it is preferred to use const when possible, If you use newArr.length = 0 rather than newArr = [] you can then make newArr a const. This is also more efficient at run time as zeroing an array is quicker than creating a new array.

The general rule for line ends is use a semicolon only when ASI (Automatic Semicolon Insertion) is ambiguous (The assumption is you may not know what the next line of code is eg when using bundlers, pre-parse parser, anything that changes the code before parsing).
A } that delimits a code block is an unambiguous line terminator and does not require a semicolon.
A } at the end of a object literal can be ambiguous and does requires a semicolon.

Most comments are just code noise, often they assume the reader does not know how to read code.
Comments that are a Human readable expressions of intent should be avoided.
If you find that some code is a little hard to understand from just reading the code it is likely that some renaming and or restructuring will make your intent clear rather than having to explain your intent with a comment

Use modern syntax.
To copy an array use the spread operator ...(Spread syntax) rather than  Array.from
Names
Names should be what the value represents rather than its type.

A (for array) can be values or numbers The plural means its an array

copA function arguments are not constants and you can reuse them. See rewrite.

Across many languages we use i, j, and sometimes k as counters. You should only use these names when they are counters. The loop for (let i in copA) { should use a name that represent what the value holds. Eg for (let num in copA) { or for (let val in copA) {

Efficient code
Always be efficient and avoid redundancy.

The line return res = copA[0] is a redundant assignment and should be return copA[0]

The second else if(newArr.length == 1) { is not required and can just be else {

Array.push returns the length of the array after the push.
Chrome, Edge, Nodejs and many APPs that use JS engines use V8. V8 has a quirk that makes indexed references eg newArr.length slower than direct or immediate references. Thus it would be better to use the statement if (newArr.push(copA[i]) === 2) {`` rather than if(newArr.length == 2)`
Please note that this is trivial and as such would be something to you do when you are comfortable with your coding knowledge.

Don't use arrays to count occurrences . See rewrite. Because I see this type of thing so often will boldly yell 'DON'T USE A ARRAYS TO GET COUNTS'

The line  newArr[0] = b; is followed by a break thus you never use the array newArr again making the assignment redundant.

Rewrite
The rewrite does not create a new algorithm. It behaves the same as you code and passes the provided tests. This does not mean it will do so on all tests but I am limited by only what you provide.
The rewrite is just a clean up of the code in regards to the points outlined above.

The  array use to count numbers has been replaced with a counter.
To keep the previous value a variable called prevNum is used.
As prevNum is the value you return via res, res has been removed with prevNum.

The code
    function findOdd(numbers) {
        let count = 0, prevNum;
        numbers = [...numbers].sort((a, b) => a - b);
        if (numbers.length % 2 === 0) { return }
        if (numbers.length === 1) { return numbers[0] }

        for (const num of numbers) {
            if (Number.isInteger(num)) {
                if (num === prevNum) {
                    count ++;
                } else if (prevNum !== undefined) {
                    if (count % 2) { break }
                    count = 1;
                    prevNum = num;
                } else {
                    count ++;
                    prevNum = num;
                }
            } else { return 0 }
        }
        return prevNum;
    }

Complexity
This problem  has a complexity of \$O(n)\$.
Your code has a complexity of \$O(n log( n))\$. Why? because you sort the array. Sorts are complex. If you can avoid using a sort do so.
I understand the reasoning behind the use of a sorted array, to group numbers.
We must find a better way to  group values but first your code has some inconsistent results (or bugs?)
Bugs???
Note: that in the rewrite (above) I pointed out that it only passed the tests provided. Any working code provides all that is needed to rewrite it and  pass any test. However I strongly suspect that you have bugs that are not detected by the tests you provided.
Test are useless if they do not check every edge case. Edge cases are more often than not the source of bugs. Just looking at the code an I see inconsistency in the return values.
Inconsistencies
The inconsistent results due to

The early return of even sized arrays.
The early break if a non integer is found.
The problems description is incomplete as it does not clearly state what should be returned in some edge cases

These Inconsistencies mean that the following inputs give or (may be giving) unexpected results
findOdd([1,0.1,2,1,0.1])); // returns 0, would expect 2?
findOdd([0.1,1]));         // returns undefined, would expect 1?
findOdd([0.1,1,1]));       // returns 0, The return has not been defined

There are also 2 unexplained return values, each the contra of the other

Returning the first and lowest value if the array length is 1. Why the lowest?
Returning zero. Why zero and not the lowest as above?

Reducing complexity
I will reduce the complexity to \$O(n)\$ by using a hash map to count groups. JS provides several hash maps Map, Set, WeakMap and WeakSet. Only the first two can help in this case as Number is not a referenced value. (exception when number is created using Number(123))
First some assumptions
I must make some assumptions about how it behaves in edge cases.

Even sized arrays may still contain odd groups of values.
If there are no odd groups the first integer value is returned.
If there are no integer values or the array is empty undefined is returned.
All values in the array are of type Number

Steps
An explanation of the new solution
Create a hash map to count occurrences in each group.
Iterate each value in input,
   If a value is an integer
       If the values is in the map add one to the count
       If not in the map add to the map with a count of 1
Iterate the completed map.
   If an entry is an odd count return that maps value as the result
If the size of the hash map is zero return undefined
return the first value in the hash map.

Getting the first entry from a hash map can be done using [...map.keys()][0] however that is is overly complex \$O(n)\$. Rather you can use the iterator protocols Iteration protocols next().value with a complexity of \$O(1)\$
The \$O(n)\$ solution
function findOdd(numbers) {
    const groupsByVal = new Map();
    for (const num of numbers) {
        if (Number.isInteger(num)) {
            const counter = groupsByVal.get(num);
            if (counter) {
                counter.count ++;
            } else {
                groupsByVal.set(num, {count: 1});
            }
        }
    }
    for (const [num, {count}] of groupsByVal.entries()) {
        if (count % 2) {
            return num;
        }
    }
    return groupsByVal.keys().next().value;
}

Or I prefer
function findOdd(numbers) {
    const grpByVal = new Map();
    for (const num of numbers) {
        if (num % 1 === 0) {
            const grp = grpByVal.get(num);
            if (grp) { grp.c ++ }
            } else { grpByVal.set(num, {c: 1}) }
        }
    }
    for (const [num, {c}] of grpByVal.entries()) {
        if (c % 2) { return num }
    }
    return grpByVal.keys().next().value;
}


(I've not coded in PHP recently, my examples are Java or Java-like pseudocode.)

In his Working Effectively with Legacy Code book Michael C. Feathers describes a lot of techniques which help making any code testable. Another good resource is the following article: Killing the Helper class, part two

The usual way to breaking static dependencies is the following: Create a non-static interface which has a similar method than the original static class:

public interface OrmFactory {
    OrmSomething create($name);
}

Then create an implementation which calls the static method/class:

public class OrmFactoryImpl implements OrmFactory {
    public OrmSomething create($name) {
        return ORM::factory($name);
    }
}

Finally, use the interface in the can_apply_extension function:

public class MyClass {

    private OrmFactory ormFactory;

    public MyClass(OrmFactory ormFactory) {
        this.ormFactory = ormFactory;
    }

    public void can_apply_extension() {
        ...
        $record = ormFactory.create('a model')
                     ->where('created_at', 'BETWEEN', $search_dates)
                     ->find();
        ...
    }
}

In tests you can pass a mocked OrmFactory to the class while in production code you can use the original one through the OrmFactoryImpl wrapper/delegate. (I guess PHP also has some mocking framework implementations which makes testing easier but you can implement a TestOrmFactory which emulates some behaviour of the original one without the need of any database.)

The second snippet in the question has test logic in production smell. I would avoid that and use the much cleaner dependency breaking above. The linked page contains some disadvantages of the smell. One of them is the following:

  Code that was not designed to work in production
  and which has not been verified to work properly
  in the production environment could accidently be
  run in production and cause serious problems.

And another one is:

  Software that is added to the SUT For Tests Only
  makes the SUT more complex. It can confuse potential
  clients of the software's interface by introducing
  additional methods that are not intended to be
  used by any code other than the tests. This
  code may have been tested only in very specific
  circumstances and might not work in the typical
  usage patterns used by real clients.

(SUT means System Under Test, in this case the class with can_apply_extension().)


Improving sub select query on two tables without relationship

It's odd you say it is not possible, because it is possible, right?

select ID, Name, MinSalary, MaxSalary, count(Salary) as SalaryCount
from SalaryBands
left outer join EmployeeSalary on salary between minsalary and maxsalary
group by ID, Name, MinSalary, MaxSalary

Now, I am not sure I would actually use that... I would actually go with your query, but transformed to be more readable...

select ID,
       Name,
       MinSalary,
       MaxSalary,
       (select count(*)
        from EmployeeSalary
        where salary between minsalary and maxsalary
       ) as BandCount
from SalaryBands


Best way to optimize multiple search on Lists java

Problem Statement

This is my understanding of the problem statement.

We have a bus that has k seats.
There is a list of people p waiting at a bus stop.  The value in each position of the list is the amount of time the person is willing to wait for a bus.  The list is replenished for each scheduled time the bus arrives.  The wait times do not change with new people.
There is a list of scheduled times q that the bus will arrive.

The method busFilled returns a List of the index of the last person to get on the bus each time the bus arrives at the bus stop.  There should be the same number of elements in the output List as there are in the list of scheduled times q.

If no one can fit on the bus, the List should return zero in that position.

Analysis

I approached the problem the same way I approach any problem.  I break the problem down into smaller and smaller steps until I can write code for each of the steps.

Here's the code I wrote.  The explanation follows the code.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BusSimulation {

    public static void main(String[] args) {
        int k = 2;
        int[] people = { 1, 4, 2, 5 };
        List<Integer> p = createList(people);
        int[] busTime = { 1, 4 };
        List<Integer> q = createList(busTime);
        List<Integer> f = busFilled(k, p, q);
        Integer[] output =
                f.toArray(new Integer[0]);
        System.out.println("Result: " +
                Arrays.asList(output));
    }

    public static List<Integer> createList(int[] array) {
        List<Integer> output = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            output.add(array[i]);
        }
        return output;
    }

    public static List<Integer> busFilled(int k,
            List<Integer> p, List<Integer> q) {
        List<Integer> output = new ArrayList<>();

        for (int i = 0; i < q.size(); i++) {
            int busTime = q.get(i);
            int index = getPassengerIndex(k, p, busTime);
            output.add(index);
        }

        return output;
    }

    private static int getPassengerIndex(int k,
            List<Integer> p, int busTime) {
        int count = 0;
        int index = -1;

        for (int i = 0; i < p.size(); i++) {
            if (busTime <= p.get(i)) {
                index = i;
                count++;
                if (count >= k) {
                    return index + 1;
                }
            }
        }

        return index + 1;
    }

}

The main method and the createList method set up the problem.

I created a separate method, getPassengerIndex, to get the passenger index for one bus trip.  That way, I avoided a nested for loop and worrying about how to break out of the nested for loop.

The getPassengerIndex method loops through the passenger list.  First, I test to see if the waiting time has been exceeded.  If not, then I save the index and increment the count of the number of passengers boarding the bus.  Finally, I test for the bus being filled.  If so, I return the passenger number.  If the bus isn't filled, I return the last passenger number whose waiting time has not been exceeded.

I could test getPassengerIndex separate from the rest of the code.  Once I got that method working, writing the busFilled method was straight forward.

Decomposition, or divide and conquer, is the most straightforward way to solve problems.


Avoiding Duplicate Boilerplate Code in WCF Service

I'm not sure why your change all of a sudden would expose data to the business layer when it didn't before.

If you have a pattern of methods which look like this:

public string MyServiceCall()
{
    try
    {
        JObject incomingRequestJson = retrieveJson();
        JObject returningJson = new JObject();

        // do stuff

        return returningJson.ToString(Newtonsoft.Json.Formatting.None);
    }
    catch (Exception ex)
    {
        throw new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);
    }
}

Then you can simply add a helper method to your service implementation:

private string ProcessServiceCall(Func<JObject, JObject> processor)
{
    try
    {
        JObject incomingRequestJson = retrieveJson();
        JObject returningJson = processor(incomingRequestJson);

        return returningJson.ToString(Newtonsoft.Json.Formatting.None);
    }
    catch (Exception ex)
    {
        throw new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);
    }
}

and your service call then becomes:

public string MyServiceCall()
{
    ProcessServiceCall(incomingRequestJson => {

        string accountId = incomingRequestJson.SelectToken("accountId", true).ToString();
        string username = incomingRequestJson.SelectToken("userName", true).ToString();
        string password = incomingRequestJson.SelectToken("password", true).ToString();

        JObject result = new JObject();

        LoginResult result = readerBLL.Login(accountId, username, password);
        result.Add(new JProperty("userSessionId", result.userSessionId));
        result.Add(new JProperty("friendlyUserName", result.friendlyUserName));

        return result;
    }
}

This should be a simple refactoring on your service class and not expose any more json to the business logic than before.


Javascript class to geocode Dutch addresses

Using Promise when async/await is supported is a sign of an anti-pattern. The only case you ever manually build promise in an environment that supports async/await is when the asynchronous operation cannot be written linearly/when you can't await (e.g. resolve must be called in a callback).

// You cannot really "await" this kind of API, hence the wrapper Promise.
foo() {
  return new Promise((resolve, reject){
    someAPIThatOnlyDoesCallbacks((err, data) => {
      if (err) reject(err)
      else resolve(data)
    })
  })
}

But in your case, fetch returns a promise, response.json() also returns a promise. You can just return the promise generated by the whole fetch operation itself.

_get(url) {
  return fetch(url).then(r => r.json())
}

Next, consider using Url and UrlSearchParams to construct your url. This way, the url is constructed correctly.

async suggest(url, param1, param2, ....){
  // Create the url
  const url = new URL(url)

  // Append the values
  url.searchParams.append('param1', param1)
  url.searchParams.append('param2', param2)

  // Construct the url
  return await this._get(url.toString())
}

On to other things, there's currently nothing in your class that is instance-specific (the base url is hardcoded, params are supplied at call time). You can simply export a bunch of stateless functions from the module instead of having to instantiate an instance.

const getJSON = url => fetch(url).then(r => r.json())
const geocoderUrl = "https://geodata.nationaalgeoregister.nl/locatieserver/v3/"

export const suggest = async (query) {
  const url = new URL('suggest', geocoderUrl)
  url.searchParams.append('q', query)
  return await getJSON(url.toString());
}

export const lookup = async(id) => {
  const url = new URL('lookup', geocoderUrl)
  url.searchParams.append('id', id)
  return await getJSON(url.toString());
}


Replace explicit recursion with library combinators. Unduplicate and inline as much as possible.

testImpl :: Int -> (Bool, String) -> String
testImpl i (cond, msg) = unwords $
  [ if cond then "ok" else "not ok"
  , show i
  ] ++ case msg of [] -> []; m -> ["-", m]

tests :: [(Bool, String)] -> IO ()
tests xs = do
  putStrLn $ unlines $ zipWith testImpl [1..] xs
  putStrLn $ "1.." ++ show (length xs)
  if all fst xs then exitSuccess else exitFailure


Toggle functions for drop down for a clock time widget

There a few simple things you could do to help clean up this code.  The first thing I always recommend is to create a closure for your script using an IIFE.  This allows your code to run in its own scope and keeps everything out of the global scope. You can also pass in jQuery to the function expression and safely refer to it as $.

(function($, undefined ) {
  // pass in undefined for very old (ES3) browsers
  // code goes here
})( jQuery );

The next thing you should consider is caching your selections.  Since accessing the DOM is one of jQuerys slowest operations, you want to minimize this as much as possible. Anything you refer to more than once, you should cache.

var $min = $('#clockMinutes');
var $hr = $('#clockHours');

I prefix all of my jQuery selections with $ so I know they are jQuery objects.

You should also start using on for defining your events instead of the shorthand of click.  Behind the scenes, click uses on so just skip the middle man.

$min.on('click', function() {
  //code here
});

You might also want to consider DRYing your code.  Since the click functions on both the clockMinutes and clockHours are so similar, you can combine them and just pass in the "main" element you want to work on.  For example:

function updateScreen( $el ) {
  $el.slideToggle();
  if ( $el === $hour ) {
    $min.hide();
  } else {
    $hour.hide();}
  }
}

Here is an updated code sample based on the above.  Note: I call an init function on document.ready to kick off the functionality.

(function( $, undefined ) {
  //place holder variables for our selections
  var $min, $hour, $minView, $hrView;

  function init() {
    $min = $('#clockMinutes');
    $hour = $('#clockHours');
    $minView = $('#clockMinutes');
    $hrView = $('#minuteView');
    $('#hour').on('click', function() { updateScreen($hour); });
    $(' #minutes').on('click', function() { updateScreen($min); });
    $('.timeSelect').on('click', function() { updateView($hrView); });
    $('.minuteSelect').on('click', function() {updateView($minView);});
  }

  function updateView( $view ) {
    $view.val( $(this).text() );
  }

  function updateScreen( $el ) {
    $el.slideToggle();
    if ( $el === $hour ) {
      $min.hide();
    } else {
      $hour.hide();
    }
  }

  $(function() {
    init();
  });

})(  jQuery );

Hope you find this helpful. Let me know if you have any questions.


I think you need to separate the CountDownTimer class logic instead of anonymous implementation.  I just made the below sample code which I try to loose coupled the CountDownTimer from the Activity

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class MainActivity extends Activity {
    Button btnStart, btnStop;
    TextView textViewTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = (Button) findViewById(R.id.btnStart);
        btnStop = (Button) findViewById(R.id.btnStop);
        textViewTime = (TextView) findViewById(R.id.textViewTime);
        textViewTime.setText("00:03:00");
        final CounterClass timer = new CounterClass(180000, 1000);
        btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.start();
            }
        });
        btnStop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer {
        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            textViewTime.setText("Completed.");
        }

        @SuppressLint("NewApi")
        @TargetApi(Build.VERSION_CODES.GINGERBREAD)
        @Override
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;
            String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            System.out.println(hms);
            textViewTime.setText(hms);
        }
    }
}


Your outer loop…

with open('hail.in') as f:
    l = f.readline()
    while l:
        …
        l = f.readline()

… should be more idiomatically written as:

with open('hail.in') as f:
    for l in f:
        …

Also, the inner counting loop, with i += 1, would be more idiomatically written using for i in itertools.count(): ….

This code looks like you are code-golfing:

while l:
    n, a, b, i = int(l[:-1]), [], { 4, 2, 1 }, 0

While n and i are acceptable, the other one-letter names are too cryptic.  Renaming l → line, a → seq, and b → steady would make the code much easier to understand.

Why do you write l[:-1]?  Is the -1 to strip the trailing newline?  You don't need to do that: int() automatically disregards trailing whitespace.

The code for counting the steps for each n should be extracted into a separate function, since it is a deterministic function of n.

You don't need to build the list a to determine how long the sequence is.

Use the // operator for integer division.  Floating-point division is wasteful.

Instead of calling print() with multiple arguments, use one of the string-formatting mechanisms in Python (e.g. str.format() or f-strings).

Suggested solution

from itertools import count

def steps(n):
    """
    Count the number of steps for the hailstone sequence starting at n to
    reach a steady state of 4, 2, 1, 4, 2, 1, ...
    """
    for i in count():
        if n in { 4, 2, 1 }:
            return i
        n = n // 2 if n % 2 == 0 else 3 * n + 1

with open('hail.in') as f:
    for line in f:
        n = int(line)
        print('{0} steps were necessary for {1}.'.format(steps(n), n))


I would go with primitive Arrays, instead of using Collections and Streams in this case.
public static double[] to3D(double z, double[] in) {
    // Pre-allocated array 1.5 size of the original array
    double[] out = new double[in.length * 3 / 2];
    //loop with a step 2
    for (int i = 0, j = 0; i < in.length; i += 2) {
        out[j++] = in[i];
        out[j++] = in[i + 1];
        out[j++] = z;
    }
    return out;
}

public static double[] to2D(double[] in) {
    // Pre-allocated array 2/3 size of the original array
    double[] out = new double[in.length * 2 / 3];
    //loop with a step 3
    for (int i = 0, j = 0; i < in.length; i += 3) {
        out[j++] = in[i];
        out[j++] = in[i + 1];
    }
    return out;
}

Reasons for using arrays instead of lists: Input and output both are arrays, the target size is known, we only need basic operations and they would be faster in this case.
I hope it helps.


I've found another answer on https://github.com/alexhanna to this question  that I've been able to adapt and enrich to somewhat meet my needs:

import json
import sys
from csv import writer
import time
from datetime import datetime

startTime = datetime.now()

with open(sys.argv[1]) as in_file, \
    open(sys.argv[2], 'w') as out_file:
    print >> out_file
    csv = writer(out_file)
    tweet_count = 0

    for line in in_file:
        tweet_count += 1
        try:
            tweet = json.loads(line)
        except:
            pass

        if not (isinstance(tweet, dict)):
            pass
        elif 'delete' in tweet:
            pass
        elif 'user' not in tweet:
            pass
        else:
            if 'entities' in tweet and len(tweet['entities']['user_mentions']) > 0:
                user = tweet['user']
                user_mentions = tweet['entities']['user_mentions']

                for u2 in user_mentions:
                    print ",".join([
                        user['screen_name'],
                        u2['screen_name']
                        ])

#values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
#csv.writerow(values)

print "File Imported:", str(sys.argv[1])
print "# Tweets Imported:", tweet_count
print "File Exported:", str(sys.argv[2])
print "Time Elapsed:", (datetime.now()-startTime)


command-line binary/hex conversion program in python

User input validation is annoying, right? My instinct is to ask fewer
questions. Does the user really need to ask for hex or binary? For example, we
could just print both conversions. And if it's a command-line script, couldn't
the decimal number come directly from the command line? Or even a bunch of
decimal numbers and our script could convert them all.
But if we retain your current approach, the repetitiveness of the validation
suggests the need to move code into functions and to create a single function
to handle all input() calls. At a minimum, that function needs a user-prompt
and a function (or callable) that will convert the value and raise an error if
it's invalid. For example, to validate conversion type, we need to lowercase
the input and then make sure it contains a b or h. While we're at it, we
could simplify downstream logic by defining constants for conv_type.
Subsequent code can use strict equality to drive logic (rather than
looser in checks). And in this case, the constant can also serve as a label
when printing.
A consolidated approach to getting user input allows you to address
another issue: how does the user quit the program? However you
decide to handle that, it's handy to be able to do it in one place
rather than multiple.
If you strip off the 0b prefix for binary shouldn't you do the same for hex?
If so, that simplifies the logic, because we can extract the things that vary
into a data structure (converters) and then use that structure to drive the
logic. The result is that most of the "algorithm" in the main() function
fades away and we end up with very little conditional branching. Instead, it
just marches step by step, calling utility functions or accessing data
structures directly. Instead, the algorithmic complexity is delegated to
smaller and more narrowly focused utility functions that are easier to think
about in isolation.
import sys

HEX = 'hexadecimal'
BIN = 'binary'

def main(args):
    # Set up conversion functions and prefixes.
    converters = {
        HEX: (hex, '0x'),
        BIN: (bin, '0b'),
    }

    # Perform conversions.
    while True:
        # Get validated input. Since int() will raise if given
        # a bad input, we get that validation for free.
        conv_type = get_user_input('Hexadecimal or binary', is_conv_type)
        dec_num = get_user_input('Decimal number', int)

        # Convert.
        func, prefix = converters[conv_type]
        converted = func(dec_num).replace(prefix, '')

        # Report.
        print(f'    {converted} = in {conv_type}')

def get_user_input(prompt, validate):
    while True:
        # Get input and provide a way for user to quit easily.
        reply = input(prompt + ': ').lower().strip()
        if not reply:
            sys.exit()

        # Return valid converted input or nag the user.
        try:
            return validate(reply)
        except ValueError as e:
            print(f'Invalid input: {reply}')

def is_conv_type(reply):
    # Takes user input. Returns HEX or BIN if valid.
    reply = reply.lower()
    for conv_type in (HEX, BIN):
        if conv_type[0] in reply:
            return conv_type
    raise ValueError()

if __name__ == '__main__':
    main(sys.argv[1:])


Toggling?  Or setting?
Our toggleLights function is oddly named and doesn't do what I'd expect.  (Specifically, a toggle turns off things on and on things off.)
In C, and especially in embedded C, we shouldn't be afraid to use unsigned integers as bit arrays.
So, perhaps we want a setLights function that looks something like this:
void setLights(uint8_t lights) {
    LEDPORT = lights;
}

And to turn each of the eight lights on, one at a time, we can bitshift over them in our for loop:
for (uint8_t lights = 1; lights != 0; lights <<= 1) {
    setLights(lights);
    // delay
}

So now we're effectively doing what your code attempts to do, but the setLights function is even more flexible.  It just sets the lights to exactly whatever we tell it to set them to (arguably, the function may not need to exist at all... but it does restrict our input to a correct type and give us some sense of safety).

Using typedef
Firstly, we should be using a uint8_t here rather than an int because we're never going to use any values that we can't represent with 8 bits and that'll save us 24 bits.
But how about we use our own name for the type?
typedef uint8_t light_positions;

So now,our setLights function becomes:
void setLights(light_positions lights);

And our for loop becomes:
for (light_positions lights = 1; lights != 0; lights <<= 1) { // ...

This type helps add to the clarity of what this variable is supposed to represent and be used for.  This can be especially useful in embedded C where you might be prone to having lots of variables of the uint8_t type (or other sizes of unsigned integers).

lights <<= 1
<<= is a compound assignment operator.  Everyone knows and is familiar with +=, correct?  It's the most common of the ten compound assignment operators.
Meanwhile, << is a bitwise left shift operator (you used it in your toggleLights function).
So here's what's happening in our for loop.
We initialize lights to 0x00000001.  Run the loop body.  Update statement shifts lights to the left by 1 (lights <<= 1), and we end up with: 0x00000010.
We repeat this several times until we get to 0x10000000, and the next update statement shifts all of the bits out.  We end up with 0x00000000 (just 0) and the for loop exits, because lights != 0 returns false now.

About preprocessor macros...
Preprocessor macros are sometimes necessary, but generally, lead to code that is harder to debug.
Rather than your version of the macro, I think the code is more clear if we just inline it in the loop:
toggleLights(lights);
#ifdef DEBUG
    delay(1000);
#endif

Of course, if we're using the DELAYITERATIONS in multiple spots, then your version is fine--we don't want to be writing extra code necessarily.  But if we're only using it in one spot, write it more like this.

Use bools...
There are a number of ways to use true/false in C (which helps make your code more human readable).  Pick one and use it.

Hexadecimal vs Binary
Using hexadecimal notation is arguably more readable than counting the number of 1s in binary notation.  I think I'd prefer seeing 0xFF rather than 0b1111111.
Did you even notice there are only seven ones there?


Underscore template conditional can be reduced

If I understand your code correctly, it looks like you want to render tables with 3 records each, with the #header template for the top of each table and the #closer template for the bottom of each table, except for the last one, which should end with #footer instead of #closer.

First, the little things:

I think you have some unused variables in your code: It looks like dLength and done are never used.
limit is a magic number and seems out of place in your template. If I were you I would pass that number to the template function along with your other data.
You render
 several times, but element IDs must be unique in a document. We shouldn't re-use an ID.
For the last table, the
 is never rendered, so the above div is never closed! Fixing this is discussed below.
You're compiling templates inside of templates, which means that every time the outer template is rendered, you recompile the inner template, which is unnecessary and negates most of Underscore.js' rendering speed advantage. Fixing this is discussed toward the end.

Deal with groups of items, not index math

Now, on to the meat of the question. I think the biggest code smell here is the modulo arithmetic, i.e. <% if(index % limit == 0 ) { %> et al. This works, but it's hard to read. Instead, we can make the code match our intent: We want tables with 3 records each, so let our code deal with the data in groups of 3. This saves us from having to do arithmetic on their indexes—or worring about their indexes at all. Changing only the #recourseParameterTemp template, we have this:

Here's a fiddle of it in action.

I think further improvements are possible, however. For one thing, why is
 inside a sub-template, but
 is inside the main template? Not only is this an odd inconsistency, it actually introduced the missing
 bug mentioned above. We can fix this by moving Continue... and
 into the #closer template, and also adding
 to the #footer template (see this fiddle), but the bug points to a more general code smell: Templates with no closing tags, or no opening tags. If a template closes all of the tags it opens, it's much easier to notice problems like our missing
.

The single responsibility principle

We usually talk about the single responsibility principle as it relates to object-oriented programming, but it's very useful here, too: Our templates are meant to isolate blocks of code that are related, and a great template has a single responsibility. Our #recourseParameterTemp template has a bunch of responsibilities—it iterates through the data, it decides whether or not to render each
, and it decides what kind of footer render. That's too much! Using this principle, a number of possible improvements reveal themselves.

In my changes, I introduced an additional loop, i.e. I put a while around the _.each. This makes it a little harder to read, but also reminds us that it's often good to extract the inside of a loop into a sub-template that has a single responsibility. Extracting the inside of the while loop into a template called #groupTmpl (along with the #closer/#footer changes mentioned above) gives us this:

Our intent has become clearer. We see that #recourseParameterTmpl's single responsibility is to render a sub-template (#groupTmpl) once for each group, and that's all it does. This makes it easier to see the intent of the rest of the code, now in #groupTmpl. It also makes it easier to see that #groupTmpl still has multiple responsibilities: It renders the #header sub-template, it loops through each item in group, and it decides what kind of footer to render.

(You probably also noticed that I changed #recourseParamaterTemp to #recourseParameterTmpl; I did this just because "temporary" is frequently shortened to "temp" in programming; "tmpl" is less ambiguous.)

One footer template

We could extract the inside of the _.each loop into a sub-template, but I think we can agree that that's probably overkill. The main thing we can improve here is that #groupTmpl is deciding what kind of footer to render, but that shouldn't be its responsibility. Instead, we should just render one template, and let that template decide what the footer should look like. Looking at our existing #closer and #footer templates, we can see that they're almost identical, except for the contents of . It makes sense to consolidate these into one template. Removing #closer entirely, #footer and #groupTmpl now look like this (here's the fiddle):

Now #groupTmpl's intent is very clear, and we don't have any duplicated footer code.

Self-contained templates close their own tags

This is looking pretty good, but we still have the problem I mentioned above: #header opens tags that it doesn't close, and #footer closes tags that it doesn't open.

An alternative is to combine those templates into a single #wrapper template. Since Underscore.js templates don't have good support for "nested" templates, this gets a little hairy, unless we do one simple thing—which we ought to do anyway: Initialize the sub-template functions outside of the template itself. Instead of doing this:

<%= _.template($('#groupTmpl').html())( ... ) %>

We should do this, in our JavaScript:

var groupTmpl = _.template( $('#groupTmpl').html() );

...for each of our templates, and then pass the compiled template functions as locals when we use a template, which will allow us to do this in a template:

<%= groupTmpl( ... ) %>

In addition to looking cleaner, this avoids recompiling the sub-template every time the (outer) template is compiled, as mentioned above.

Along with this, instead of passing around a bunch of variables (recourseParameter, parameterCode, etc.) among our templates, it's probably a good idea to use the variable option to _.template. That is, when we call var tmpl = _.template(html, { variable: 'locals' }), then render it with tmpl({ foo: "bar" }), foo will be available as locals.foo inside the template, instead of just foo. While this seems less convenient, it lets us just pass locals to sub-templates instead of specifying the whole object. Instead of passing { variable: 'locals' } every time we compile a template, though, we can set it globally using _.templateSettings.variable = 'locals'.

Finally...

...we end up with templates that look like this:

And JavaScript that looks like this:

_.templateSettings.variable = "locals";

var tmpl = _.template( $('#recourseParameterTmpl').html() ),
    locals = {
        limit: 3,
        parameterCode: "foo",
        recourseParameter: [
            { description: "Foo 1" },
            // ...
        ]
    },
    renderedTmpl
;

locals.wrapperTmpl = _.template( $('#wrapperTmpl').html() );
locals.groupTmpl   = _.template( $('#groupTmpl').html() );
// You could also automate the above with jQuery, e.g.:
//
//     $("[type='text/template']").each(function() {
//       var el = $(this), id = el.attr('id');
//       locals[id] = _.template( el.html() );
//     });

renderedTmpl = tmpl(locals)

$('body').append(renderedTmpl)

Here's the final fiddle. I hope that's helpful!


Sometimes using arity overloading like you've done is the best way to write a function.

I tried to rewrite your function using destructuring, like this:

(defn rev [[x & more]]
  (if more
    ...

however, it doesn't really work because you need some way of storing your "result sequence" in progress, which in your function is l. Because we're trying to write a reverse function, it's hard to do what we want without having some way of "building up" the sequence as we go and storing it in an intermediate value.

Taking a look at how reverse is actually implemented in Clojure, we can see that a more concise way to express this idea of iterating over a sequence and building up a result sequence is by using reduce with a starting value of '():

(defn reverse [coll]
  (reduce conj '() coll))

The magic behind this is that we're starting with a seq, '(). When you conj something onto a seq, it adds it to the beginning, not the end. So what this does is it starts with an empty seq, then goes through the input list items one by one and adds them to the beginning of the result list, so that you end up with a list that's reversed.

EDIT: Leonid has a more thorough answer here.


Checking if three numbers sum to a given number

This is a specialised instance of the Subset sum problem, which is NP-Complete in the general case.

Of course, when working with a small subset size that is known in advance, we can significantly cut down on the running time (at worst checking C{n, k} values, where n is the number of values in the search space and k is the size of the subset we're looking for).  The O(n^3) naive algorithm here is clearly much better than the O(n!) running time of your original algorithm. However, we can get this down to O(n^2 log n) pretty easily. Firstly, sort the original array:

private int[] values;

public Subset(int[] v)
{
    values = Arrays.copyOf(v, v.length);
    Arrays.sort(values);
}

Now, we can loop over each pair of indices in the array, and binary search for the difference between the calculated sum and the desired number:

public boolean sumsTo(int num)
{
    int sum = 0;
    for(int i = 0; i < values.length - 1; ++i) {
        for(int j = i+1;  j < values.length; ++j) {
            sum = values[i] + values[j];
            if(Arrays.binarySearch(values, num - sum) > 0) {
                return true;
            }
        }
    }

    return false;
}

In fact, with a bit more stuffing around, we can get this down to O(n^2). There is an approach to do so outlined here.


Data validation for to check required fields are mapped

For readability I'd separate this into steps. Instead of doing your query within the declaration of your for loop, do it first.

var fieldMappingOptions = collectionHelper.FieldMappingOptions
    .Where(fmo =>
        fmo.IsRequired
        && !fmo.IsCalculated
        && !fmo.FieldDefinition.Equals(MMPConstants.FieldDefinitions.FieldValue)
        && (implicitParents || anyParentMappings
        || fmo.ContainerType == collectionHelper.SelectedOption.ContainerType))
    .ToArray();

var fieldMappingOptionsWithoutHelpers = fieldMappingOptions
    .Where(fmo => !collectionHelper.FieldMappingHelpers
            .Any(fmh => fmh.SelectedOption.Equals(fmo)));

foreach(var fieldMappingOption in fieldMappingOptionsWithoutHelpers)

What this achieves is that the reader can break this into multiple steps: First, which fieldMappingOptions you're looking for, and second, what you're going to do with them, instead of trying to read all of that at one time.

Any way you can limit how many things that future developer has to follow at the same time will help him or her to read and understand your code more quickly.

That also means that you can potentially break it apart as needed more easily. For example, if the method gets too long, you could separate the first two lines into their own function that returns IEnumerable<FieldMappingOption>.

Also, every time you break up these steps you're going to have to declare a variable or a function, and every time you do that you get to give it a name. If the names are meaningful then your code becomes more self-documenting. That future developer might also be able to skip over parts they don't care about more quickly while still having some idea what those parts are, based on the names of the methods called.

Even some of the conditions in the Where clause could potentially be functions if that makes it more readable.

Just as an example:

public static void RequiresValue(this FieldMappingOption fieldMappingOption)
{
    return fieldMappingOption.isRequired
      && !fmo.IsCalculated
      && !fmo.FieldDefinition.Equals(MMPConstants.FieldDefinitions.FieldValue);
}

Now your Where clause could read:

var fieldMappingOptions = collectionHelper.FieldMappingOptions
    .Where(fmo =>
        fmo.RequiresValue()
        && (implicitParents || anyParentMappings
        || fmo.ContainerType == collectionHelper.SelectedOption.ContainerType))
    .ToArray();

(I have no idea if I got the logic or intent right.)

But that's the gist of my recommendation. Keep LINQ as readable as possible, don't feel like the whole thing has to be in one statement, and keep methods short (15 lines or less.)


Sort function to sort item numbers separated by colon

@Flambino was a bit faster :

function sortSKU( a, b  )
{
    var aParts = a.split( ':' ),
        bParts = b.split( ':' ),
        partCount = aParts.length,
        i;

    if( aParts.length != bParts.length )
        return aParts.length - bParts.length;

    for( i = 0 ; i < partCount ; i++ )
    {
      if( aParts[i] != bParts[i] )
        return +aParts[i] - +bParts[i];
    }
    //Exactly the same
    return 0;
}

console.log( data.sort( sortSKU )  );

As Flambino said, use .reverse() to sort one way or another. Also this function will sort 123 prior to 2:2 if such a case can occur.

If you need the 'c'

function sortingCallback( array, direction ){

  if( direction == 'whatever ascending is' ){
    return array.sort( sortSKU );
  }

  return array.sort( sortSKU ).reverse();
}


First of all, you should definitely re-use the same session for multiple requests to the same domain - it should result into a performance improvement:

  if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase

Other Improvements

improve naming: you are over reusing item and titles variables. Instead, think of more appropriate and meaningful variable names. Also, I don't think the "_stuff" prefix contributes to readability and ease of understanding of the program
put the main script execution logic to under if __name__ == '__main__': to avoid executing it on import
you can avoid inner loops and iterate directly over hrefs here:

for link in tree.xpath("//a[@class='sidebar-item-label']/@href"):
    paging_stuff(link)

And here:

for link in tree.xpath("//ul[@class='pagination']//a[@class='pageNumber']/@href"):
    processing_stuff(link)

instead of putting comments before the functions, put them into appropriate docstrings

Notes

Note that you should realize that your solution is synchronous - you are processing urls sequentially one by one. If performance matters, consider looking into Scrapy.


I have a very good solution for you. See the below two blog posts:

  Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit
  Testing Triangle

  How to Work With Generic Repositories on ASP.NET MVC and Unit Testing
  Them By Mocking

What I can suggest more is this:

Implementing IDisposable:

Implement IDisposable on your repository and dispose them on your controller by overriding the Controller.Dispose method. Sample:

IContactRepository:

public interface IContactRepository : IDisposable {

    //same as above
}

Add the below code to your ContactRepository class:

private bool disposed = false;

protected virtual void Dispose(bool disposing) {

    if (!this.disposed)
        if (disposing)
            addressBookdb.Dispose();

    this.disposed = true;
}

public void Dispose() {

    Dispose(true);
    GC.SuppressFinalize(this);
}

On your controller, add this code:

protected override void Dispose(bool disposing) {

    contactRepository.Dispose();

    base.Dispose(disposing);
}


Not really. It hard to optimize something with little logic. You could do this instead:

var row =
    "
 \

 \
            \

" + a + "
 \
           	 \

 \

";

But aside from that looks good!


button.onclick = function() {

Use addEventListener instead. That way, you can add as many handlers as you want without replacing any previous ones assigned.

if (div.style.display !== 'block') {

Instead of using inline CSS, put them in stylesheets and define the styles in classes. Then have JS assign/remove classes instead to apply/remove. The problem is that 1) You have CSS in your JS and 2) inline CSS have very high specificity. The only way to override them is to replace the inline style value, or use !important on the stylesheet.

if(document.body.clientWidth > 900) {

If you also use CSS, this can easily be remedied by media queries.

if(window.location.href.indexOf("home.php") > -1) {

You probably want to use a more robust routing library like Page.js to do this.


Change case of string, replace hyphens with spaces and capitalize first letter

Some things:

That pretty variable is pretty useless. Omit it.
temp is quite meaningless. Use a descriptive name like words or parts.
You could use the Array map method instead of that for loop. This will likely be slower, but more elegant:

function prettify(str) {
    return str.split('-').map(function capitalize(part) {
        return part.charAt(0).toUpperCase() + part.slice(1);
    }).join(' ');
}

regular expressions and the String replace method could further shorten it, and possibly improve performance:

function prettify(str) {
    return str.replace(/(-|^)([^-]?)/g, function(_, prep, letter) {
        return (prep && ' ') + letter.toUpperCase();
    });
}

Decide yourself whether this is too cryptic or not.


There's nothing particularly wrong with the code.  It happens often enough that this question has plenty of upvotes.

Marc Gravell gives the exact code that you have.  But you can go take a look at the link for ideas about using extension methods to make calling the conversion nicer and possibly adding an "IsDefined" check in case the enums get out of sync sometime in the future.


The IDE you linked uses CLISP, which is a bit lenient; when I evaluate
that definition, I immediately get two warnings from SBCL:

; in: DEFUN COUNT-UP-DOWN-CHARACTERS-WITH-DIFFERENCE
;     (SETF COUNT-DOWN 0)
; ==>
;   (SETQ COUNT-DOWN 0)
;
; caught WARNING:
;   undefined variable: COUNT-DOWN

;     (SETF COUNT-UP 0)
; ==>
;   (SETQ COUNT-UP 0)
;
; caught WARNING:
;   undefined variable: COUNT-UP
;
; compilation unit finished
;   Undefined variables:
;     COUNT-DOWN COUNT-UP
;   caught 2 WARNING conditions

That is because count-up and count-down weren't defined anywhere.
It's implementation-defined what happens in this case.

So firstly let's define them with defvar:

(defvar *count-up*)
(defvar *count-down*)
...
(defvar +night-before-xmas+ "...")
...

(Constants usually have + as markers, globals *.  Indentation is
usually a bit different as well, I'm only going to show the
Emacs-formatted code without more explanation though.)

Then again, if you want a functional solution, don't use setf (that
is, assignment) or globals at all.  Instead (and in general) prefer
let.

A few other things to make it more idiomatic (for some value of
idiomatic) are the use of the most strict equality operator possible,
which here would be eql (since you check for exact equality between
characters), and not using if if there's only one case, instead when
or unless would be preferable.

(defun count-up-down-characters-with-difference (input-string up-char down-char)
  "..."
  (let ((count-up 0)
        (count-down 0))
    (loop
      for c across input-string
      do (when (eql c up-char)
           (incf count-up))
         (when (eql c down-char)
           (decf count-down)))
    (list count-up count-down (+ count-up count-down))))

loop also has more grammar to compress it more, but I think this is
fine for now.  Also consider using count instead of a manual loop, i.e.:

(defun count-up-down-characters-with-difference (input-string up-char down-char)
  "..."
  (let ((count-up (count up-char input-string))
        (count-down (- (count down-char input-string))))
    (list count-up count-down (+ count-up count-down))))

Or also (count up-char input-string :test #'char-equal) (see COUNT).


How to make this code of shortest Path Finder more maintainable,extendable and get better static code analysis result?

How to improve the overall code quality?

I don't know much about C#, but I guess your analyzer is complaining mainly about the length of your method and its cyclomatic complexity. Try to split it in multiple well named methods and use guard conditions to reduce the nesting level of your ifs.

Maybe you could also use the ternary operator instead of the if in your first foreach to extract the common part of the if branches. But this is an highly discussed topic.

How can I make it more extendable or maintainable?

There is no real use in making something extensible, that you never plan to extend. So if you don't know possible (useful) extension points, you shouldn't desperately try to find some. You can refactor it later when you need it.

Maintainable is in general achieved by readable code and a good test base. If you are not afraid of breaking something, you can do everything with your code easily.

Will employing some specific Design Pattern here would have mad more sense?

Actually I would say, you applied the Strategy pattern here already. This is more or less the default use case, having an interface and change the path finding algorithm. (Maybe building the graph should be splitt from traversing)


Converting an input audio file to a monophonic FLAC file

I think your code would become much simpler and more readable if you encapsulated all the BASS-related functionality from into separate types.

Something like:

class Stream
{
    private readonly int handle;

    // add overload that supports setting offset and lenght, if you need that
    public Stream(string inputFile, BASSFlag flags)
    {
        handle = BASS_StreamCreateFile(inputFile, 0, 0, flags);

        if (handle == 0)
            throw new BassException("Could not create stream");
    }

    public ChannelInfo GetInfo()
    {
        var result = Bass.BASS_ChannelGetInfo(stream);

        if (result == null)
            throw new BassException("Could not retrieve stream info");

        return result;
    }

    // etc.
}

This would simplify the start of your code to just:

Stream stream = new Stream(inputFile,
    BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
var info = stream.GetInfo();


def validateIP(ip):

I would expect a name starting is (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. is_valid_IPv4_address.

  #split them by '.' , and store them in an array
  #check the array if the length is 4 length
  arr = ip.split('.')
  if len(arr) != 4:
    return False

The comments don't tell me anything which the code doesn't already. In general, good comments explain why, not what.

  #0 check for special edge cases when non-digit
  #1. check if they are digit,
  #2. check if check the integer is between 0 and 255

  for part in arr:
    .. various conditions which return False
  return True

IMO it would be more Pythonic to use all: I would boil the whole function down to

    parts = ip.split('.')
    return len(parts) == 4 and all(is_valid_IPv4_address_part(part) for part in parts)

    if len(part) > 1:
      if part[0] == '0':
        return False

This isn't in the spec. It's a reasonable constraint, but you should check with the person who gave you the spec before writing the code, or at least put in a comment saying that you're making an assumption about the true intentions of the specifier.

    if not part.isdigit():
      return False

This is buggy. (Before testing I thought there was an issue which should be bounced back to the specifier. Upon testing, I found that some of my test cases caused validateIP to throw an exception).

What is the expected output for these test cases?

¹.¹.¹.¹
١.١.١.١
...
①.①.①.①