Freeing a binary tree data structure in C

1. Bug

JS1 is quite correct to point out that this does not work: it never visits or frees tree->yes->no (among other nodes).

2. Correct algorithm

Consider a finite state machine with three states:

If tree has a left child, set tree to its left child and go to state 1. Otherwise, go to state 2.
If tree has a right child, set tree to its right child and go to state 1. Otherwise, go to state 3.
(In this state tree has no children.) Destroy tree. If tree had no parent, stop. Otherwise, delete whichever of parent's children is equal to tree, set tree to parent and go to state 1.

This state machine walks the tree in post-order, destroying each node after destroying all of its descendant nodes. Here's one way of translating this into C:

void TreeDestroy(Tree *tree)
{
    for (;;) {
        if (tree->left) {
            tree = tree->left;
        } else if (tree->right) {
            tree = tree->right;
        } else {
            Tree *parent = tree->parent;
            free(tree->value);
            free(tree);
            if (!parent)
                break;
            else if (parent->left == tree)
                parent->left = NULL;
            else if (!parent->left && parent->right == tree)
                parent->right = NULL;
            else
                assert(0); /* can't happen if tree is well-formed */
            tree = parent;
        }
    }
}

(I've used "left" and "right" here because these are the more usual names for the two children of a node in a binary tree.)

3. What if there are no parent pointers?

To iteratively destroy a binary tree with no parent pointers, start with the rotate right operation:

void TreeRotateRight(Tree **tree)
{
    Tree *left = (*tree)->left;
    (*tree)->left = left->right;
    left->right = *tree;
    *tree = left;
}

By repeatedly applying the rotate right operation, you can turn a tree into a vine. (A vine is a degenerate tree in which nodes only have right children.)

void TreeToVine(Tree **tree)
{
    while (*tree) {
        while ((*tree)->left)
            TreeRotateRight(tree);
        tree = &((*tree)->right);
    }
}

And then a vine is easy to destroy iteratively:

void TreeDestroy(Tree *tree)
{
    TreeToVine(&tree);
    while (tree) {
        assert(!tree->left);
        Tree *right = tree->right;
        free(tree->value);
        free(tree);
        tree = right;
    }
}


Updating user log in time while he logs in to the web page

The first point I notice looking at your code is that it looks as though you are storing passwords in plain text. You should not do this. It is highly irresponsible. They should be salted and hashed in almost all cases.

Secondly there is no point looking up the same information three times.

Once to check if it exists, secondly to update it, and thirdly to select it.

You can do all this in one operation.

ALTER PROCEDURE [dbo].[WP_LogInUser] @Username NVARCHAR(100),
                                     @Password NVARCHAR(100)
AS
  BEGIN
      UPDATE TableName
      SET    UserLastLogin = GETUTCDATE()
      OUTPUT INSERTED.UserID,
             INSERTED.Username,
             INSERTED.UserEmail,
             INSERTED.UserFullName,
             INSERTED.UserType
      FROM   TableName
      WHERE  Username = @Username
             AND UserPassword = @Password
             AND IsActive = 1
  END


Symfony controller that registers a user via HTTP-POST

I feel like my controller is too big and the function does too much.

I think you're right there. Your validation rules shouldn't be in the controller, but in separate classes. That makes re-using them much easier. I

  My initial hunch is that I should put this into a service and break it
  up. But it seems like I would just be copying and pasting this code
  into class.

You're right here. Just moving code from your controller to a service makes no sense.

Why aren't you using Symfony Forms? It does exactly the job you're doing here: take the Request and some rules and tell you if the request matches your validation rules.

You can create an object (a Doctrine entity or a Data Transfer Object, DTO), add the constraints to it by using annotations.

See this to examples from https://stovepipe.systems/post/avoiding-entities-in-forms:

Your DTO:

class ChangeUsernameData
{
    /**
     * @Some\Custom\Assert\Unique(entity="App\Entity\Authentication", field="username")
     * @Assert\Length(5, 16)
     **/
    public $newUsername;
}

Your controller:

$changeUsername = new ChangeUsernameData();
    $form = $this->formFactory->create(ChangeUsernameType::class, $changeUsername);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $authentication->setUsername($changeUsername->newUsername);
        $this->em->flush($authentication);

        // redirect
    }


int v = b ? (a ? 1 : 2) : (a ? 0 : 1);

EDIT #1:

As per svick, parsed out conditional operator on separate lines:

int v = b
    ? (a ? 1 : 2)
    : (a ? 0 : 1);

EDIT #2:

Here's one I don't like, but it has no branching whatsoever:

int v = Convert.ToInt32(b) + Convert.ToInt32(!a);


Outputting years with no repeated digits

The model solution they propose is very unidiomatic, your code is far better. I'd just made some minor changes:

Use String#chars instead of String#split(//).
Use Enumerable#select? instead of Array#keep_if to avoid modifying data in-place. It's better to work with immutable streams of data (with methods from Enumerable).

I'd write:

def no_repeats(year_start, year_end)
  (year_start..year_end).select { |year| no_repeat?(year) }
end

def no_repeat?(year)
  year_digits = year.to_s.chars
  year_digits == year_digits.uniq
end


Eliminate size

The size function is not useful. Imagine if one list contains 1 element and the other contains a million. If you're lucky you might traverse the shorter list first, and use that size to stop traversing the second list early when possible.

Instead of trying to check the size first, you could adjust the main loop in add from this:

while (l1 != NULL) {

to this:

while (l1 != NULL && l2 != NULL) {

and add this condition after, to prepare for the second loop:

if (l1 != NULL) {
    l2 = l1;
}

More natural int carry

Instead of bool carry_over, it would be more natural to have an int carry, with 0 or 1 as values. The end result is the same, but more natural, less surprising.

Duplicated adding logic

The logic of adding is duplicated several times:

For the first pair of elements
For the pairs of elements while exist
For the remaining elements of the longer list

You can easily eliminate the first, by using a dummy node to mark the head of the new list. The value of this node will not be used, but dummy->next will point to the first element. In addition, this little trick will make the implementation more robust, and handle the case when one of the lists is empty (null).

Declare variables in the smallest scope

There's no need to declare x at the top. You can declare it inside the loops where needed.

Naming

Lowercase l is one of the worst possible names for a variable. In some fonts it might look like the number one. Almost any name would be better than that. For example node.

Braces

It's recommended to use braces always, even with single-statement if.

Suggested implementation

Applying the above suggestions, the implementation becomes:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        return add(l1, l2);
    }

private:

    /**
     * Input: Two lists l1 and l2 with size(l1) <= size(l2)
     * Output: result list
     */
    ListNode* add(const ListNode *l1, const ListNode *l2) {
        // dummy node, helps simplify the code a bit
        ListNode dummy(0);
        ListNode *node = &dummy;

        int carry = 0;

        while (l1 != NULL && l2 != NULL) {
            int x = l1->val + l2->val + carry;
            if (x > 9) {
                carry = 1;
                x -= 10;
            } else {
                carry = 0;
            }
            node = node->next = new ListNode(x);
            l1 = l1->next;
            l2 = l2->next;
        }

        if (l1 != NULL) {
            l2 = l1;
        }

        while (l2 != NULL) {
            int x = l2->val + carry;
            if (x > 9) {
                carry = 1;
                x -= 10;
            } else {
                carry = 0;
            }
            node = node->next = new ListNode(x);
            l2 = l2->next;
        }

        if (carry) {
            node->next = new ListNode(1);
        }

        return dummy.next;
    }
};

Speed

I suppose the exercise comes from here.
I don't know how to make this faster.
I submitted your original code, and some variations, but the result appears to be randomly within 36-56ms. At 36ms it beats 64% of submissions, at 40ms it beats only 18% of submissions. But I don't think speed is important at all. The time complexity of your algorithm is \$O(n)\$, and I don't think it's possible to solve this problem faster than that. Any speed optimizations at this level are just micro-optimizations, neither relevant nor interesting.


Reading/writing null-terminated strings from socket

I would accumulate bytes instead of integers.

(define (read-c-str inp)
  (define (read-to-zero acc)
    (define b (read-byte inp))
    (if (equal? b 0)
        (blist->string acc)
        (read-to-zero (bytes-append acc (bytes b)))))
  (read-to-zero #""))

And change blist->string accordingly.

Edit: in this case blist->string will become just bytes->string/utf-8 .


Fetching data from your database in a constructor

First of all, it violates the "tell don't ask" principle: if your OptionInstallItem is not inherently coupled to the database and its actions (and as you do not even record the reference to the refmanager, it obviously isn't) it should not go about scavenging in your whole application to get its job done. Always give every class exactly what it needs to operate, not the "master key" for self service.

Then, your way makes it unnecessarily hard to test. If you have a simple object along the lines of

public MyClass(String myLabel) {
    this.myLabel = myLabel;
}

Testing is as simple as can be:

MyClass testObject = new MyClass("test");
Assert....

On the other hand, if you have

public MyClass(DatabaseInterfaceThingy database) {
    this.myLabel = database.doSomeQueryForMyLabel("me");
}

... say hello to mockito to even instantiate that object.

And send your colleagues over to Codereview to learn a few things and be able to tell you "why" the next time ... ;-)


Return Full Month Name From 3 Letter Month

The following avoids assumptions about and/or the need to convert according to culture, by letting the tried-and-tested DateTime plumbing do the work.  Creating a translation map once at first instantiation of the class (the static constructor) is the best I can think of to optimise performance.

If you use it, don't forget to do error-checking - specifically the result of TryParse.

using System;
using System.Collections.Generic;

public class Program
{
  private static readonly Dictionary<string, string> MonthNameMap;
  //  Static constructor to build the translation dictionary once
  static Program()
  {
    MonthNameMap = new Dictionary<string, string>();
    //var months = new List<string>() { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    //foreach (var shortMonthString in months)
    //{
    //  DateTime.TryParse($"1 {shortMonthString} 2000", out var dt);
    //  MonthNameMap.Add(shortMonthString, dt.ToString("MMMM"));
    //}
    for (int i = 1; i <= 12; i++)
    {
      DateTime.TryParse($"2000-{i}-25", out var dt);
      MonthNameMap.Add(dt.ToString("MMM"), dt.ToString("MMMM"));
    }
  }

  public static void Main()
  {
    foreach (var entry in MonthNameMap)
    {
      Console.WriteLine($"{entry.Key}: {entry.Value}");
    }
  }
}

Results:

Jan: January
Feb: February
Mar: March
Apr: April
May: May
Jun: June
Jul: July
Aug: August
Sep: September
Oct: October
Nov: November
Dec: December


You use root as parameter name when you pass the list around but I think a better name would just be list. root implies that you pass the first node of the list around rather than the container.
++root->node_count is correct but root->node_count += 1 reads nicer (imho).
I would consider changing the interface slightly:

Have a List* new_list() method which creates the list (and initializes the object).
delete_list should also delete the list object (probably needs signature change to delete_list(List **list))
Add a method clear_list which just clears the contents of the list.

Right now the programmer has to remember whether a node was added via add_node or add_node_store in order to call the proper delete function. However this could be solved by having a flag in nNode which indicates whether the node owns the content or not. Delete could then automatically do the right thing.


Am I missing some things from the problem requirements?

I would say that you are:

  Create a class diagram and Java code for the following system and scenario, taking into account the possibility of future extensions.

You don't really have classes (and thus also didn't really take into account future extensions).

I would think that the expectation is something like this:

Create classes Quote, Person (for the attribution, maybe also an Attribution class), a class containing a collection of Quotes, from which you can retrieve items via index, an Output class with methods for print quote and print attribution.

That way, it would be easy to add a GUI for output, to add additional attribution information, add a date for the quote, etc.

Misc

There isn't really much to your code to review, but a couple of points:

you should not have all your code in the main method. The main method should only start your program, not perform any actions itself.
package names should be all lowercase
extract magic numbers to fields (but if you actually change your code as I suggested above, you would not need it at all)


Consider that Bool is an algebraic data structure like any other in Haskell. Pattern matching is the most elegant solution, but you can use even more of it to be even more elegant!

-- import Prelude hiding (or)

or :: [Bool] -> Bool
or []         = False
or (False:bs) = or bs
or (True :_ ) = True


Since the Fibonacci algorithm is so nice and clean there is one little nitpicky thing to add. You don't need to directly return 0 and 1 in the base cases, you can just return n. So the function can be rewritten (in Javascript, my experience with Python is extremely subpar) as:

var fib = function(n) {
    if(n === 0 || n === 1) {
        return n;
    }

    return fib(n - 1) + fib(n - 2);
}

The algorithm is beautiful but it also does a lot of extraneous work when run in a loop, that can be removed with the technique of memoization (again, to keep these tests fair, I think (?) this is possible in Python as well but someone else could be of more use in helping with the code). In this specific case, the technique is incredibly easy to employ with a simple Javascript object as a cache

var fib = (function() {
    var cache = {};

    function fibonacci(n) {
        if(n === 0 || n === 1) {
             return n;
        }

        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    return function(n) {
       if(n in cache) {
           return cache[n];
       }

       return fibonacci(n);
    }
}());


Setting QProgressBar values based on selection

One idea would be to gather all your techs in a queue and iterate over that, updating the progress as you go.

Since my Python is rather Rust-y (I'm sorry for that pun), here's some pseudocode:

# Setup progress bar et cetera
# Gather techs in a queue
techs = Queue()
if pv_checkBox.isChecked():
    techs.add(pv_task)
if wind_checkBox.isChecked():
    techs.add(wind_task)

# Do the work
total_tasks = techs.count()
done_tasks = 0
while not techs.isEmpty():
    task = techs.take()
    task.doWork()
    done_tasks += 1
    new_progress = max(done_tasks / total_tasks * 100, 99)
    progress.setValue(newProgress)

# Progress is now 99
doFinalStuff()
progress.setValue(100)

This will do all the tasks in a FIFO fashion and set the progress as you wanted with the last step always being 99.

Now, it would be a good idea to gather all checkboxes in a group or layout and, by getting and filtering all child elements, add the techs via loop as well.


I (and many other people) expect certain behavior from a function called "assert"...namely that it throws an exception or otherwise halts execution if the asserted condition isn't true.  If your assert function did that, you wouldn't have to test the return value.

function assertEqual(a, b, message)
{
    if (a != b) throw new Error(message + " mismatch: " + a + " != " + b);
}

assertEqual(parsedInput.protocol, cu.protocol, "protocol");
assertEqual(parsedInput.port,     cu.port,     "port");
assertEqual(parsedInput.hostname, cu.hostname, "hostname");
assertEqual(parsedInput.hash,     cu.hash,     "hash");

If that's not what you want, then you should seriously consider renaming your function.  Maybe check or something, i dunno.  Assertions die when they're false.

Now, as for your equality tests, you could do something like

function propsEqual(obj1, obj2, propNames) {
    var result = true;
    for (var i = 0; i < propNames.length; ++i) {
        var prop = propNames[i];
        if (obj1[prop] != obj2[prop]) {
            console.log("Failed to match " + prop +": " + obj1[prop] + " != " + obj2[prop]);
            result = false;
        }
    }
    return result;
}

if (!propsEqual(parsedInput, cu, ["protocol", "port", "hostname", "hash"])) {
    console.log("Skipping.");
    continue;
}

Benefits of this approach being, you get to see all of what doesn't match, rather than stopping at the first thing.


Suggestions:

Most of your lambdas are unnecessary wrappers around perfectly fine functions, so I'd just use the latter instead.
The list in (*list(map(...))) is unnecessary, just unpack the iterable that map gets you.
There's nothing else in your code, so importing it doesn't give you anything, so you'd just run the script, so if __name__ == '__main__': is rather pointless.
I'd read the number of commands only when I need it, not early.
I find my_list unnecessarily verbose, a commonly used name is lst.
Indent the dict arguments by the standard four spaces instead of eight.
So, rewritten:

lst = []

commands = dict(
    insert=lst.insert,
    print=lambda: print(lst),
    remove=lst.remove,
    append=lst.append,
    sort=lst.sort,
    pop=lst.pop,
    reverse=lst.reverse
)

for _ in range(int(input())):
    command, *args = input().split()
    commands[command](*map(int, args))

As shown in some other solutions in the discussion, we can use getattr instead of building our own dict serving pretty much the same purpose. I didn't see anyone using its default parameter, though, which can neatly cover the print command:
lst = []
for _ in range(int(input())):
    command, *args = input().split()
    getattr(lst, command, lambda: print(lst))(*map(int, args))


Function to print command-line usage for a program

You can use textwrap.dedent to remove common whitespace from the start of all lines in a multiline string:

>>> import textwrap
>>> print(textwrap.dedent(
        """
        Usage examples:
        Test deployment:
            $ fab [noinput] test deploy
        Staging deployment:
            $ fab [noinput] staging deploy
        Production deployment:
            $ fab [noinput] production deploy
        """
))

Usage examples:
Test deployment:
    $ fab [noinput] test deploy
Staging deployment:
    $ fab [noinput] staging deploy
Production deployment:
    $ fab [noinput] production deploy

As it says in the docs:

  This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.


Printing the values on each level of a Binary Tree

This is good code.

General

While it does what it says it will do, here is one beef I have with it, but it's a small one:

    Node temp = que.poll();
    if(temp != mark)
    System.out.print(temp.key);

No braces, no indenting, code meaning is confused.....

That should be:

    Node temp = que.poll();
    if(temp != mark) {
        System.out.print(temp.key);
    }

There is a fair amount of debate about using '1-liner' if statements. The following are reasons why I despise them:

the meaning of the code becomes white-space defined (like your indenting problem above). There are whole languages ( cough Pythong cough ) which are defined by whitespace. Java is defined by braces {}. Use them.
If you use a version-control-system like CVS, SVN, Git, etc. then small changes to code blocks can become visually big in a change-log. Adding one line to the code means updating 3 lines.
it can lead to bugs where people do not put braces in to lines where there should be two statements.
etc.
etc.

I don't like 1-liners Sam-I-Am

OK. But, as code goes, yours is good. How can it be better?

Improvements

You can make mark a private static final instance:

private static final Node MARK = new Node(0);

The following statement has redundancy:

        if(que.peek() == mark || que.isEmpty()){
            return;
        }

it could be:

        if(que.isEmpty()){
            return;
        }

It is not possible for the queue to have two consecutive marks, so the peek can never be a mark.
Now, back to that indentation on the println() method call... here's your code:

    if(temp != mark)
    System.out.print(temp.key);
    if(temp == mark){
        if(que.peek() == mark || que.isEmpty()){
            return;
        }
        que.add(mark);
        System.out.println();
    }

if you had correct braces, etc. you would see that you would be better off with an if/else condition, and that will save an if check:

    if(temp != mark) {
        System.out.print(temp.key);
    } else {
        if(que.peek() == mark || que.isEmpty()){
            return;
        }
        que.add(mark);
        System.out.println();
    }

System.out.println(...) and all the print*(...) variants are slow (they are synchronized). Your code would be faster if you used a system like:

StringBuilder sb = new StringBuilder();
....

    if (temp != mark) {
        sb.append(temp.key);
    } else {
        ....
        sb.append("\n");
    }

....
System.out.print(sb);

Conclusion

Otherwise, this is good code.


Script to print weather report from OpenWeatherMap API

For your first question, yes, breaking down functions to do really specific things is always good. Makes it easier to use the same functions again in other situations etc.

For your second question, I would personally only call one function at a time, for me it makes it easier to read and understand.

Also, you can have a single print statement for a multi-line string for example:

print('''' Hello
world
      isn't this cool?'''

and that would print:

Hello
world
      isn't this cool?

but in your circumstance it might be a little bit difficult with all those format().


Finding decreasing sequences in an array of numbers

Some general remarks:

Don't use namespace std;, see for example Why is “using namespace std;” considered bad practice?.
Define variables at the narrowest possible scope. In particular, avoid
global variables.
Use better variable names. It is unclear what each variable in

int n,i,v[100001],nr,j,s;

stands for.
return 0; at the end of the main program can be omitted.
The range of integer types is implementation defined, the C++ standard only
guarantees that a (signed) int can hold values from -32767 to 32767,
which is too small for your numbers. Many compilers define int as a 32-bit
integer, but you can use long to be on the safe side, or use fixed-size
types like int32_t.

With respect to readability, I recommend to leave more (horizontal) space,
e.g. around operators and parentheses.

There are two places with identical code to count the divisors
of a number. This should be done in a separate function.

Your code uses a nested loop where the inner loop updates the index of the
outer loop. That is difficult to understand and error-prone. And it is
not necessary: Instead of starting a nested loop when the start of a
decreasing subsequence is found, set a flag instead and continue with the
main loop.

You store all numbers from the input file in an array, which is not necessary:
each loop iteration only needs the previous number to decide if the subsequence
is (still) decreasing. It suffices to store the previously processed number
in a variable.

Summarizing the suggestions so far, the code could look like this:

#include <fstream>
#include <cmath>

long numberOfDivisors(long n) {
    long count = 0;
    for (long j = 2; j <= sqrt(n); j++) {
        if (n % j == 0) {
            count++;
            if (j != n/j)
                count++;
        }
    }
    return count;
}

int main()
{
    std::ifstream inFile("furnici.in");
    std::ofstream outFile("furnici.out");

    long decreasingSequences = 0;
    bool isDescending = false;
    long lastDivisorCount = 0;
    long numDays;
    inFile >> numDays;
    for (long i = 1; i <= numDays; i++) {
        long numAnts;
        inFile >> numAnts;
        long divisorCount = numberOfDivisors(numAnts);
        if (divisorCount >= lastDivisorCount) {
            // No longer decreasing.
            isDescending = false;
        } else if (!isDescending) {
            // A decreasing subsequence started right here.
            isDescending = true;
            decreasingSequences += 1;
        }
        lastDivisorCount = divisorCount;
    }
    outFile << decreasingSequences;
}

Now you can start to improve the performance, and the prime candidate is
of course the numberOfDivisors() function.

An efficient method (and I'm repeating arguments from Getting all divisors from an integer now) is to use the prime factorization:  If
$$
 n = p_1^{e_1} \, p_2^{e_2} \cdots p_k^{e_k}
$$
is the factorization of \$ n \$ into prime numbers \$ p_i \$
with exponents \$ e_i \$, then
$$
 \sigma_0(n) = (e_1+1)(e_2+1) \cdots (e_k+1)
$$
is the number of divisors of \$ n \$, see for example
Wikipedia: Divisor function. Example:
$$
 720 = 2^4 \cdot 3^2 \cdot 5^1 \Longrightarrow
  \sigma_0(720) = (4+1)(2+1)(1+1) = 30 \, .
$$

Here is a possible implementation in C:

long numberOfDivisors(long n){

    long numDivisors = 1;
    long factor = 2; // Candidate for prime factor of `n`

    // If `n` is not a prime number then it must have one factor
    // which is <= `sqrt(n)`, so we try these first:
    while (factor * factor <= n) {
        if (n % factor == 0) {
            // `factor` is a prime factor of `n`, determine the exponent:
            long exponent = 0;
            do {
                n /= factor;
                exponent++;
            } while (n % factor == 0);
                // `factor^exponent` is one term in the prime factorization of n,
                // this contributes as factor `exponent + 1`:
                numDivisors *= exponent + 1;
        }
        // Next possible prime factor:
        factor = factor == 2 ? 3 : factor + 2;
    }

    // Now `n` is either 1 or a prime number. In the latter case,
    // it contributes a factor 2:
    if (n > 1) {
        numDivisors *= 2;
    }

    return numDivisors;
}

As a further improvement you can pre-compute the prime numbers with a
sieving method. Note that it sufficient to pre-compute the primes in the
range \$ 2 \ldots \sqrt{N} \$ where \$ N = 10^9 \$ is the upper bound for the given input.  That should help to stay within the given memory
limit of 64 MB.


Your setup is going to eventually be working around Rails configurations, which are built for the canonical index, new, create, show, edit, update, delete.

Rails does resource routing for this very reason (read more in the Rails Guide on Routing). It's also very in-line with HTTP verb standards and will make turning this into a JSON API trivial, should you need one.

Since your Employer and Employee are separate domain objects, I would make them separate controllers. This leaves some nice future options for other actions when you need them like edit and destroy.

class EmployerController < ApplicationController
  def new
    @employer_signup = EmployerSignup.new
  end

  def create
    @employer_signup = EmployerSignup.new(params[:employer_signup])

    if @employer_signup.save
      sign_in @employer_signup.user
      redirect_to root_path, notice: 'You signed up successfully.'
    else
      render action: :employer_registration
    end
  end
end

class EmployeeController < ApplicationController
  def new
    @employee_signup = EmployeeSignup.new
  end

  def create
    @employee_signup = EmployeeSignup.new(params[:employee_signup])

    if @employee_signup.save
      sign_in @employee_signup.user
      redirect_to root_path, notice: 'You signed up successfully'
    else
      render action: :employee_registration
    end
  end
end


Is it fine to typecast from one implementation type to another while using an object?

Composition over inheritance and Strategy Pattern

I would, instead of having differents weapons implementing differents interfaces defining their behaviour, create classes that holds the logic of the behaviour

Let's consider a weapon can have a primary attack, a secondary one and reload.

The class could be defined as such :

abstract class Weapon
{
    public IWeaponPrimaryAttack WeaponPrimaryAttack { get; set; }
    public IWeaponSecondaryAttack WeaponSecondaryAttack { get; set; }
    public IReloadable Reloadable { get; set; }
}

Now, we can define classes that holds differents behaviours of the interfaces.

In example :

public class SlashAttack : IWeaponPrimaryAttack
{
    public void DoAttack()
    {
        Console.WriteLine("Performing a slash attack");
    }
}

public class StabAttack : IWeaponSecondaryAttack
{
    public void DoSecondaryAttack()
    {
        Console.WriteLine("Performing a stab attack");
    }
}

public class Shooting12Caliber : IWeaponPrimaryAttack
{
    public void DoAttack()
    {
        Console.WriteLine("Bam !");
    }
}

public class Caliber12Reloader : IReloadable
{
    public void Reload()
    {
        Console.WriteLine("Reloading caliber 12 !");
    }
}

public class ShootingWith556 : IWeaponPrimaryAttack
{
    public void DoAttack()
    {
        Console.WriteLine("Bam (version 5.56) !");
    }
}

public class Caliber556Reloader : IReloadable
{
    public void Reload()
    {
        Console.WriteLine("Reloading caliber 5.56 !");
    }
}

And now, you can use theses class as properties in differents weapon classes.

You'll implement once the methods and can use the same for differents weapons :

public class Katana : Weapon
{
    public Katana()
    {
         WeaponPrimaryAttack = new SlashAttack();
         WeaponSecondaryAttack = new StabAttack();
    }
}

public class Machete : Weapon
{
    public Machete()
    {
         WeaponPrimaryAttack = new SlashAttack();
    }
}

public class Shotgun : Weapon
{
    public Shotgun()
    {
         WeaponPrimaryAttack = new Shooting12Caliber();
         Reloadable = new Caliber12Reloader();
    }
}

public class AssaultRifleWithBayonet : Weapon
{
    public AssaultRifleWithBayonet()
    {
         WeaponPrimaryAttack = new ShootingWith556();
         WeaponSecondaryAttack = new StabAttack();
         Reloadable = new Caliber556Reloader();
    }
}

Now, your methods implementations are refactored within classes and are reusable. You don't need to typecast to check if this or that interface is implemented.

if (weapon.Reloadable != null)
{
    weapon.Reloadable.Reload();
}
else
{
    Console.WriteLine("This weapon isn't meant to be reloaded");
}

/*
This works too if you want to omit the Reloadable != null

public class CannotReload : IReloadable
{
    public void Reload()
    {
        Console.WriteLine("This weapon isn't meant to be reloaded");
    }
}
*/


Calculating doubling times from data points

Especially with mathematical-like programs, you want to write docstrings with your functions and classes.

In case you don't know what a docstring is, a docstring is a short piece of documentation that describes the parameters and return value of a function. And, it can include any sort of information/summary that is needed to fully explain a function.

Here is an example:

def add(a, b):
    """
    Adds two numbers together and returns the sum
    a + b
    @param(number) -- one number to add
    @param(number) -- another number to add
    @return(number) -- the sum of both parameters

    return a + b

In the case of your code where you have a few mathematical functions, providing a docstring is greatly important because there you can write out the formula that the function is using, what each part of the formula means, and what the return of the formula does for the rest of your code.

And, in places that aren't functions but need a docstring, you can just a # comments on the side (you don't have enough of these).

All of your main code (aside from functions) should be put into:

if __name__ == "__main__":
    [code or main()]

See here for why.

Your code seems very procedural. You have a few functions here and there but other than that, everything is just one after the other.

I'm having difficulty following your code so I can't give too many specific recommendations, but you should move more code to separate functions. For example, however, you could try to make a function call create_graph that will create a graph for you in just a single call.

That way, when you put your code into if __name__ == "__main__", every single line of code that you wrote won't be in there.


rand = crypto.randomBytes(32).toString("base64");
id = hashFct(rand).substr(0, 8);

If those random bytes are random, passing them through a hash function adds nothing. If they are only somewhat random, hash + truncation is better than just truncation. However, crypto.randomBytes are from a strong RNG, so you can use them as is.

The problem is that 8 bytes is not always unique. You solve it by looping until you get one that is unique. However an attacker could do the inverse: guess until it hits a real ID.

The probablity of guessing a particular ID is \$2^{-b}\$, where b is the number of bits in the random number. If you have n users in your database the probability is n times as high. With \$n = 2^m\$, the attacker needs only about \$2^{b-m}\$ guesses to hit some ID.

If your ID's are 8 bytes:

2^64 bit IDs (8 bytes)
2^20 users   (~1 million)
//
2^44 guesses (~17 million million)

However, if your IDs are 8 characters in base64:

2^48 bit IDs (8 base64 characters)
2^20 users   (~1 million)
//
2^28 guesses (~268 million)

Depending on your application and the number of users it is possible that both, the latter or neither is insecure.

My recommendation (echoing well known advice) is to use the 32-byte random string directly as an ID (converted to base64 if needed). That gives such a small chance of collisions that you can do away with the loop as well. (It's likelier e.g. that the CPU fails to loop due to cosmic rays than that you see a collision.)


using namespace std is considered a bad practice.
Unrestricted getters and setters are as good as making Item's members public. In fact, if there is no class invariant to maintain, do make them public.
arrayEnd is not a particularly good name. Consider calling it items (or items_count) instead. As a side note, use it!

for (int i = 0; i < items; i++)
    total_price += whatever;

This way the shopping cart constructor reduces to

ShoppingCart() {
    items = 0;
}

totalPrice is not initialized.
Having pointers in the shopping card is a dubious decision. You must answer the question who owns items. In other words, who's responsibility is to destroy Item, and what happens to the cart when it is destroyed? I strongly recommend to either have the cart to keep objects, or make cart responsible for their construction and destruction.


I have few suggestions, and modified the code.

Use Lazy singleton pattern instead of Double check singleton, avoid usage of volatile

private static readonly Lazy<SequentialTaskExecutor> _lazy = new
Lazy<SequentialTaskExecutor>(() => new SequentialTaskExecutor());

Tasks should be cancelled and disposed properly. Since the task we want to run for long time, create a new task using Task.Factory.StartNew with Cancellation tokens and TaskCreationOptions.LongRunning

Task.Factory.StartNew(this.ExecuteTask, _token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

Class should implement IDisposable interface, so created threads can be cancelled properly and items in the queue are cleared

public class SequentialTaskExecutor : IDisposable

protected virtual void Dispose(bool disposing)
{
    try
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // clear the items in queue.
                Action item;
                while (_queue.Count != 0)
                {
                    if (_queue.TryDequeue(out item))
                    {
                    }
                }

                _tokenSource.Cancel();
                _executionTask.Wait();
                _tokenSource.Dispose();
                _executionTask.Dispose();
            }

            disposedValue = true;
        }
    }
    catch
    {
    }
    finally
    {
        _tokenSource = null;
        _executionTask = null;
    }
}

Use Smart waiting instead of Busy waiting in tasks.

private void ExecuteTask()
{
    bool isTaskCompleted = true;
    while (true)
    {
        Action item;
        if (_token.IsCancellationRequested)
        {
            while (_queue.Count != 0)
            {
                if (_queue.TryDequeue(out item))
                {
                }
            }

            break;
        }

        if (isTaskCompleted)
        {
            isTaskCompleted = false;
            var innerTask = Task.Factory.StartNew(() =>
            {
                if(_token.IsCancellationRequested)
                {
                    return;
                }
                if(_queue.TryDequeue(out item))
                {
                    item();
                }

            }, _token).ContinueWith((ants) =>
            {
                if(ants.IsCanceled || ants.IsFaulted)
                {
                    isTaskCompleted = true;
                }
                else if(ants.IsCompleted)
                {
                    isTaskCompleted = true;
                }
                _currentInterval = _minimumInterval;
                System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task execution complted _currentInterval : " + _currentInterval);
            });
        }
        else
        {
            // Raise the interval till maximum value
            if (_currentInterval < _maximumInterval)
            {
                _currentInterval++;
            }

            System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task waiting complted _currentInterval : " + _currentInterval);
            Thread.Sleep(TimeSpan.FromSeconds(_currentInterval));
        }
    }
}

Complete source code is as follows

public class SequentialTaskExecutor : IDisposable
{
    private static readonly Lazy<SequentialTaskExecutor> _lazy = new Lazy<SequentialTaskExecutor>(() => new SequentialTaskExecutor());
    private readonly ConcurrentQueue<Action> _queue = null;
    private CancellationTokenSource _tokenSource = null;
    private CancellationToken _token;
    private int _maximumInterval = 10;
    private int _minimumInterval = 1;
    private int _currentInterval = 0;
    private bool disposedValue = false;
    Task _executionTask = null;

    private SequentialTaskExecutor()
    {
        _queue = new ConcurrentQueue<Action>();
        _tokenSource = new CancellationTokenSource();
        _token = _tokenSource.Token;
        _executionTask = Task.Factory.StartNew(this.ExecuteTask, _token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
    }

    public static SequentialTaskExecutor Instance
    {
        get
        {
           return _lazy.Value;
        }
    }

    public void AddToQueueForExecution(Action action)
    {
        _queue.Enqueue(action);
        System.Diagnostics.Debug.WriteLine("Task added " + _queue.Count);
    }

    private void ExecuteTask()
    {
        bool isTaskCompleted = true;
        while (true)
        {
            Action item;
            if (_token.IsCancellationRequested)
            {
                while (_queue.Count != 0)
                {
                    if (_queue.TryDequeue(out item))
                    {
                    }
                }

                break;
            }

            if (isTaskCompleted)
            {
                isTaskCompleted = false;
                var innerTask = Task.Factory.StartNew(() =>
                {
                    if(_token.IsCancellationRequested)
                    {
                        return;
                    }
                    if(_queue.TryDequeue(out item))
                    {
                        item();
                    }

                }, _token).ContinueWith((ants) =>
                {
                    if(ants.IsCanceled || ants.IsFaulted)
                    {
                        isTaskCompleted = true;
                    }
                    else if(ants.IsCompleted)
                    {
                        isTaskCompleted = true;
                    }
                    _currentInterval = _minimumInterval;
                    System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task execution complted _currentInterval : " + _currentInterval);
                });
            }
            else
            {
                // Raise the interval till maximum value
                if (_currentInterval < _maximumInterval)
                {
                    _currentInterval++;
                }

                System.Diagnostics.Debug.WriteLine(Task.CurrentId + " " + DateTime.Now.ToString() +  " Task waiting complted _currentInterval : " + _currentInterval);
                Thread.Sleep(TimeSpan.FromSeconds(_currentInterval));
            }
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        try
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // clear the items in queue.
                    Action item;
                    while (_queue.Count != 0)
                    {
                        if (_queue.TryDequeue(out item))
                        {
                        }
                    }

                    _tokenSource.Cancel();
                    _executionTask.Wait();
                    _tokenSource.Dispose();
                    _executionTask.Dispose();
                }

                disposedValue = true;
            }
        }
        catch
        {
        }
        finally
        {
            _queue = null;
            _tokenSource = null;
            _executionTask = null;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
 }
}


Computing the double Integral using MonteCarlo techniques using Julia

Try swapping out the three arrays with calling a function iteratively---three Int64 arrays (each element 8 bytes) of ~100M elements is a lot. That is, switch out the body of the sum into a separate function:

function foo(u)
    x = rand()
    y = rand()
    z = rand(u)
    (x^2 + y^2 <= 1) & (z <= x^4 + y^2) ? 1 : 0
end

and replace the sum expression itself with just a loop:

count = 0
for i in 1:N
    count += foo(u)
end
count * 2.0 / N

This runs a bit faster, since the compiler can optimize the internal function, and with a much smaller memory footprint, since we sidestep the arrays entirely.


Predict new ratings for each user based on their pearson correlation with other users

You have incorrect indexing in the loop. Better version with mapply and correct indexing:

df <- mapply(function(i, j) {
  sim_user = which(cor_mat[i,] >= lower & cor_mat[i,] < upper)
  final_x[j, i] = t(x[j, sim_user]) %*% (cor_mat[j, sim_user]/sum(cor_mat[j, sim_user]))
  cbind(i, j, sim_user, cor_mat[j, sim_user])
}, 1:ncol(x), 1:nrow(x))

This version already 44 times faster than the loop version:

    test replications elapsed relative user.self sys.self user.child sys.child
1   loop          100    2.21     44.2      2.21        0         NA        NA
2 mapply          100    0.05      1.0      0.05        0         NA        NA


Efficiently working out the nearest weekend

Short, short version:

function get_weekend()
{
    $fri = strtotime('friday');
    $sun = strtotime('sunday');
    // strtotime('friday') will be after strtotime('sunday') if it is after 0:00 Friday
    // and before 0:00 on Sunday
    $start = $sun < $fri? now():$fri;
    $weekend = array();
    $weekend['StartDate'] = date('d-F-Y', $start);
    $weekend['EndDate'] = date('d-F-Y', $end);
    return $weekend;
}


Simple octal reader macro in Common Lisp

First of all a note about variables: You're using setq on previously undefined and undeclared variables. This is actually undefined behavior and in most implementations will create global dynamic/special variables. To create local variables (which you presumably intended) use let.

(defun oct-string-to-number
  (string)
  "Converts an octal string to a number.  Only digits from 0 - 7 are accepted; sign or decimal point symbols will cause oct-to-number to fail"

This whole function can be implemented as (parse-integer string :radix 8). However for the sake of learning let's go through the function anyway:

(setq digits '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7))
...
(setq pos (position char digits))

Iterating through the list of digits to convert a digit to an integer, is neither the most efficient nor the most succinct to do it. You can use the digit-char-p function which returns the digit's int value, if the given char is a digit and nil otherwise. (The same applies in slurp-octal-digits where you do the same thing).

(loop for char across (reverse string)
    do
    (setq pos (position char digits))
    (setq result (+ result (* pos place)))
    (setq place (* 8 place)))

Instead of reversing the string and keeping track of a place variable, you can just iterate over the string from the beginning and multiply the result by 8 each step:

(loop for char across string
    do
    (setq result (+ (* 8 result) (digit-char-p char))))

That being said, I'd rather use reduce then loop here (that is, if I weren't using parse-integer) - especially as higher order functions are one of the most useful things in lisp that a newcomer should get acquainted to. Using reduce the function would be written like this:

(defun oct-string-to-number (string)
  "Converts an octal string to a number.  Only digits from 0 - 7 are accepted; sign, non-octal digit or decimal point will signal error."
  (reduce
    (lambda (sum digit)
      (+ (* 8 sum) (digit-char-p digit 8)))
    string :initial-value 0))


Inserting users using PDO prepared statements

Do not escape SQL query parameters when using PDO. PDO will do the right thing. If you call unnecessary escaping functions "just in case", then you end up mangling the data. That's how you get junk like "this &amp; that" appearing in some broken web pages.

When would you want to escape text using htmlspecialchars()? When outputting text to be embedded in HTML. For example,

 <input type="text" name="firstname" id="firstname" value="<?php echo escape($_POST['firstname']); ?>">

If you didn't call htmlspecialchars() on $_POST['firstname'], then a malicious user could break the page by inputting a name that contained double-quotes.


Looks fine for me, but such a class should be abstract, because it does not make sense to be able create instances of this type.

public abstract class DatabaseEntity <T>{
//
}

Making it abstract will reflect the actual abstraction of this entity.

One more thing, try to avoid java.util.Date as much as you can, it is just awful. You can use Joda time instead, or the new java date api if you using Java 8.


Reading and Converting XML File to Array

Types

Your code would be easier to read if one variable could only be one type. $plugins is initiated as a boolean, but can also be an array. But what would a boolean value even mean? $plugins = false; doesn't really make sense.

If there are no plugins, your code should just return an empty array. If there are errors loading the plugins, you could return false (but don't use the $plugin variable for that), or ideally throw an exception if you are using PHP5.

Don't reuse variables

You shouldn't reuse variables for completely different things. For example $plugin_array seems to be holding a lot of different data, which is quite confusing.

This for example:

    $plugin_array = json_decode( $plugin_json, TRUE );
    $plugin_array = ( ! empty( $plugin_array ) && isset( $plugin_array['plugin'] ) ) ? $plugin_array['plugin'] : '';

    if( ! empty( $plugin_array) ) {
        // do stuff
    }

Would be better as:

    $plugin_array = json_decode( $plugin_json, TRUE );
    $is_valid_data = ! empty( $plugin_array ) && isset( $plugin_array['plugin'] );
    $plugin = $plugin_array['plugin'];

    if( $is_valid_data ) {
        // do stuff
    }

Or you could just save the $is_valid_data variable by putting the expression inside the if directly.

Return early

Generally, your code will get a lot more readable if you handle simple checking at the top of your function, and return early. This will also reduce the level of nesting. eg:

if( empty( $plugin_list ) ) {
    return array();
}

And the same with $plugins = ( ! empty( $plugins ) ) ? $plugins : false;, which could just be:

if ( empty( $plugins ) ) {
    return array();
}

Or just ignore it, as there doesn't seem to be an error to handle (it's already empty, and returning an empty array if there are no plugins seems appropriate). Same goes for if( ! empty( $plugin_array) ) {.


I have several comments about styling:

check the indentation and fix it. There are some different styles that can be observed but universally lines that are inside a function (or even more generally - a scope) would have one indentation level more than before.
Spacing - be consistent. In one line you have checkbox.value = "value"; with spaces around the equals sign. The next line you have var idStr="id:"+numericalID - no spaces around the equals or the operator. I personally put spaces around each but that's personal preference. You can have spaces only around equals signs, or even only on the right side of equals signs or only around operators, etc. Whatever you pick - be consistent.
Semicolons at the end of the line. In JavaScript, they are not strictly required due to a feature called automatic semicolon insertion (ASI). So, a lot of times you can get away without putting them. Although occasionally, you may find your code doesn't behave as expected. Still, as long as you understand how ASI works, you should be fine. Just pick a style - with or without a semicolon and stick with it. I personally prefer putting them in because I find the ASI rules quite annoying to try and remember every time.
Opening curly brackets - they should be either at the same line as the statement they accompany or the next line. You're pretty consistent with having it on the same line aside from where the else shows up.
Super tiny issue - you don't have linebreakID declared properly. It's missing the var keyword, so the variable is now an implied global. I'm mentioning it here with the style issues because you've been consistent with having var statements, so it seems like a simple typo, rather than a different problem.

Styling is pretty important for readable and understandable code. You can employ a linter like ESLint or JSCS (JavaScript Code Style) where you can define the style you want (indentation using spaces/tabs, spaces around equals signs, etc) and then they will scan your code and report back any style violations. They even have an autofix option that takes care of all the style changes, so you don't have to, for example, manually go and fill in every missing semicolon in the file. Linters are a pretty useful tool.

Other than styles, I'd say the function is quite long. It can be broken down into smaller ones for the sake of readability. This is subjective, I know, but having to scroll to read everything is usually too much. There is no duplicate code but you can still just do something like this:

function createCheckbox() {
  var checkbox = document.createElement('input');
  checkbox.type = "checkbox";
  checkbox.name = "name";
  checkbox.value = "value";

  var idStr = "id:" + numericalID;
  checkbox.id = idStr;

  checkbox.addEventListener('change', function() {
    var idSplitArray = this.id.split(':');
    var labelStr = "label:" + idSplitArray[1];
    var labelTask = document.getElementById(labelStr);

    if (this.checked) {
      labelTask.style.setProperty("text-decoration", "line-through");
    } else {
      labelTask.style.setProperty("text-decoration", "none");
    }
  });

  return checkbox;
}

So you don't have all the boring details about setting up a checkbox around more important code. It's a judgement call how you'd split off the code, though - you might elect to have the event handler defined back in the addNewTask function or even split off into a separate function. Whatever it is, the point is to make the main function shorter by splitting off logical portions of the code. In effect, you get code comments - only instead of //creating checkbox you have checkbox = createCheckbox(). But the latter is also self-documenting and has less of a chance to drift away from the code and become an irrelevant and/or inaccurate comment.

For actual logic improvements - right now, there is string manipulation to determine which HTML ID corresponds to which element ID by employing string splitting and conversely creating complex ID values to accommodate that. That works and it's honestly something even big name libraries out there do. Still, it's possible to do better - you can use data-* attributes in HTML. In short, you can have custom attributes attached to HTML elements. The custom attribute is prefixed with data- and you can define the rest of the name. So, you can add a data-id="1", for example, to all elements that will operate on the element with ID 1. That way, you don't need to do string manipulation to get the correct data out of it, you can directly reference the custom attribute.

And that's most of my advice. I think there are other things, too but I don't consider them that important. I'm honestly quite pleased with this code and my main issue is really formatting inconsistency. I am especially pleased that you create the HTML elements programmatically via document.createElement followed by setting the attributes. That is a very good style and amazing to see in a beginner. I very often see even experienced JS developers opting to just do something like parentElement.innerHTML = '<input type="checkbox" id="id:"' + numericalID +'" /> which can be quite annoying to read and has some potentially disadvantages, some even potential security vulnerabilities.

Overall, I'd applaud this effort, especially from a beginner.


Sidekiq worker to validate survey participants

Your code looks pretty good to me. Just some minor notes:

next if survey.nil? -> next unless survey is enough.
The conditional operator ? is normally used for expressions, not for actions with side-effects. Also, it's a long line, a normal if-else would look better.
Argument panel_id is not used?

That said, I'd refactor it a little bit. In my experience, full-fledged conditionals (no inline conditionals) make code easier to read so the line count increase is worth it.

class VerificationWorker
  include Sidekiq::Worker

  def perform(panel_id)
    members = MembersAPI.members.fetch

    members.each do |member|
      if (survey = Survey.find_by(number: member.data_number))
        if survey.id != member.data['survey_id']
          survey.fail!('survey_id does not match')
        else
          survey.recipient_id = survey.recipient_id.presence || member.id

          if survey.recipient_id == member.id
            survey.verify!
          else
            survey.fail_panel!('recipient_id does not match member id')
          end
        end
      end
    end
  end
end


Making sure a block of code takes at least 5 seconds to execute

Rather than waiting for 5 second between calls, consider that Twitter API returns three HTTP headers that explicitly tells you your quota:

  X-Rate-Limit-Limit: the rate limit ceiling for that given request
  X-Rate-Limit-Remaining: the number of requests left for the 15 minute window
  X-Rate-Limit-Reset: the remaining window before the rate limit resets in UTC epoch seconds

You can just query as much as you like, until the X-Rate-Limit-Remaining reaches zero or until you receive a 429 Too Many Request status code, then sleep for X-Rate-Limit-Reset.

This gives you several advantages:

You're utilising your limit to the fullest
If twitter changes their rate limit (e.g. someone is DDoSing them and they need to stricken it up or they make a significant upgrade that allows them to increase their quota), then your application will automatically adapt.
sleeping can't take into account of the per-user quota when you share access tokens for multiple applications/multiple purposes

Refer to Twitter documentation: https://dev.twitter.com/docs/rate-limiting/1.1


Java binary search (and get index if not there) review

2 minor things:

Remove the unnecessary comparison. If

sortedArray[mid].equals(target)

fails, it will again compare the two strings in the next if condition. Instead, you can just do:

int c = target.compareTo(sortedArray[mid]);
if(c == 0)
  return mid;
else if(c < 0)
  ...

To keep the method signature simple, you can overload it and delegate to the one that does the work:

public int binarySearch(String[] sortedArray, String target) {
  binarySearch(sortedArray, target, 0, sortedArray.length - 1);
}


PHP creating slugify (clean URL) links in simple way?

An alternative, simpler way to code your solution is to use the strtr function which "translates characters". Also I made sure to escape the special characters in the regex.

function url_clean($str) {
    $accent = array(' űáéúőóüöíŰÁÉÚŐÓÜÖÍ');
    $clean  = array('-uaeuoouoiUAEUOOUOI');
    $str = strtr($str, $accent, $clean);
    return preg_replace('/[^A-Za-z0-9\-\.]/', '', $str);
}


How to shorten this terrible HTTP header parser?

Here I assume you just want to see how your current code can be improved without changing the algoritm.

First of all, give HLint tool a chance to suggest you obvious improvements. In your case the only improvement was that do in do readHeaderLine' "" was redundant, so not much.

Second, in my opinion many small top-level definitions are better than few large ones. You can still control namespace pollution by not exporting definitions local to the module:

import System.IO

type HostName = String

handleRequest :: HostName -> Handle -> IO ()
handleRequest host handle = do
    requestLine <- readHeaderLine handle
    putStrLn $ requestLine ++ "\n-------------------"

-- FIXME: This code is bad, and its author should feel bad.
readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = do
        chr <- hGetChar handle
        case chr of
            '\r' -> do
                nextChr <- hGetChar handle
                case nextChr of
                    '\n' -> return s
                    _    -> readHeaderLine' $ s ++ [chr, nextChr]
            _    -> readHeaderLine' $ s ++ [chr]

Next, your nextChr <- hGetChar handle ; case nextChr of limes appear twice, so you can extract a function and reduce code duplication.

Thanks to purity, you can do pretty mechanically:

foo handle quux bar baz = do
    chr <- hGetChar handle
    if chr == quux then bar else baz

Now replace the two fragments with calls to foo. Let's start with inner one:

readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = do
        chr <- hGetChar handle
        case chr of
            '\r' -> do
                foo handle '\n' (return s) (readHeaderLine' $ s ++ [chr, nextChr])
            _    -> readHeaderLine' $ s ++ [chr]

Heh, it didn't work because nextChr is only known inside foo. No problem, pass it as parameter to baz branch and use lambda to catch it:

readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = do
        chr <- hGetChar handle
        case chr of
            '\r' -> do
                foo handle '\n' (return s) (\nextChr -> readHeaderLine' $ s ++ [chr, nextChr])
            _    -> readHeaderLine' $ s ++ [chr]

foo handle quux bar baz = do
    chr <- hGetChar handle
    if chr == quux then bar else baz chr

So now you can do the outer one.

readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = do
    foo handle '\r' (foo handle '\n' (return s) (\nextChr -> readHeaderLine' $ s ++ [chr, nextChr])) (\chr -> readHeaderLine' $ s ++ [chr])

No luck again as first chr is nowhere to get from. Fortunately we know it's always '\r', so

readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = do
    foo handle '\r' (foo handle '\n' (return s) (\nextChr -> readHeaderLine' $ s ++ ['\r', nextChr])) (\chr -> readHeaderLine' $ s ++ [chr])

As line got too long, we can split it, removing another redundant do:

readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = foo handle '\r' haveCR noCR where
        haveCR = foo handle '\n' (return s) haveCRnoLF
        noCR chr = readHeaderLine' $ s ++ [chr]
        haveCRnoLF nextChr = readHeaderLine' $ s ++ ['\r', nextChr]

Now there are more repeated patterns to eliminate: foo handle and readHeaderLine' $ s ++. To remove foo handle we move foo back in and remove its handle parameter both from applications and definition as it's now accessible from closure:

readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return s) haveCRnoLF
        noCR chr = readHeaderLine' $ s ++ [chr]
        haveCRnoLF nextChr = readHeaderLine' $ s ++ ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

To eliminate readHeaderline' repeated patterns we extract them into recurse local function:

readHeaderLine handle = readHeaderLine' "" where
    readHeaderLine' s = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return s) haveCRnoLF
        noCR chr = recurse [chr]
        haveCRnoLF nextChr = recurse ['\r', nextChr]
        recurse x = readHeaderLine' $ s ++ x
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

This is how far you can get with mechanical code deduplication. Now it's time for heavier weapons. You can still:

separate recursive code from non-recursive code
separate monadic code from non-monadic code

The initial redHeaderLine' call can be implemented using recurse with an extra parameter:

readHeaderLine handle = recurse [] [] where
    recurse s x = readHeaderLine' $ s ++ x
    readHeaderLine' s = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return s) haveCRnoLF
        noCR chr = recurse s [chr]
        haveCRnoLF nextChr = recurse s ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

Now we can inline readHeaderLine' as it is only applied once:

readHeaderLine handle = recurse [] [] where
    recurse s1 x = foo '\r' haveCR noCR where
        s = s1 ++ x
        haveCR = foo '\n' (return s) haveCRnoLF
        noCR chr = recurse s [chr]
        haveCRnoLF nextChr = recurse s ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

And we can remove duplication of recurse s:

readHeaderLine handle = recurse [] [] where
    recurse s1 x = foo '\r' haveCR noCR where
        s = s1 ++ x
        rf = recurse s
        haveCR = foo '\n' (return s) haveCRnoLF
        noCR chr = rf [chr]
        haveCRnoLF nextChr = rf ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

Now let's put return value of recurse into a local declaration g:

readHeaderLine handle = recurse [] [] where
    recurse s1 x = g where
        s = s1 ++ x
        rf = recurse s

        g = foo '\r' haveCR noCR
        haveCR = foo '\n' (return s) haveCRnoLF
        noCR chr = rf [chr]
        haveCRnoLF nextChr = rf ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

Our goal is to divorse g from recurse. You can do it by adding parameters to both recurse and g and localizing identifiers used only in recurse and used only in g:

readHeaderLine handle = recurse g [] [] where
    recurse g s1 x = g rf s where
        s = s1 ++ x
        rf = recurse g s

g rf s = foo '\r' haveCR noCR where
    haveCR = foo '\n' (return s) haveCRnoLF
    noCR chr = rf [chr]
    haveCRnoLF nextChr = rf ['\r', nextChr]
    foo quux bar baz = do
        chr <- hGetChar handle
        if chr == quux then bar else baz chr

Now recurse is completely self-contained:

readHeaderLine handle = recurse g [] [] where
    g rf s = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return s) haveCRnoLF
        noCR chr = rf [chr]
        haveCRnoLF nextChr = rf ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

recurse g s1 x = g rf s where
    s = s1 ++ x
    rf = recurse g s

But g is still recursive: it has a nasty rf parameter which is an indirect recursive application. We need to move rf into recurse too. So here comes a trick: convert a function call into a constructor.

g can have only 3 return values: return s, rf [chr] and rf ['\r', nextChr]. We can represent them with a data type and return it instead of calling return or rf:

data Outcomes a b c = RF1 a | RF2 b | Return c

readHeaderLine handle = recurse g [] [] where
    g rf s = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return $ Return s) haveCRnoLF
        noCR chr = return $ RF1 [chr]
        haveCRnoLF nextChr = return $ RF2 ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

recurse g s1 x = analyzeOutcomes $ g rf s where
    s = s1 ++ x
    rf = recurse g s
    analyzeOutcomes outcomeM = do
        outcome <- outcomeM
        case outcome of
            RF1 a -> rf a
            RF2 a -> rf a
            Return a -> return a

Now rf parameter is unused, so we can clean the definitions of g and recurse:

data Outcomes a b c = RF1 a | RF2 b | Return c

readHeaderLine handle = recurse g [] [] where
    g s = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return $ Return s) haveCRnoLF
        noCR chr = return $ RF1 [chr]
        haveCRnoLF nextChr = return $ RF2 ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

recurse g s1 x = analyzeOutcomes $ g s where
    s = s1 ++ x
    rf = recurse g s
    analyzeOutcomes outcomeM = do
        outcome <- outcomeM
        case outcome of
            RF1 a -> rf a
            RF2 a -> rf a
            Return a -> return a

Now two more improvements: a) RF1 and RF2 outcomes can be joined into one outcome as they are handled uniformly and have the same types; b) the only reason we pass s is to return it in Return outcome, so we can eliminate s argument of g too.

data Outcomes a = RF a | Return

readHeaderLine handle = recurse g [] [] where
    g = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return Return) haveCRnoLF
        noCR chr = return $ RF [chr]
        haveCRnoLF nextChr = return $ RF ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

recurse g s1 x = analyzeOutcomes g where
    s = s1 ++ x
    rf = recurse g s
    analyzeOutcomes outcomeM = do
        outcome <- outcomeM
        case outcome of
            RF a -> rf a
            Return -> return s

Now rf and analyzeOutcomes are used only once and Outcomes type became the same as Maybe. So:

readHeaderLine handle = recurse g [] [] where
    g = foo '\r' haveCR noCR where
        haveCR = foo '\n' (return Nothing) haveCRnoLF
        noCR chr = return $ Just [chr]
        haveCRnoLF nextChr = return $ Just ['\r', nextChr]
        foo quux bar baz = do
            chr <- hGetChar handle
            if chr == quux then bar else baz chr

recurse outcomeM s1 x = do
    outcome <- outcomeM
    let s = s1 ++ x in case outcome of
        Just a -> recurse outcomeM s a
        Nothing -> return s

Now s1 and x are only used in recurse to construct s. We can then construct s outside of recurse and pass it. Also, g now can be inlined.

readHeaderLine handle = recurse (foo '\r' haveCR noCR) [] where
    haveCR = foo '\n' (return Nothing) haveCRnoLF
    noCR chr = return $ Just [chr]
    haveCRnoLF nextChr = return $ Just ['\r', nextChr]
    foo quux bar baz = do
        chr <- hGetChar handle
        if chr == quux then bar else baz chr

recurse outcomeM s = do
    outcome <- outcomeM
    case outcome of
        Just a -> recurse outcomeM (s ++ a)
        Nothing -> return s

Now note that outcomeM is just a constant and it is not changed across recursive calls. So we can proceed further with our splitting of recursive and non-recursive code:

recurse outcomeM s = f s where
    f s = do
        outcome <- outcomeM
        case outcome of
            Just a -> f (s ++ a)
            Nothing -> return s

And duplicate return $ Just can be moved inside foo:

readHeaderLine handle = recurse (foo '\r' haveCR noCR) [] where
    haveCR = foo '\n' (return Nothing) haveCRnoLF
    noCR chr = [chr]
    haveCRnoLF nextChr = ['\r', nextChr]
    foo quux bar baz = do
        chr <- hGetChar handle
        if chr == quux then bar else return (Just $ baz chr)

After renaming of nonsense identifiers in definition of foo we get:

readHeaderLine handle = recurse (match '\r' haveCR noCR) [] where
    haveCR = match '\n' (return Nothing) haveCRnoLF
    noCR chr = [chr]
    haveCRnoLF nextChr = ['\r', nextChr]
    match expectedChar onSuccess onFailure = do
        actualChar <- hGetChar handle
        if actualChar == expectedChar
            then onSuccess
            else return (Just $ onFailure actualChar)

recurse outcomeM s = f s where
    f s = do
        outcome <- outcomeM
        case outcome of
            Just a -> f (s ++ a)
            Nothing -> return s


What makes your code difficult to read is nonsense (in the sense of 'carries no meaning') like int tmp, or stuff like the condition (j + lowerBound) == tmp. The superfluous parentheses are just noise but j + lowerBound does not make sense at all, as it corresponds to offsetting the current index j into the window by the window's lower bound. lowerBound + j would make sense, as it corresponds to the actual number represented by the jth slot of the window. The fact that operator + is commutative is beside the point; it's humans who must understand your code. And your code is so difficult to understand that you don't even understand it fully yourself! Trying to express code with the greatest possible clarity can be a great aid in understanding the problem under consideration; on the other hand, churning out code when the problem has not been understood achieves the opposite effect.

The problem under consideration has no need of arrays containing offsets into the window. The algorithm just needs one offset during each iteration of the outer loop, just once. The computation of the offset would have warranted some 'hands-free' thinking time before the actual coding.

The first location that needs to be worked on by the inner 'cross off the composites' loop is p * p, where p is the current prime; let's call this start. This value needs to be reduced to an offset within the window being worked on, which is trivial (start - lower_bound) if start >= lower_bound. If start < lower_bound then it's time to unsheath the modulo operator.

// (p is the current prime)

int stride = p << (p & 1);
int start = p * p;
int offset;

if (start >= lower_bound)
{
   offset = start - lower_bound;
}
else
{
   int before_the_segment = (lower_bound - start) % stride;

   offset = before_the_segment == 0 ? 0 : stride - before_the_segment;
}

// ...

An alternative expression for the tricky case would be

offset = (stride - (lower_bound - start) % stride) % stride

but it leaves no clue for the reader as to what's intended... This can be simplified further to drop one module operator, by careful consideration of the magnitudes involved. But it is easy to shoot oneself in the foot. If there's no pressing need for shaving cycles then it's better to leave the simpler - if more verbose - code in place.

The original code uses the prime p itself as stride, which has the effect that all even composites get crossed off multiple times (first during the run with p = 2, and then again during all even steps during the runs with other primes). This means that the code does almost double the amount of work that's necessary.

A simple fix is to use p + p as stride when p <> 2. In effect this amounts to using a two-spoke wheel and ignoring the even spoke entirely except for its one lone prime occupant (the number 2). Another solution - which halves memory consumption - would be to represent only the even numbers in the sieve array and to pull the only even prime out of thin air when needed. Higher-order wheels would further reduce memory consumption and the amount of work done, but they would complicate the code considerably. By contrast, the two-spoke wheel gives a lot of bang while adding only one minuscule complication to the code.


Check whether a string contains exactly one distinct vowel

exactlyOne pred l = case filter pred l of
  [] -> False
  (x:xs) -> all (==x) xs

or equivalently

exactlyOne pred = (== (1 :: Natural)) . genericLength . nub . filter pred

since nub is lazy and takes O(optimal) time for this problem: If its input list has exactly one distinct member, the list is traversed once; if it has at least two, the list is traversed up to the second member and then (== (1 :: Natural)) knows to shortcut to False.

(I also like the operator .: and keep using it everywhere:)

infixr 8 .:
(f .: g) x = f . g x
exactlyOne = (== (1 :: Natural)) . genericLength . nub .: filter


First, no need to do :
Sht.Activate and then
ActiveSheet.Copy after:=wb1.Sheets(wb1.Sheets.Count)

This is heavily slowing the process (avoid Activate and Select as much as possible).

Then you can turn off more (see comments) in the Application to speed up your code :

Dim CalcMode As Long
With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
    'Turn off events (like Workbook_Open, Worksheet_Change, ...)
    .EnableEvents = False
    'Turn off the Status Bar
    .DisplayStatusBar = False
    'Store initial calculation mode
    CalcMode = .Calculation
    'And set it to manual
    .Calculation = xlCalculationManual
End With 'Application

I've amended a bit your error handler to go back to the part where we reset all those parameters for a regular use.

Opening your workbooks as read-only (as you don't modify them), should improve the speed a bit.

Finally, the use of With/End With allow the code to know which object you are using for multiple rows and will provide a better/faster access to it.

So all of this will speed up your code, but copying sheets is a bit ressources-demanding so it'll probably still be a long, especially if you are opening big files!

Sub SKR_Import()
On Error GoTo ErrorHandler

    Dim CalcMode As Long
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
        .DisplayStatusBar = False
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
    End With 'Application

    Dim wB1 As Workbook
    Dim wB2 As Workbook
    Dim Sht As Worksheet
    Dim fD As FileDialog
    Dim FileChosen As Integer
    Dim FileName As String
    Dim i As Long

    Set fD = Application.FileDialog(msoFileDialogOpen)
    With fD
        .AllowMultiSelect = True
        .Title = "Select Excel workbooks to import all sheets"
        FileChosen = .Show
    End With

    Set wB1 = ActiveWorkbook
    With wB1
        If FileChosen = -1 Then
            For i = 1 To fD.SelectedItems.Count
                'Open as read-only
                Set wB2 = Workbooks.Open(fD.SelectedItems(i), , True)
                For Each Sht In wB2.Sheets
                    Sht.Copy after:=.Sheets(.Sheets.Count)
                Next Sht
                wB2.Close SaveChanges:=False
            Next i
        End If
    End With 'wB1

ProperExit:
On Error GoTo 0
    wB1.Activate
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
        .DisplayStatusBar = True
        .Calculation = CalcMode
    End With 'Application
Exit Sub
ErrorHandler:
    MsgBox Err.Number & vbCrLf & Err.Description, vbCritical + vbOKOnly, "Error"
    wB2.Close SaveChanges:=False
    Resume ProperExit
End Sub


As Jamal implied, std::cin >> input will only extract one word. Since the prompt says words, I would assume this is wrong, and you should use std::getline like he suggested.

set is vaguely named. What is set? Something like firstEven might be a bit clearer (though then off course you have to default to true).

This would be clearer as int number = c - '0';.

(Also, if you're wanting to be incredibly pedantic, it's worth noting that this depends on ASCII (or an ASCII compatible encoding) and is not portable. The standard functions (e.g. std::stoi like MORTAL suggested) are guaranteed to be portable.)

While I'm at it with pednaticness...

if (isdigit(c)) {

That should be std::isdigits (same with toupper/tolower). When a C header is included via the C++ version of the header, it's guaranteed that the functions will be present in the std namespace, but it's only optional that they'll be present in the global namespace. Every major compiler exports them in the global namespace along with std, but CodeReview brings out the pedant in me :p.

Even though you're wanting to make this shorter, I think it's a bit too dense already, and it could use a bit of breaking out into smaller pieces. Luckily, since none of the 3 things interact, you can pretty easily encapsulate each item and keep the code reasonable. Unfortunately... doing so will almost inevitably come at a pretty steep amount-of-code cost.

The best way to do this that I can think of (at least without getting way carried away) is functors (or functor-ish things anyway):

#include <cctype>
#include <iostream>
#include <string>

/** Mutlipy odd numbers together as they're encountered, or default to 0 if none are seen. */
class odd_mult {
private:
    int val_ = 0;
public:
    void operator()(int x) {
        if (x % 2 == 0) { return; }
        val_ = (val_ == 0) ? x : val_ * x;
    }
    int val() const { return val_; }
};

/** Subtract subsequent even numbers from the first one encountered, defaulting to 0. */
class even_sub {
private:
    bool first = true;
    int val_ = 0;
public:
    void operator()(int x) {
        if (x % 2 != 0) { return; }
        if (first) {
            val_ = x;
            first = false;
        } else {
            val_ -= x;
        }
    }
    int val() const { return val_; }
};

/** Build up a string such that each encountered letter has its case reversed (i.e. lower -> UPPER, UPPER -> lower) */
class letter_upcase {
private:
    std::string val_;
public:
    void operator()(char c) {
        if (!std::isalpha(c)) { return; }
        val_ += std::isupper(c) ? std::tolower(c) : std::toupper(c);
    }
    const std::string& val() const { return val_; }
};

int main() {
    odd_mult odd;
    even_sub even;
    letter_upcase letters;

    std::cout << "enter words: ";
    std::string input;
    std::getline(std::cin, input);

    for (char c : input) {
        if (std::isdigit(c)) { // This could go in the functors, but then it'd have to be repeated.
                               // Better would be a number_fn, but that would require templating to do correctly.
            odd(c - '0'); // Creating a string to do the conversion seems a bit excessive. I'm willing to rely on ASCII.
            even(c - '0');
        }
        letters(c);
    }

    std::cout << "odd: " << odd.val() << '\n';
    std::cout << "even: " << even.val() << '\n';
    std::cout << "letters: " << letters.val() << '\n';
}

All in all, I'm not very happy with this approach, even though I'm suggesting it :/. It's incredibly long compared to your code, though a dozen lines or so can be cut out by changing the classes to structs. Additionally, a few sacrifices had to be made in terms of design to avoid it growing even longer. I do still feel though that your code is a bit hard to follow (I had to resort to the English description to understand it after trying to read it a few times -- what if the English hadn't been there?), but it seems this might be a situation where it's just too much logic to try to cram into a small amount of code.


I see 2 approaches to this:

Allow Member to be initialized with a dictionary.
Allow your Member class to behave like a dictionary.

If you proceed by approach 1, then your resulting code will be very concise:

if isinstance(member, Member):
    return member.identification()
else if isinstance(member, dict):
    member = Member(member)
    return member.identification()
raise ValueError('no identification could be made')

But you will have a lot of additional logic in Member

Alternatively, if you do not like that approach, we can make Member work like a dictionary. Basically member['guid'] would refer to member.guid if member is a Member or the dictionary version if member is a dictionary.

We can do this by adding some magic methods to Member: __getitem__(self, key): and __setitem__(self, key, val): and __contains__(self, val):. The code would look something like this:

def __getitem__(self, key):
    if key == "nickname":
        return self.nickname
    elif key == "guid":
        return self.guid
    # and so on

def __setitem(self, key, val):
    if key == "nickname":
        self.nickname = val
    elif key == "guid":
        self.guid = val
    # and so on

def __contains__(self, val):
    if val == "guid":
        return self.guid != None
    elif val == "user_id":
        return self.user_id != None
    # and so on

This would make code snippet something like this:

try:
    return member.identification()
except AttributeError:
    pass

if not isinstance(member, Member) and not isinstance(member, dict):
    raise ValueError('no identification could be made')

id_types = ['user_id', 'email', 'phone_number']
if 'guid' not in member:
    member['guid'] = cls._next_guid()
for idt in id_types:
    if idt in member:
        try:
            return {
                'nickname': member['nickname'],
                'guid': member['guid'],
                 idt: member[idt]
            }
        except KeyError:
            raise ValueError('no nickname')
 else:
    raise ValueError('no user_id, email, or phone_number')


Some notes:

Think about reusability.  Your code integrates the field names directly into the functions.  Same goes for some of your choices of function names (alterWaterMarkForDateTBX). This makes it difficult to reuse next time you need this function.
You appear to be mixing ideas.  You set a class name sometimes, set the text color other times.  I'm not sure if this was intentional but I just changed it all to class names.
You had some dead variables.  Stuff like this just make it harder to edit in the future.  Remove them.
var d = new Date(); var t = d.toLocaleTimeString();
You are checking to make sure the field had focus before it blurred (and vice versa).  And then Not sure what the purpose of that is.
Your focus and blur events pass in the textbox name and the textbox value (as watermarkText.  Then you check the value against a couple of other values and if it matches set the textbox back to watermarkText.  This will never accomplish anything and is confusing.  Just pass in the textbox itself.
Think about non-intrusive javascript.  It is easier to maintain.  Notice how I added the blur and focus events to the field through javascript instead of directly in the html.
You should try to avoid global objects.  Look into putting this entire code block into an object.  The problem you will face is what if you have two fields on the same form that need this functionality.  The changes I have made below will go a long way in helping but the global interval and global counter will conflict with one another and it will not work.

EDIT:

I was interested in this problem. So I extended my code.

I moved the main work into a function object.  This can now be called using a constructor which passes in the text box.  This also allows for multiple textboxes using this even on the same page.
I added an options object to the parameters.  This will allow you to change the functionality of the script without changing the actual code.  This allows for reusability without needing to modify the code (open-closed principle).  This is also a common technique used in many of the JS frameworks (jQuery, mooTools, etc..)

Styles:

.NormalTextBox {
color = "black";
}
.WaterMarkedTextBox {
color = "grey";
}

Script:

    var MultiWatermark = function (obj, options) {

    var defaultOptions = {
        // These variables can be changed to alter functionality using the passed in options object
        watermarkVals: ["insert date", "mmddyyyy"], // all watermark values.
        totalIterations: 2, // how many times to go through watermark Array.
        watermarkClassName: "WaterMarkedTextBox",
        normalClassName: "NormalTextBox",
        changeDelay: 1000, // in milliseconds
        extraValsToCheck: ['', null]//
    }

    //merge options with defaultOptions
    for (var property in defaultOptions) {
        if (!options.hasOwnProperty(property)) {
            options[property] = defaultOptions[property];
        }
    }

    // local variables (do not change)
    var textBox = obj;
    var iterationCounter = 0;
    var itemCounter = 0;
    var intrId;

    var startWatermark = function () {
        itemCounter = 0; iterationCounter = 0; // resets for after blur
        intrId = setInterval(function () { alterWaterMark() }, options.changeDelay);
    }

    var stopWatermark = function () {
        clearInterval(intrId);
    }

    var alterWaterMark = function () {

        if (iterationCounter < options.totalIterations) {

            textBox.value = options.watermarkVals[itemCounter];
            itemCounter += 1;
            if (itemCounter == options.watermarkVals.length) {
                itemCounter = 0;
                iterationCounter += 1;
            }
        }
        else {
            stopWatermark();
        }

    }

    var isWatermarkValue = function (val) {

        var i = options.watermarkVals.length;
        while (i--) {
            if (options.watermarkVals[i] === val) {
                return true;
            }
        }
        // value is not in watermark array, so check secondary values.
        i = options.extraValsToCheck.length;
        while (i--) {
            if (options.extraValsToCheck[i] === val) {
                return true;
            }
        }
    }

    var setClass = function () {
        textBox.className = isWatermarkValue(textBox.value) ? options.watermarkClassName : options.normalClassName;
    }

    var focusEvent = function () {

        stopWatermark();
        if (isWatermarkValue(textBox.value)) {
            textBox.value = "";
        }
        setClass()
    }

    var blurEvent = function () {

        if (isWatermarkValue(textBox.value)) {
            startWatermark();
        }
        setClass();

    }

    var initWatermark = function () {
        setClass();
        textBox.onfocus = focusEvent;
        textBox.onblur = blurEvent;
        startWatermark();
    }

    initWatermark();
}

Body:

<form id="form1" runat="server">
    <input ID="TBXinsertDate" ToolTip="date Box"  Width="79px" />
    <input ID="Text1" ToolTip="date Box"  Width="79px" />
 </form>

<script>

var dateOptions = {
    // These variables alter functionality, the main script will use the defaults of any options not included here
    watermarkVals: ["insert date", "mmddyyyy", "mm/dd/yyyy"], // all watermark values.
    totalIterations: 4,
    changeDelay: 500, // in milliseconds
    extraValsToCheck: ['', null, '__/__/____', 'test']//
}
new MultiWatermark(document.forms["form1"].elements["TBXinsertDate"], dateOptions);
new MultiWatermark(document.forms["form1"].elements["Text1"], dateOptions);
</script>
</body>
</html>


Replacing a string until it matches a certain length

That is an O(L2) algorithm: each replace involves copying the entire string. A better strategy would be to call replace just once. First, figure out how many spaces need to be eliminated. Then, use a callback that conditionally modifies its match based on a count.

It should be possible to do it that way without reversing the string twice.


Controller structure for a browser game module with filters and pagination

First of all, for a better user experience, I would avoid pagination in favour of infinite scroll. Here is a simple Angular infinite scroll implementation

I presume you are aware of minification-proof technique .controller('name', ['$scope', function($scope){}], so won't go into that.

Next, I see many fields like $scope.players, $scope.teams, ..., mixed with $scope.filters, which can lead to namespace conflicts as the app grows. Hence I would gather all data-related fields into one object like $scope.data. Then you can simply pass the whole object from your service instead of assigning one-by-one.

The hard-coded declation $scope.predicate = 'team.name'; is mixed with others provided by the service. Perhaps it belongs to a Config service together with other hard-coded properties.

Also I presume you are aware of the difference between using $scope.field vs $scope.field.subfield in terms of their interactions with parent and child scopes.

EDIT.
Unless you know what you are doing, a recommended practice is to use $scope.field.subfield. That way, in a child controller, you have both read and write access to it. If instead you use $scope.field, then changing it from a child controller will add a variable on the local scope but won't change the parent scope as you likely intend, see here.

EDIT.
See also Misko's video on best practices, including putting the dot inside your $scope property.

minMax($scope.players); suggests that you are using service minMax just for one function. I would gather those functions into one bigger service like Utils. You already have lots of dependencies for your controller, so lowering that number can be a good thing. Similar for $scope.teams = TeamsModel;.

I am not sure why you define filters inside a controller, rather than with .filter as common.

Usually filters declared via .filter update themselves, so no need for watchers.


Nullable Generics - Implementing SequentialSearchST in C#

Consider removing the requirement that default(TValue) is null, and instead of returning null, throw a KeyNotFoundException:

  The exception that is thrown when the key specified for accessing an element in a collection does not match any key in the collection.

For convenience, you may also want to provide a bool TryGetValue(TKey key, out TValue value) method.

If possible, making SequentialSearchSt<TKey, TValue> implement IDictionary<TKey, TValue> will make using the class easier for any .NET developer.


ForEach Methods Implementation for Multidimensional Array in C#

The solution is fine as it easy as it could be but there's a better way to make the access to it - extension method.
public static class ArrayHelpers
{
    public static void ForEach<T>(this Array array, in Action<T> action)
    {
        if (ReferenceEquals(array, null))
        {
            throw new ArgumentNullException(nameof(array));
        }

        if (ReferenceEquals(action, null))
        {
            throw new ArgumentNullException(nameof(action));
        }

        foreach (T item in array)
        {
            action.Invoke(item);
        }
        return;
    }
}

Then the test cases can look like this
Console.WriteLine("One dimensional case");
int[] test = new int[] { 1, 2, 3, 4 };
test.ForEach<int>(ShowSquares);

Console.WriteLine("Two dimensional case");
int[,] test2 = { { 0, 1 }, { 2, 3 } };
test2.ForEach<int>(ShowSquares);

Console.WriteLine("Three dimensional case");
int[,,] test3 = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } };
test3.ForEach<int>(ShowSquares);


There is a not a lot to review, from a once over:

Indenting is not good for stopDefault, but I guess that's from copy pasting
There is no sense in calling addEventListener if file is not set, it should be part of your if block
Personally I would first add the listener, then starting reading text
I like your use of stopDefault
JsHint could find nothing wrong
Looks easy to maintain and to grok


How can this function be faster? Solving for a row of Pascal's triangle

You can memoize the rows you have already computed previously.

Alternatively, you could compute it in closed form using the binomial coefficients:

Start looking in scipy.special.binom.


I think you should use escapeshellarg to secure that $user does not do damage through your exec call. Also, you should check if your $arr actually has the required data.

As for optimization, replacing multiple spaces and dashes with single spaces and then exploding such strings seems to me slower than just splitting the string right away, using preg_split:

$arr = preg_split("/[\s-]+/", $quota);

However, you should still check that count($arr) > 3.

I must say that I am a bit surprised to see this work for you. That means that the user under which PHP is running has the permission to see other users' quota. IMO, web server should not be allowed as much.

A better way to do this is to dump all users' quotas in some text file (i.e., using repquota command; see an example on how to use it here), via a cron job run as root, and then make the script that only parses that file.

Or, quite similarly, your cron job can make a file with all the data, i.e., create quota-data.php like this:

<?php

$quota_data = array(
  'zuul' => array(
    'total' => ...,
    'used'  => ...,
    'free'  => ...,
  ),
  ...
);

?>

which you then just include in your script and use the data.

Which of these two approaches is better depends on how often the data is read from the web. If rarely, the text file approach is better, so that parsing is done only when really needed; if often, the second approach is better, as it parses the data only once per update.


Using the Sieve of Eratosthenes seems like a reasonable way to generate a large number of primes.

One thing that you could do is directly return your bitset representation of the primes, rather than copying it to a condensed list. This would save a bit of time in the short term, and be helpful for the next step.

for i in (list_prime(A)):
    for j in (list_prime(A)[::-1]):

A few comments.

First, doing something twice is slower than doing it once! Since list_prime(A) is repeated in both lines, it will have to re-run the Sieve of Eratosthenes: even though you know that the list of prime numbers isn't going to change, Python doesn't! Even worse, because the second line is in a loop, you're running list_prime again for every value of i. So you can speed it up a bit by storing that list in a variable before you get to the loops.

Second, when you have nested loops like this, you make your algorithm quadratic in the size of list_prime(A). The issue is that you're doing the imprecise test for j before the precise test, which is normally the slow way around. That is, you're considering all the values of j which meet the rule "j is a prime number" and then testing whether "j + i == A". Instead consider all the values of j for which "j + i == A" first. There is exactly one of those for each i, which is found by simple subtraction. Then check whether that j is in your list of prime numbers. If so, you have a match. If not, you can immediately check the next i.

(The reason that I suggested returning the bitset representation of the list of primes is that it makes it much faster to check whether a specific number is prime.)

A few less substantial optimisations

solution_set.append((i,j))

It is good to consider the tie-breaking rules for problems like this, and listing candidates first and checking which wins afterwards is a valid way to do so.

However, it is worth thinking about the order of your algorithm before implementing the tie-breaking check. If, as is the case here, the first satisfying value is guaranteed to be the one that wins the tie break because it has the smallest i value, you might as well just return the first one you get to.

if bool_a[j]:
    bool_a[j] = False;

If the end result of these two lines is that bool_a[j] must be False, just set it to false. if statements are surprisingly slow on modern CPUs.

primes.append(i)

Whenever you find yourself appending something to a list one element at a time, consider whether you can rewrite it using list comprehensions. For example something like the following:

primes = [index for (index, is_prime) in enumerate(bool_a) if is_prime]

(However, as above, my actual recommendation is that you completely remove that step and directly return bool_a)