There is definetely a way to improve that even though the excel sheet has a lot of formulas.
In VBA there is an:

Application.Calculation = xlManualCalculation

That can be used to help dramatically improve the time it takes, when the problem is many formulas in a sheet. And then in the end you should turn it back to automatic.

As you are using VB with a connection to the Excel Workbook through a COM, the way to do it is very similar. It is:

ExcelApp.Calculation = XlCalculation.xlCalculationManual

Where ExcelApp is the excel application object.


Python password generator based on the current month

Independent of the actual programming language you break a lot of rules and recommendations.

First - you shall not repeat yourself. The snippet

if letter_one_ascii == 91 or letter_one_ascii == 123:
    letter_one_ascii = 65

is repeated with slightly changed names

if letter_three_ascii == 91 or letter_three_ascii == 123:
    letter_three_ascii = 65

or slightly changed values

elif letter_three_ascii == 92 or letter_three_ascii == 124:
    letter_three_ascii = 66

Most probably you did not type that but you did copy-paste and edited names and/or values. This is very error prone as you could easily forget to change a name or value. Such errors are very hard to find. What would you do if you had to extend this generator to handle 5 characters? or 6?
Typical solution: write a function that shifts by n letters and another one shifting by one letter

def shift_by_one(letter):
    # some magic here
    return new_letter

def shift_by_n(letter, n):
    # some magic here using previously defined function 'shift_by_one'
    return new_letter

you are not repeating yourself any more and extending comes easy. finally you should implement another function shifting a word according to your rules

def shift_word(word):
    # some magic here using previously defined function 'shift_by_n'
    return new_word

Second - you shall name your magic numbers, especially if they are appearing more than once. but even if appearing only once, what does 124 stand for? or 66? This is hard to maintain for you and even harder for a different person.
Instead of 65 you could have something like

first_letter_ascii = ord('A')

Third - boundary checking. you can do that after incrementing like you did, but you can also do it before. The latter is preferred if outside values do not exist or do not make sense.
Instead of

letter_one_ascii = ord(letter_one)
letter_one_ascii += 1

if letter_one_ascii == 91 or letter_one_ascii == 123:
    letter_one_ascii = 65
else:
    letter_one = chr(letter_one_ascii)

you could easily write

if letter_one == 'Z' or letter_one == 'z':
    letter_one = 'A'
else:
    letter_one_ascii = ord(letter_one)
    letter_one_ascii += 1
    letter_one = chr(letter_one_ascii)

That is much more readable and by the way this would make the body for shift_by_one.

Other options for boundary checking are modulo operations

arr = 'ABCD'
print(arr[4%len(arr)])

and deliberatly extending arrays outside

arr = 'ABCDA'
print(arr[4])

Fourth - you handle a lot of special cases as you process uppercase and lowercase. however in your final output you are interested in uppercase only. convert month to uppercase immediately and eliminate all 90+ numbers respectively letter 'z'.

month = myDate.strftime("%b").upper()

this also enables you to use a modulo boundary check and we can eliminate the loop in shift_by_n

def shift_by_n(letter, n):
    index = ord(letter) - ord('A')
    index = (index + n) % 26
    letter = chr(index + ord('A'))
    return letter

Finally some python stuff:
you do not have to convert a string into a list to access characters, string provides slicing and iterability.

word = myDate.strftime("%b").upper()[:3]

if you end up in a list of characers and want to have a string you can join all characters by

''.join(mylist)

another nice feature in python is list comprehension which we use in shift_word

letters = [shift_by_n(letter,n+1) for n, letter in enumerate(word)]

we end up in

import datetime

def shift_by_n(letter, n):
    index = ord(letter) - ord('A')
    index = (index + n) % 26
    letter = chr(index + ord('A'))
    return letter

def shift_word(word):
    letters = [shift_by_n(letter,n+1) for n, letter in enumerate(word)]
    return ''.join(letters)

myDate = datetime.datetime.now()
word = myDate.strftime("%b").upper()[:3]
print "Your Password is: " + shift_word(word)


A quick detail

You've written inc == 2 ? inc = 4 : inc = 2; : this is not the ""right"" way to use the "ternary" operator. Don't get me wrong, it will do what you expect it to do. However, the whole point of the operator is to return a value. In your case, it is no different that : if (inc == 2) inc = 4; else inc = 2;.

This calls for a ternary operator but to write it in a simple way : inc = (inc == 2) ? 4 : 2;


You have waaaay too many sums you are checking. KISS-Principle --> Keep it Simple {and} Stupid:

private boolean checkSudokuStatus(int[][] grid) {
    for (int i = 0; i < 9; i++) {

        int[] row = new int[9];
        int[] square = new int[9];
        int[] column = grid[i].clone();

        for (int j = 0; j < 9; j ++) {
            row[j] = grid[j][i];
            square[j] = grid[(i / 3) * 3 + j / 3][i * 3 % 9 + j % 3];
        }
        if (!(validate(column) && validate(row) && validate(square)))
            return false;
    }
    return true;
}

private boolean validate(int[] check) {
    int i = 0;
    Arrays.sort(check);
    for (int number : check) {
        if (number != ++i)
            return false;
    }
    return true;
}

Short Explanation:

A Sudoku has three elements to validate. Each has to contain the single digit numbers from 1 to 9 exactly once.
These three elements are: each single row, each single column, the 9 3x3 sqares.
These elements are exactly mapped by the three variables you see in the for-loop.
Each of these elements is given to a validate function to verify, that it contains the numbers only once. Originally this was a golfed solution, so the square calculation is heavily algorithmic.
The validate function is quite simple. It initializes a counter to 0, and then walks the sorted "validated element" through, while always incrementing by 1. this gives the numbers from 1 to 9. In fact it is just a shortened for-loop, written a little different it's:

this one

for(int i = 1; i <= 9; i++){
    if(check[i-1] != i){
       return false;
    }
}
return true;

Longer Explanation

How I got to the algorithmic generation for the squares:

[(i / 3) * 3 + j / 3]      [i * 3 % 9 + j % 3]

(i / 3) * 3 + j / 3

This part is relatively simple. It gives the correct "column" by help of implicit integer conversion: The first part of the equation is a little difficult:

  \$ (i / 3) \$
  \$ {0,1,2} \mapsto 0 \$
  \$ {3,4,5} \mapsto 1 \$
  \$ {6,7,8} \mapsto 2 \$

take it * 3 and you got the sqare you want to get in to. then if we now iterate row-wise, we need to jump to the next column every 3 Elements. That's done with j / 3.

Now for the difficult one:

 i * 3 % 9 + j % 3

  \$ (i * 3 \% 9) \$
  \$ {0,3,6} \mapsto 0 \$
  \$ {1,4,7} \mapsto 3 \$
  \$ {2,5,8} \mapsto 6 \$

This one is for "jumping" the sqares vertically. Then we just have to iterate 0, 1, 2. This is accomplished by running the % 3 operation.


I tested with the cases of standard integral types (expecting true,) standard floating point types (expecting false,) user-defined types convertible to some standard integral type (expecting false.) All tests passed.

You should have tested with all the other kinds of types in C++. Reference types, pointer types, enum types, nullptr_t, void, pointer-to-member types, etc. etc.

Your is_integral incorrectly reports that int& is an integral type. (Godbolt.)

It's not a hard fix, of course; but the code-review feedback is "Write more tests."


I think this code is fine, and can't be sped up very much. But ....

The MD5 hash is most likely unique, it's got 16^32 (3.4e38) values after all, but once in a blue moon two different objects will have the same identity, especially if you use this a lot. This might cause very rare, random, bugs in your software. Bugs that are virtually impossible to track down.

I don't think the __toString() magic Method was intended for the purpose you're now using it for. I have learned that; "You should always use something for the purpose it was intended for.". The purpose of __toString() is to give you a readable representation of the object. By appropriating it now for identifying objects, you're loosing the capability to use it for its intended purpose later.

You're also relying on an undocumented property of get_object_vars(), namely that it will always return the variables in the same order. Will it? I don't know. It probably will, but doesn't have to. This could also change with changing versions of PHP, leaving you with a very big headache if it happens. You could use ksort() to make sure the order is always the same, but that will slow things down a lot.

I've also read in various places, and in the comments in the manual, that get_object_vars() doesn't return static variables. That makes sense since all objects of a class share the same values for these variables, but it is something to keep in mind.

The storing and checking of the identity hashes, in some collection of hashes, will probably be the slowest part of this whole idea.

Then my final problem wilt this code:

Properly written code would know the identity of its objects, or at least have a 100% reliable method to check this. Your code should be written in such a way that it already minimizes object duplication. This code seems the result of not being able to write good and efficient code (sorry, I'm trying to make a point here).

For instance, many objects could already have a simply ID integer that identifies them. For instance a model class, based on a database row, would most likely have such an ID. Most other classes could, if needed, have a similar way to identify themselves. Once you combine such an ID with the class name you should have a 100% reliable identifier.

If you really need a way to identify various objects you could simply add an identity() method to them. Something like this:

<?php

class MyClass
{
    public function __construct($id)
    {
        $this->id = $id;
    }

    public function identity() {
        return get_class() . ":" . $this->id;
    }
}

$myObject = new MyClass(999);

echo $myObject->identity();

?>

This would return:

  MyClass:999

I agree that this is a very basic example, but it should be possible to do something similar for any class.

By writing such a specific identifier method for each class you can optimize it, which means it will be faster, and you can make it a 100% reliable under any circumstances. It is also a lot easier to debug, because you can see and read what is going on. No hiding behind mysterious hashes here.

Conclusion: Despite my objections I think your code looks fine. I do however wonder whether this approach will, in the end, cause more trouble than it is worth.

Note: There is more discussion in the comments. In the end coolpasta wrote a response to this question.


void function

The bibesCutter itself doesn't care how many bibes have been claimed already. It only calculates how many are needed for the remaining requests. Therefore I'd recommend to change its signature to

int bibesCutter(Vector<int> & requests, int stockLength, int & rest)

Recursion

The first recursive call to bibesCutter always falls into a base case (tmp has exactly 1 element). I suppose it is much cleaner to deal with it inline. At least you'd spare creating and destroying a vector.

Once this is done' you'd notice that a code becomes tail recursive, so the recursion could be eliminated at all.
Correctness

It would be nice to prove that the algorithm yields the optimal solution. The request to fulfill with the remaining piece of pipe (toCheck) is selected pretty much at random. That, along with the above observation on recursion elimination, is a red flag.
Misc

tmp and toCheck are not best identifiers.

stoclLen is a very funny typo.


Use weather API to get information in JavaScript + jQuery

Response to your question

  If there is any other language than Jquery that I can use to get json files from api, please let me know because i find Jquery quite confusing :-).

As was mentioned in a comment (as well as a link-only answer that has since been deleted), there are alternatives, including but not limited to:

vanilla JavaScipt:

with XMLHttpRequest - refer to Using XMLHttpRequest on MDN
with the fetch API

other libraries, some of which are listed on youmightnotneedjquery.com/:

reqwest
then-request
superagent

General review

User experience

You didn't state whether the specification was part of an assignment/task or just something you came up with, but the UX might be improved by having the prompt and Ajax request triggered by an event like a mouse click instead of page load.

If such a change was implemented, then it would be wise to cache the DOM references in variables instead of querying the DOM each time- e.g.

var weatherEl = document.getElementById('weather');
var descEl = document.getElementById('desc');
var tempEl = document.getElementById('temp');

//function to prompt

//AJAX response callback
function ajaxResponse(data) {
    //parse data
    //...
    weatherEl.innerHTML = data.weather[0].description;
    descEl = data.weather[0].description;
    tempEl.innerHTML = data.main.temp + "°C";
}

That way, the lines can be shorter, the DOM won't get queried each time, and you can likely eliminate those variables that are assigned and then only used once.

Perhaps a template system would help improve the process of updating the DOM elements instead of having to update each item individually.

Handling other responses and errors

The code above doesn't appear to (gracefully) handle any response other than a successful call to the API endpoint. When the user types in a city that the API doesn't recognize, then a 404 response is returned. If you continue to use the jQuery library, then a .fail() callback could be specified (see the $.getJSON() documentation for an example to handle that. Also, if a server error occurred, then a 5xx response might be returned.

Additionally, the code assumes that data.weather will be an array and have at least 1 element. What happens if either of those are not true? While it may seem implausible it may be possible and something to guard against.

Extra libraries

The code includes mousetrap.js and moment.js - I presume those correspond to the libraries Mousetrap and MomentJS, but it doesn't appear that those libraries are used by the code. Unless those are used by other code not included, those libraries can be removed to save the users time loading the page.


Getting target IDs from promotions related to an order item

Use the java 8 stream API:

public Set<String> getTargetIdsFromPromotion(String itemToRefundId, RepositoryItem orderItem) {
    return getRelationships(orderItem).stream()
            .filter(this::isValidShippingType)
            .map(this::getAdjustments)
            .flatMap(Collection::stream)
            .map(this::getPromotion)
            .filter(Objects::nonNull)
            .map(p -> getTargetIdsByQualifier(itemToRefundId, p))
            .filter(s -> !s.isEmpty())
            .findFirst()
            .orElseGet(Collections::emptySet);
}


Your program is clearly written, and works correctly (to the best of my knowledge). I don't think that the time complexity is \$O(n)\$ can be improved, because the array must be traversed in order to locate the dangerous thunderheads. Your algorithm already optimizes that by checking only every second element (if that is a safe spot), relying on the fact that a solution is guaranteed.

The program can be improved a bit though. The while location < c.count condition of the main loop will always be true because the loop is always “early left” at

if location >= c.count {
    break
}

As a consequence, the program computes one location beyond the array bounds which is not needed (and not counted). This can be simplified by using a while-loop instead:

while location < c.count - 1 {
    if (location + 2 < c.count) &&
        (c[location + 2] == 0) {
        location += 2
    } else {
        location += 1
    }
    jump += 1
}

This is shorter and easier to understand because there is only one terminating condition for the loop instead of two.

A possible improvement might be to run the loop until one of the last two positions it reached, because then the test against the array count is done only once per iteration and not twice:

while location < c.count - 2 {
    if c[location + 2] == 0 {
        location += 2
    } else {
        location += 1
    }
    jump += 1
}
return location == c.count - 1 ? jump : jump + 1

A further optimization would be to use that if we do a size 1 jump because of a thunderhead, the following jump will always be of size 2:

while location < c.count - 2 {
    if c[location + 2] == 0 {
        // Jump two positions:
        location += 2
        jump += 1
    } else {
        // Jump one position and then two positions:
        location += 3
        jump += 2
    }
}
return location == c.count - 1 ? jump : jump + 1

But the performance increase will probably be negligible since the arrays have at most 100 elements.

Some minor points: The parentheses in

if (location + 2 < c.count) &&
    (c[location + 2] == 0)

are not needed because the comparison operators have a higher precedence than the logical operators:

if location + 2 < c.count && c[location + 2] == 0

Finally, I would name the counter variable jumps or jumpCount to better describe its purpose.


Golang visitor pattern for marshaling shapes as JSON, and XML

General things:

The visitor pattern is more suited for object-oriented languages. Whether Go is object-oriented is up for debate, but fact is that many OOP patterns are implemented differently in it (or don't make sense at all).
Specifically, I don't see an advantage to XmlVisitor and JsonVisitor over xml.Marshal and json.Marshal. That said, design is beyond the scope of codereview SE, so I'll assume you have a good reason.
Create a separate package rather than adding to main. I understand this is something you'd do eventually, but it's good practise to do it from the very start.

type Visitor func(shape Shape)

Do you actually need this to be a type? I see little advantage to it (slightly shorter lines perhaps) and this effectively hides from the user what Visitor really is. func (c Circle) accept(v func(Shape)) is self-documenting and easier to read. If you must have your own type, name it VisitorFunc at least, to make it clear what it is.

type Shape interface {
    accept(Visitor)
}

Probably not the best name - it can be anything, doesn't neccessarily need to be shape. I'd go with e.g. "Visitable", but the proper name per Effective Go would be "Accepter" since it contains a single method (use your best judgement to decide which name is better).

More importantly, accept shouldn't be private - you won't be able to call private methods outside of the package where the type is defined.

func (c Circle) accept(v Visitor) {
    v(c)
}

You probably want to pass by reference (pointer): func (c *Circle) accept.... The way it is now, your visitor is read-only and also more costly, as the whole object is copied.

func JsonVisitor(shape Shape) {
    bytes, err := json.Marshal(shape)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(bytes))
}

func XmlVisitor(shape Shape) {
    bytes, err := xml.Marshal(shape)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(bytes))
}

Don't panic(...). panic is used for unrecoverable errors - you'll only use it if you can answer "yes" to "am I confident that, whenever this errors happens, it's so severe that the best thing to do is just crash". Instead, have your accept method, your Visitor type and these functions all return error.


Reviewing the file download controller in spring rest

In my opinion, there are two ways with Spring to do that; your way is one of them (using the Spring Resource), and the other is to inject the file bytes directly in the javax.servlet.http.HttpServletResponse.
Your version can be improved, since you can use the FileSystemResource instead of the InputStreamResource.
The InputStreamResource is good when there are no other options available, as stated in the Java documentation since there are lots of other implementations to use.
Should only be used if no specific Resource implementation is applicable[...]

The FileSystemResource will remove the need to open the file and make the code shorter.
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename + EXTENSION);
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");

File file = new File(serverLocation + File.separator + filename + EXTENSION);
Resource resource = new FileSystemResource(file);

return ResponseEntity.ok()
.headers(header)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);

The thing that concerns me with your code, is the potential Path Traversal vulnerability that you have when reading the file, from the parameter. If I pass the filename value of ..\..\..\system.log, this could potentially be a problem, because we could download file out of the scope of your application.
File file = new File(serverLocation + File.separator + filename + EXTENSION);

One way to prevent that is to compare the base path / location of the file with the serverLocation, if the path is different, you ignore the request.


First of all I would recommend you to move the code to function so that you can re-use it by importing it in some other module as well.

To differentiate between whether the module has been ran directly or it was imported use the if __name__ = "__main__" condition at the bottom of the code.

Now coming to your code:

You don't really need to open the file 3 times to do this. With r+ mode this can be done in a single go. Note that good thing about r+ mode is that it also allows us read as well as write to the file.
Use a with statement to handle a file object, it makes sure that the file object gets closed even when an error occurs.
Instead of asking the user to hit Enter or CTRL-c ask them for a simply 'yes' or 'no' or may be 'y' or 'n'.
You're always writing three lines to the file, you can also ask the user for the number of lines they would like to write. Make this a default variable to the function with value 3 if you want them to write 3 lines by default. You can pass this value using another argument to the script: python foo.py file.txt 10. Using this variable you can run a loop and ask the user to enter the lines they would like to write.
Don't create unnecessary variables like line1, line2 and line3, better use a list and append the lines to it within in a loop.
Lastly, this is not an issue. But I would recommend that you should use the new-style string formatting over the old printf style string formatting as it is much more powerful and expressive in my opinion.

Code:

from sys import argv

def file_overwrite(filename, n=3):

    with open(filename, 'r+') as f:
        content = f.read()
        print content
        # ask user to overwrite the file
        while True:
            feedback = raw_input("Type 'y' to overwrite the file or 'n' to exit: ")
            if feedback.lower() == 'y':
                # move the file pointer back to the start and then truncate the file
                f.seek(0)
                f.truncate()
                break
            elif feedback.lower() == 'n':
                # return instantly, another advantage of using a function
                return
            else:
                print "Please enter either 'y' or 'n'."

        print 'Write {} lines to the file.'.format(n)
        # Loop n times and ask for user input and save it in the list.
        lines = []
        for line_num in xrange(1, n+1):
            line = raw_input('line {}: '.format(line_num))
            lines.append(line)

        f.write('\n'.join(lines))

        # After writing the file pointer is again at the end of the file.
        # To read the content again move it back to the start and then
        # read file's content.
        f.seek(0)
        print f.read()

if __name__ == '__main__':

    # The condition will run only when the user runs this file
    # directly.

    script, filename = argv[:2]
    print "The name of the script is: {!r}.".format(script)
    try:
        n = int(argv[2])
        file_overwrite(filename, n)
    except (IndexError, ValueError):
        file_overwrite(filename)


For one I don't believe your code will cover all the possible values.  If the values passed in are 9,3,9,3,9,7,7 I believe they would want 9 to be the result since there is an odd number of 9.  Currently you are checking for a single value.

By using a dictionary you first must add all the values to it then loop over it again.  Another option would be to check if the key exist.  If not then add it but if it does then remove it.  Then all that would be left if the "odd occurrences".  If we do it that way we don't even need to have the value part of the dictionary just the key part.  If we just need the key part of the dictionary then we should use a HashSet.

so the code would look something like this (I didn't run this code just typed in here)

foreach (var item in A)
{
   if (!hashset.Add(item))
   {
       hashset.Remove(item);
   }
}

return hashset.Single();

I never used codility so I don't know what they would score this solution.

Also as a side note there is no reason to cast the oddval in your code as an int in the return statement.  It's already declared as an int.


Coming from Python world, I was tempted to create a separate method named fizzBuzz() which I then called in my main() method. Is this a bit of overkill for such a simple task ?

Well, it is a little bit too much for such a simple task, but it is a good habit to do so and if I were you I would stick to it.

Overall your fizzBuzz looks good.

Naming -> Check

but

Best Practices -> Fail

This is because you omitted braces {} although they are optional for single instruction if, else if and else branches.

Omitting the braces can lead to hidden, and therefore hard to find bugs. I would like to encourage you to always use them.

Another thing is that you have some magic numbers, like 1, 100, 3, and 5 in your code which should either be extracted to some meaningful named constants, or passed to the method as parameters.

You could add a isDivisibleBy(int value, int divider) method as well to make the responsibilities clear.


Since jquery event handler is a memory and processing "eater" because has to listen for the events then I think is better to delegate the hover responsibility to css. The change is just remove class="hidden" from your elements and then set the right selectors to user display:none to hide or display:inline to show - I use inline instead of block since it is applied to anchor tag and the default behavior for this tag is inline.

With this change then javascript can be simplified and the hover handlers can be removed.

BTW you still have to implement the click handler to add the has-request class.

The code should look likes the following,

In your css:

.rendering.rendering-expert.request-list-supported:hover [rel=request-list-add],
.rendering.rendering-expert.request-list-supported.has-request [rel=request-list-remove]
{
    display: inline
}
.rendering.rendering-expert.request-list-supported [rel=request-list-add],
.rendering.rendering-expert.request-list-supported [rel=request-list-remove],
.rendering.rendering-expert.request-list-supported:hover .fa-cog,
.rendering.rendering-expert.request-list-supported.has-request .fa-cog,
.rendering.rendering-expert.request-list-supported.has-request [rel=request-list-add]
{
    display: none
}

And then replace your js:

$(function() {
    $(".rendering-expert.request-list-supported").on("click", function(e) {
        e.preventDefault();
        var toggler = $(this);
        toggler.toggleClass("has-request");
    });
});


Project Euler #4 (largest palindrome product) in Swift

Style

The reversed() function is only called from the isPalindrome function. Since the isPalindrome function is a 1-liner, it strikes me that there is no value added by exposing the reversed functionality at all, and that it can all be emedded in to the isPalindrome() call. There is no need for the method extraction in this case, it is overkill, and adds no significant value, while adding bulk to an extension on Int.

The problem constant 999 strikes me as being a good candidate for an input parameter. Instead you have encoded it as a magic number (three times) in the largestPalindrome() method. I feel it is more natural to have the input defined in the same way as the problem, use 3-digit numbers:

func largestPalindrome(limit: Int) -> Int {

note, the function receives the input limit, and it also returns the largestPalindrome from that limit. Note that the single-responsibility principle suggests that a function should return the value, and that you should print the result outside the function. The print in the function is.... ugly.

The code to turn the value 3 (for 3 digit numbers), would be:

limit max (exclusive) \$10^3\$
limit min (inclusive) \$10^{(3 - 1)}\$

Performance

There is a trivial, but effective optimization available for you, by breaking the inner loop when the product will always be less than the previously found largest.

Consider the code:

for left in stride(from: 999, through: 100, by: -1) {
    for right in stride(from: left, through: 100, by: -1) {
        let product: Int = left * right
        if product > largestPalindrome {
            if product.isPalindrome() {
                largestPalindrome = product
            }
        } else {
            break
        }
    }
}

In the above code, there is no point in testing smaller right values if they will never beat the current largest palindrome.


Sometimes just adding whitespace helps:

let rec add w tr = match w, tr with
    | [], Node (_, lvl_l) ->
        Node (true, lvl_l)
    | wh :: wt, Node (b, lvl_l) ->
        try
            let ins_point = List.assoc wh lvl_l in
            Node (b, (wh, add wt ins_point)::(List.remove_assoc wh lvl_l))
        with Not_found ->
            Node (b, (wh, add wt empty)::lvl_l)

The match expression was upgraded in recent years to match on exceptions. So you can also do this:

let rec add w tr = match w, tr with
    | [], Node (_, lvl_l) ->
        Node (true, lvl_l)
    | wh :: wt, Node (b, lvl_l) ->
        begin match List.assoc wh lvl_l with
            | ins_point ->
                Node (b, (wh, add wt ins_point)::(List.remove_assoc wh lvl_l))
            | exception Not_found ->
                Node (b, (wh, add wt empty)::lvl_l)
        end

(I had to wrap the match in a begin/end block to avoid confusing which match the patterns are applied.)

Since the return value has a common form, you could use match to just compute the second part of the pair:

let rec add w tr = match w, tr with
    | [], Node (_, lvl_l) ->
        Node (true, lvl_l)
    | wh :: wt, Node (b, lvl_l) ->
        Node (b, match List.assoc wh lvl_l with
                 | ins_point ->
                     (wh, add wt ins_point) :: (List.remove_assoc wh lvl_l)
                 | exception Not_found ->
                     (wh, add wt empty) :: lvl_l)

It's subjective whether these are any better than your example. I do think, however, that visually showing the structure helps me understand the code better. For instance, my last version shows Node being produced in both match cases. You could elevate the constructor "one more level up" and have the nested match expressions compute the pair to apply to the constructor. This wasn't immediately obvious from your example.


T-SQL Query remove duplicates except for original row from the table

Review

Your SQL seems the generally accepted way (Discussed Before) of deleting duplicates.

WITH cte
     AS (SELECT id,
                student_code,
                exam_code,
                mark,
                Row_number()
                  OVER(
                    partition BY id, student_code, exam_code, mark
                    ORDER BY student_code) AS rn
         FROM   exam_merge)
DELETE cte
WHERE  rn > 1

Optimization

I found a possible optimization using a non-clustered index. You would like to create a (non-unique) index on your key (id) with the other columns included.

CREATE NONCLUSTERED INDEX idx_exam_merge ON exam_merge
(id)
INCLUDE (student_code, exam_code, mark);

This example shows how such index could optimize the query plan to avoid clustered index lookup.


I wrote this up using a lot more jQuery as an example. Confirmed working JSFiddle here.

You can see there's a considerably less lines of code, there's less boilerplate on each line (things like document.getElementsByTagName), and at least in my opinion it's a lot more expressive.

Additionally, it becomes much easier to do other things that jQuery does well. For example, to animate these toggles. Just change $hidden.toggle() to $hidden.slideToggle()

Full code:

'use strict';

function enterData(){
    var day, info, day_regex = /[A-Z][a-z]{1,7} [1-9][0-9]?, 2[0-9]{3}/;
    do {
        day = prompt('Day');
        if (!day_regex.test(day)) alert('Day not correct .. !');
    } while(!day_regex.test(day))
    info = prompt('Info');
    addDiv(day, info);
}

function bindEventsToEl( $trigger, $hidden, events ){

    //This lets you pass in a different hash of events to bind, if you wanted to
    var eventsHash = events || {
        click: function(){
            $hidden.toggle();
        }
    };

    for ( var event_type in eventsHash ){
        $trigger.on( event_type, eventsHash[event_type] );
    }
}

function defineTriggers(hide) {
    var $hidden = $("div"),
        $triggers = $("h2");

    if (hide) {
        $hidden.hide();

        $triggers.each(function(i,el){
            bindEventsToEl( $(el), $( $hidden[i] ) );
        });
    }
}

function addDiv(date, info) {
    //Creating your empty elements and inserting content
    var $header = $("<h2>").text(date),
        $p = $("<p>").text(info),
        $div = $("<div>").append($p).hide();

    //You can chain appends to the root selector
    $("body").append($header).append($div);

    bindEventsToEl( $header, $div );
}

alert('running')

// bind all of our initial header/div combos
defineTriggers(true);

// create the button to add new sections
var $button = $("<button>").text("Add a Date").appendTo("footer").on( "click", enterData );

I removed your PER_TRIGGER, per_trigger variables and the if check around binding event listeners based on their count. It didn't seem to apply in your current JSfiddle anyway, and the reasoning behind it seemed a little shaky.

However, I think this problem might be solved just by using jQuery. Check out the bindEventsToEl function. Because $trigger and $hidden are jQuery selectors, you can have any number of elements in them.

For example, we can call this:

bindEventsToEl( $("h2, div"), $("div") );

This causes ALL divs to toggle whenever ANY h2 or div is clicked. Not exactly useful, but I think it shows you how powerful and expressive jQuery can be when selecting and binding events.

You can pass in a different event hash to the bindEventsToEl as well:

bindEventsToEl( $("h2"), $("div") , {
    click: function(){ console.log("bonus click"); },
    mouseover: function(){ console.log("mouseover"); }
});

If you're still not convinced that jQuery is the route you want to go, some recommendations for your prior code:

Focus on simplifying your toggle function so that it's much more clear what it's doing.
Try not to have as much nesting inside functions, break them out into their component parts.
Definitely don't have another function named 'toggle' inside a function named 'toggle'. It makes it look like it's calling itself recursively.
Give the rest of your variables slightly clearer names as well.


Breaking a 32-bit value into bytes for an ArrayList

Assuming your list was defined elsewhere, you could append the bytes of value as follows.

for(int i = 3; i >= 0; i--) {
    list.add((byte)((value >>> (i*8)) & 0xFF));
}

It avoids pre-populating the arraylist
It avoids resetting the byte already stored
It avoids storing the shifted value back in value
It uses a logical right shift to avoid sign extension of negative integers


Is there anything wrong with this unusual NSMutableArray setter?

You should add edges = nil; either after [edges release]; or as the else clause. Otherwise passing a nil argument will make edges a dangling pointer to a released object.

Other than that, I don't see any issues with this implementation.


Print last Sunday of each month in a given year

You do not need to put ;; everywhere. They're artifact of the interpreter.
print_date can be rewritten using printf:

let print_date = Printf.printf "%d/%d/%d"

It is better to store days in an array. List is not a good container for random access. Also, syntactically it would be easier to read: days.(2) is better than List.nth 2. Also, just FYI, you can have arrays in OCaml indexed from one, e.g., let days = Bigarray.(Array1.create int fortran_layout 12). Although, using them here would be overkill, I think.
You do not need parens here:

let last_sunday = last_day - (get_shift  y m last_day) in


You can simplify if(col is null,0,col) as ifnull(col, 0).

The SQL keywords are inconsistently formatted.
Sometimes you write SELECT, other times as Select.
I suggest to stick to all caps always.
The same goes for if (and ifnull) and as too.
It's easier to read the code when the writing is consistent.

The last line of your script is very long,
and it's difficult to read when I have to scroll to the right and the left part goes out of sight.
I suggest to add a few line breaks in there to make the code fit within one horizontal window. (I see you updated your original post, now it's good.)

It would be better to indent the sub-query more, and to put the closing ) on a new line to make it more visible. Something like this:

SELECT IFNULL(roll, 0) AS roll,
       IFNULL(cpapername, 0) AS compulsory,
       IFNULL(corepapername, 0) AS Core,
       IFNULL(e1papername, 0) AS Elective1,
       IFNULL(e2papername, 0) AS Elective2
       FROM (
           SELECT student.univ_roll AS roll, student.name AS name, student.rollno AS rollno,
           (CASE WHEN student.compulsory = paper.subject
             THEN (paper.paper_name) END) AS cpapername,
           (CASE WHEN student.core= paper.subject
             THEN (paper.paper_name) END) AS corepapername,
           (CASE WHEN student.elective_I= paper.subject
             THEN (paper.paper_name) END) AS e1papername,
           (CASE WHEN student.elective_II= paper.subject
             THEN (paper.paper_name) END) AS e2papername
            FROM student, paper WHERE student.semester='First'
            AND student.batch='2014' AND student.class='BSc'
            AND student.semester=paper.semester AND student.batch=paper.batch
            AND student.class=paper.class  AND student.regd='1'
    ) r


Welcome to Swift! Everything looks like it's working correctly so I'm adding some thoughts that will apply as you continue working and as the code gets more complex...

You're not doing anything in your viewDidLoad or didReceiveMemoryWarning except call the super class so my preference is to remove them.

I'd really recommend not capitalizing your property and function names (e.g. use leftCardOutlet instead of LeftCardOutlet), once you start writing more in swift it will make reading your card harder.

I'd suggest extracting your random number generation into a computed property, and instead of hardcoding the number 12 using the size of your cards array.

Nothing wrong with using non-english grammar in variable names (actually Swift works really well with unicode so feel free to use fur Polish alphabet) but try to be consistent, e.g. either scorePlayer, scoreCPU or computerScore, playerScore -- not a mix of both.

Finally, to help prevent bugs/logic errors as the code gets more complex:

Default to assigning new variables as 'let', and change only to var if you find you're modifying it at some later time.
Don't create a variable if you're only going to use it in one place (e.g. next line or couple of lines down) shorter/more concise code is normally easier to read and rationalize as it gets more complex.
When you have if/else logic make sure you're capturing all cases. In this case there's the chance the numbers will tie, it's worth adding a placeholder block with a brief comment there (or to print message) even if you've not decided yet what to do there.

A few minor changes:

import UIKit

class ViewController: UIViewController {

    // made outlet property names shorter, don't need to include that they are outlet in the name
    @IBOutlet weak var leftCard: UIImageView!
    @IBOutlet weak var rightCard: UIImageView!
    @IBOutlet weak var leftScore: UILabel!
    @IBOutlet weak var rightScore: UILabel!

    var karty = ["card2","card3","card4","card5","card6","card7","card8","card9","card10","jack","queen","king"]

    // (personal preference, but removed `Int` type declaration since it's easily implied)
    var scorePlayer = 0
    var scoreCPU = 0

    private var randomDeal: Int {
        // (instead of hardcoding 12, use the size of your cards array)
        return Int(arc4random_uniform(UInt32(karty.count)))
    }

    @IBAction func dealClicked(_ sender: UIButton) {

        // (use 'let' instead of 'var' since they won't change in the scopy of this function)
        let random1 = randomDeal
        let random2 = randomDeal

        // (got rid of `im1`, `im2` variables and just assigning directly here)
        leftCard.image = UIImage(named:"\(karty[random1])")
        rightCard.image = UIImage(named: "\(karty[random2])")

        if random1 > random2 {
            //player wins
            scorePlayer += 1
            leftScore.text = String(scorePlayer)
        }
        else if random1 < random2 {
            // computer wins
            scoreCPU += 1
            rightScore.text = String(scoreCPU)
        }
        else {
            // tie - do nothing
            print("tie: nobody wins")
        }
    }
}


Converting an integer to binary, hex, and octal

I'll just address several things regarding good practice.  This can probably be simplified greatly overall, but I won't try to focus on that particularly.

main():

I don't see the need for if (number == 0), especially in relation to parse().  Are you just skipping further calculation if the return is 0?  If you do that, the outputs at the end will not be printed, even though 0 is a valid number.
You don't need to use std::endl in main().  That also flushes the buffer, which is unnecessary here, and you do it multiple times.  Just use "\n" within a print statement.

parse():

You can define it above main(), allowing you to remove the function prototype.
It doesn't need the command line parameters; only main() does.
Its control paths and returns don't make sense to me.  If the if statement is executed, it displays a message and returns 0.  If the else is executed, it returns a converted integer.  Instead, the function should only be called if it will parse something, which is its main job.  Functions should focus on just one thing.  Let the calling code decide if it should be called.

Header:

There's no need for protected if you're not using inheritance (I believe even Bjarne Stroustrup himself has regretted adding that keyword).  Either change it to private, or just remove the keyword since classes are private by default.
If you're not maintaining one or more data members, then this program may not need to utilize classes.  This one just contains functions, but class functions are supposed to change the state of one or more data members.  Instead, those functions could just be free functions (non-member) and the class removed entirely.

Other:

This:

if (number % 2 == 0){
    result.append("0");
}
else{
    result.append("1");
}

can just be made into a single-ternary statement:

(number % 2 == 0) ? result.append("0") : result.append("1");

Better yet, since std::string supports +=, use that instead:

result += (number % 2 == 0) ? "0" : "1";

The local variables in int_to_bin() don't need to be static.
You don't need your own reverse function; just use std::reverse().
As @rachet freak has mentioned in the comments, you can just use std::hex to manipulate the I/O when displaying this value.  In addition, you can do this with all three number systems.


Protect from people bruteforcing the PHPSESSID

Depending of the attack, your code might be either may be more secure than the traditional use of PHP sessions.

If the attacker gets the session_id cookie from an XSS attack, he also gets access to the session_key one, and your code won't protect sessions from being hijacked. You can avoid this by setting the HttpOnly flag on your cookies, making them not accessible by JavaScript through document.cookie :

Using ini_set('session.cookie_httponly', 1); will configure PHP to add the flag on the session_id cookie.
Setting the seventh parameter of the setcookie function to true will set the HttpOnly flag on the session_key cookie. More information about all the parameters can be found on the official documentation : http://php.net/manual/function.setcookie.php

Anyway, that won't protect from the man in the middle attacks.
PHP has a function named session_regenerate_id which changes the current session id by a new one, making the hijacked cookies obsolete.

All you need to do is calling this function once you've started the session : http://php.net/manual/en/function.session-regenerate-id.php

If the attacked gets the session_id cookie from bruteforce, then your solution is indeed more secure, but you should still have a look to the two settings mentioned above.

Note that substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyz', 5)), 0, 32); doesn't generate a true random lowercase alphanumeric string since each character won't appear more than 5 times. substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyz', 32)), 0, 32); will work.

There are also more php.ini settings to add more entropy to PHP sessions ids :

The session.hash_function setting changes the hash function used by PHP to generate the id.
The session.entropy_file and session.entropy_length settings will tell PHP to use an external file as a source of additional entropy when generating the id.


Apart from the fact that a tab doesn't necessarily map to 4 spaces, as was nicely put by @Loki in his comment, there are a few other points that you can improve:

Your main function is not following a standard signature. It should be returning an int.
Your count() function, besides having a vague name (what is it counting exactly?), is reinventing strlen(). Avoid reinventing the wheel, unless you have a good reason to (in this case I'd say yes, since you are learning, but it is also valuable to know the standard functions and how to use them).
Still talking about count(), avoid calling it in the conditional section of a loop, like here:

 for (i=0; i< count(stri); ++i)

Remember that the condition gets tested every iteration of the loop, so this would imply a full scan of stri if the compiler is not smart enough to hoist that function call out the loop. Better would be to call the function once and store its result in a local variable.
Declare variables as close to their first usage as it is possible. For instance, h could be declared inside the body of the for loop:

for (int h = 0; h < TABLINE; ++h)

Reducing scope is important to avoid name collisions and facilitate the understanding of the program states. If you had to remember the state of all variables in a program, you would be doomed. Variables that are scoped inside a { } block can be forgotten as soon at the block ends. There is a discussion here that might also find relevant.
You make two other dangerous assumptions in your program: One is that the input will never exceed one line (you terminate the loop in the first '\n') and that the input will never exceed 100 characters (that's the size of your string buffer). Those assumptions are very unrealistic. More than likely the input would consist of multiple lines in a real world scenario. A 100 chars limit is also quite small. If using a statically allocated buffer, without resorting to malloc and pointers, at least make it a bit bigger and make sure to end the loop when the buffer is full. Something in the lines of (where MAX_CHARS is the size of your char[] buffer):

while (i < MAX_CHARS && (c = getchar()) != '\n' && c != EOF) {
    ...
}

Lastly, there is a confusion with the curly braces in the main loop which I'm not quite sure how the compiler is resolving, but it certainly is broken:

while ((c = getchar()) != '\n' && c != EOF) {
    if (c == '\t')
        for (h=0; h<TABLINE; ++h) {
            stri[i] = ' ';
            ++i;
    } else { // <--- does this belong to the first if ???
        stri[i] = c;
        ++i;
    }
}

As you can see if you look carefully, the } else part is bound to the { in the for loop, the if has no {. I was surprised that this compiled, but it did!

Be very careful with this. My advice is to always add curly braces on all control statements and loops, even for the single line ones.


JavaScript calculator using inputs value

Id attribute cannot contains spaces.

You can also use an object which contains the function's definition for all the possible operations.

var operators = {
  '+': function(a, b) { return +a + (+b) },
  '-': function(a, b) { return a - b },
  '/': function(a, b) { return a / b },
  '*': function(a, b) { return a * b },
};

var operators = {
    '+': function(a, b) { return +a + (+b) },
    '-': function(a, b) { return a - b },
    '/': function(a, b) { return a / b },
    '*': function(a, b) { return a * b },
};
function calculator() {
  var cel = document.getElementById("NumberF").value;
 var celular = document.getElementById("NumberS").value;
  var operator = document.getElementById("NumberO").value;
  var result = document.getElementById("resul");
  if(cel && celular && operator)
    result.innerHTML = operators[operator](cel, celular);
};
<input placeholder="Number" id="NumberF" class="NumberF" onchange="calculator()">
<input placeholder="/ ,  * ,  -  or +" id="NumberO" class="NumberO" onchange="calculator()">
<input placeholder="Number" id="NumberS" class="NumberS" onchange="calculator()">

<button id="button" onclick="calculator()">Click</button>


Your problem is not in the code, but in your algorithm. Brute-forcing the solution as you are doing is fundamentally slow, and you need to tackle the problem from a different angle if you want to make a substantial dent in your runtime.

The problem is constrained in two specific ways we can exploit:

Only letters in the 'a'->'z' range are admissible. That's only 26 letters.
Only strings of length <= 100 characters are admissible. By extension, this means we'll never have more than 100 substrings of a given length to deal with.

Now, if I had a function that converts a substring into "some" representation that's common between annagrammic pairs, but only between annagrammic pairs, I could simply generate that representation for each substring and work off that datastructure instead (probably by using it as a key to a map of number of instances seen).

Since we only have 26 possible letters, a simple std::array<uint8_t, 26>, where each cell represents the number of times a given letter appears in the substring, has all the properties we need.

Just to make sure I'm not spouting nonsense, I gave it a try, and my solution using these principles solves all the hackerrank test cases in under 10ms.

I encourage you to give it a try by yourself, but if you request it, I'll be glad to post the code for my solution here.


The params for testing are different from each object, so I think this part should be put in the classes and present a uniform interface, this is what classes are about.

I suggest 2 versions: either you only put the params needed for test in the classes, or (better in my opinion), you put the entire call to the test in the classes. With some syntactic sugar, this leads to

Only the test data in the classes

class Engine(object):
    """Class that holds information about the
tests relevant to the engine"""

    def __init__(self):
        self.run = True # Flag to run the test or not
        self.kg = 20.5 # Some information required by this test
        self.ok = 'Not run' # Final result to say if the test was passed

    def get_test_params(self):
        return { 'weight': self.kg }

class Wheels(object):
    """Class that holds information about the
tests relevant to the wheels"""

    def __init__(self):
        self.run = True
        self.number = 4
        self.ok = 'Not run'

    def get_test_params(self):
        return { 'nwheels': self.number }

class Door(object):
    """Class that holds information about the
tests relevant to the doors"""

    def __init__(self):
        self.run = True
        self.colour = 'red'
        self.ok = 'Not run'

    def get_test_params(self):
        return { 'shading': self.colour }

class Car(object):
    """Class that holds information about the
different tests available"""

    def __init__(self):
        self.engine = Engine()
        self.wheels = Wheels()
        self.door = Door()

motor = Car()

for partName in 'engine wheels door'.split():
    part = getattr(motor, partName)
    part.on = True # So the test is run (everything is off in your example)
    if part.on: # No need to write "is True", this is what "if" is about
        test_module = __import__(partName + '_tests')
        part.ok = test_module.launch(**part.get_test_params())

print 'Tests completed'
print 'Engine: ', motor.engine.ok
print 'Wheels: ', motor.wheels.ok
print 'Door: ', motor.door.ok

Running the test from the classes

class Engine(object):
    """Class that holds information about the
tests relevant to the engine"""

    def __init__(self):
        self.run = True # Flag to run the test or not
        self.kg = 20.5 # Some information required by this test
        self.ok = 'Not run' # Final result to say if the test was passed

    def run_test(self):
        import engine_tests
        return engine_tests.launch(weight=self.kg)

class Wheels(object):
    """Class that holds information about the
tests relevant to the wheels"""

    def __init__(self):
        self.run = True
        self.number = 4
        self.ok = 'Not run'

    def run_test(self):
        import wheels_tests
        return wheels_tests.launch(nwheels=self.number)

class Door(object):
    """Class that holds information about the
tests relevant to the doors"""

    def __init__(self):
        self.run = True
        self.colour = 'red'
        self.ok = 'Not run'

    def run_test(self):
        import door_tests
        return door_tests.launch(shading=self.colour)

class Car(object):
    """Class that holds information about the
different tests available"""

    def __init__(self):
        self.engine = Engine()
        self.wheels = Wheels()
        self.door = Door()

motor = Car()

for partName in 'engine wheels door'.split():
    part = getattr(motor, partName)
    part.on = True # So the test is run (everything is off in your example)
    if part.on: # No need to write "is True", this is what "if" is about
        part.ok = part.run_test()

print 'Tests completed'
print 'Engine: ', motor.engine.ok
print 'Wheels: ', motor.wheels.ok
print 'Door: ', motor.door.ok

If there's only one car, the last part can become:

for part in (motor.engine, motor.wheels, motor.door):
    part.on = True # So the test is run (everything is off in your example)
    if part.on: # No need to write "is True", this is what "if" is about
        part.ok = part.run_test()


I would definitely wrap the FileStream object into a using clause like this:

using (Stream reader = new FileStream(filePath, FileMode.Open))
{
  var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
  return (T)serializer.Deserialize(reader);
}

This way the Dispose method of the FileStream gets called immediately. Otherwise it will be delayed until the FileStream object gets garbage collected. This may not be a big problem in practice in simple applications where you read the configuration only once but is good practice to do it anyway.
Also note that you have to use XmlSerializer(typeof(T)) instead of XmlSerializer(T).
My opinion is that it is overkill to create a generic method if you have only one kind of configuration file in your app. This method might be hard to read for a maintainer who is not sufficiently comfortable with generics and it has no benefit in making your code DRY-er if you have only one type of configuration file.


Using recursion to count substrings (with exceptions to the rule) in Java

Similar to @Ben Aaronson above but uses indexOf() instead of startsWith()

public int countHi2(String str) {
    int pos = str.indexOf("hi");
    if (pos == -1) {
       return 0;
    }
    int increment = (pos == 0 || str.charAt(pos-1) != 'x')
                      ? 1
                      : 0;
    return countHi2(str.substring(pos+2))
           + increment;
}


Unless you intend (and have carefully designed) for your KeyHandler to be extended, you should make it final.

If you extend KeyAdapter instead of implements KeyListener, you won’t have to implement keyReleased and keyTyped. The Adapter classes in Swing provide empty implementations of all the methods on the interface they implement, so you can just override the ones you care about.

Don’t use int values to represent more complex concepts - those are called “magic numbers”. In this case, just use the constants defined on KeyEvent, namely KeyEvent.VK_BACK_SPACE and KeyEvent.VK_SHIFT.

Put whitespace in between if and (. This visually differentiates control flow keywords from method names. Put whitespace after a , also, to make it easer to separate method arguments visually.

In keyPressed, you don’t need to declare nested if statements. Prefer &&.

Since String is immutable, a StringBuilder is preferred when doing String manipulation. You might not have covered that in class yet. It might be cleaner to use a switch statement on the value of the

It’s probably overkill to have a separate method for printing in this case.

You can clean up your logic by reversing the this.output.length() - 1 < 0 to be this.output.length() > 1 and getting rid of the empty clause.

Note that you’re deleting a character when the shift key gets pressed. Also, no matter how many times shift or delete are pressed, you’re not deleting the first character. These are both probably bugs.

You can just declare the initial value of output when you declare the variable. You don’t need a separate line in the constructor for that.

If you were to implement all my suggestions, your code might look more like:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

public final class KeyHandler extends KeyAdapter {

    private String output = "";
    //private final StringBuilder stringBuilder = new StringBuilder();

    public KeyHandler() {
        super();
    }

    @Override
    public void keyPressed(final KeyEvent k) {
        if ((k.getKeyCode() != KeyEvent.VK_BACK_SPACE) && (k.getKeyCode() != KeyEvent.VK_SHIFT)) {
            this.output += k.getKeyChar();
        } else if (this.output.length() > 1) {
            this.output = this.output.substring(0, this.output.length() - 1);
        }

        System.out.print('\f'); //clear screen in BlueJ
        System.out.println(this.output);

        /*
        switch (k.getKeyCode()) {
            case KeyEvent.VK_BACK_SPACE:
                if (this.output.length() > 0) {
                    this.stringBuilder.deleteCharAt(this.stringBuilder.length() - 1);
                }
                break;
            case KeyEvent.VK_SHIFT:
                break;
            default:
                this.stringBuilder.append(k.getKeyChar());
        }

        System.out.print('\f'); //clear screen in BlueJ
        System.out.println(this.stringBuilder.toString());
         */
    }

    public static void main(final String[] args) {
        final JFrame frame = new JFrame("KeyEvent Handler");
        frame.setSize(400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addKeyListener(new KeyHandler());
        frame.setVisible(true);
    }
}


Cleaning up code and making better loops for soccer shoot-out game

Not a bad start. However here's a few things that immediately pops out when I look at the code.

Avoid duplication: The code for both players to kick is exactly the same. You should try to move that into a function instead of writing it out twice.
Make a player class: By moving all the code for a player into a class, you avoid having to keep each variable twice. Instead of shot_1/shot_2, result_1/result_2 etc, you could have player[0].shot, player[0].result etc.
Make a game class: While you're at it, why not also turn the game itself into a class. I think this would solve your looping problem all by itself.

Something like this:

class Game
  def initialize
    # set up for a new game
  end

  def play_round
    # play one round of the game
  end
end


Find the number in an array which is closest to an given number

mov edi, edi    ; Index of the element with the smallest value.

An error here. You want to zero this register. Use xor

A better strategy will be to simply subtract without looking at which number is the largest and then later take the absolute value of the difference.

    mov     eax, [nums + 4 * esi]
    sub     eax, ebx
    jnl     IsPositive
    neg     eax
IsPositive:
    cmp     eax, edx ; Compare the result to the current smallest value.
    jnb     prepare_next
    mov     edx, eax
    mov     edi, esi
prepare_next:

Less code and less register usage!

A further optimization will come from not using ECX as a loop counter. You can determine if the loop is completed by looking at the ESI array index.

    xor     esi, esi         ;Start at index 0
check_next:
    ...
    inc     esi
    cmp     esi, (nums_end - nums) / 4
    jb      check_next

In stead of branching, you could use one of the conditional forms of mov.
Same code size but faster. Having less labels is also nicer.

    cmp     eax, edx ; Compare the result to the current smallest value.
    cmovb   edx, eax
    cmovb   edi, esi

About coding style.

mov eax, dword[nums + 4 * edi]

Does your assembler requires you to write this redundant mention of the size?
Do you get an error if you write it shorter?

    mov     eax, [nums + 4 * edi]


Prime numbers with array and OpenMP in C

A couple of minor things.
For int psize, consider using size_t.
log(sqrt(maxn)) should simply be log(maxn)/2, which is equivalent.


A few things pop out:

this:

needle_dict = dict(zip(list(set(needle).union(set(haystack))), range(len(list(set(needle).union(set(haystack)))))))

...creates two identical sets.  More space(and time, perhaps) efficient to do:

        straws = list(set(needle).union(set(haystack)))
        needle_dict = dict(zip(straws), range(len(straws)))

this:

dfa = [[0 for i in range(M)] for j in range(R)]

...does needless iteration.  Instead do:

    dfa = [ list(range(M)) for j in range(R) ]

There's a small bug in:

if len(needle) == 0:
    return 0
if (haystack == None or needle == None or len(haystack) < len(needle) ):
    return -1

... in that you're calling len(needle) before testing if it's None.

It's unclear why you're doing:

global needle_dict

... it may have performance implications (though I'm not positive).


Merge sort in declarative style with JavaScript

I'd move the helper functions into sort's scope. Names like any and merge are very generic, and don't need to be cluttering up the global scope.

I also question the need for some of the functions, especially dropHead. It's just a synonym for Array.shift, so why not just call shift? All you get is a function with side-effects; since shift modifies the receiver, dropHead modifies the passed-in array, but at an extra level of, well, obfuscation almost.

The naming of isSingleton isn't great either. "Singleton" in OO languages usually has precise meaning. In mathematics it refers to a single-element set, but in a programming context I'd expect it to check whether the array object itself is a singleton.

In the end, I'd just say array.length === 1 where needed. And any can be replaced with array.length > 0 or even array.length as zero is falsey. Is it as declarative? Maybe not, but in my opinion it's more readable JS than inventing new expressions.

Conversely, I see no reason to skimp on the naming of variables and properties. Why fst and snd instead of simply first and second? Why xs instead of just array or items or list? If the goal is to be declarative, I see little point to use overly terse naming.

Your main sort function has a subtle gotcha: If you return early because the array is a "singleton" or empty, you return the same array reference that was passed in. If there's actual sorting going on, you return a new array object. So the function essentially has two distinct behaviors depending on input - dangerous. I'd recommend that the early return uses xs.slice(0) (or just xs.slice()) to ensure that it's always a copy that's returned.

There are a few ES6 features you can use, although support is spotty. One is to use array destructuring instead of object destructuring to assign the return value(s) from split. It obviates the need for fst/snd, and by returning an array you ensure ordering, rather than having to explicitly assign fst and snd in order, or even having to know those property names. E.g.

const [head, tail] = split(array); // where split() returns a 2-element array

Returning an array also means you can simply run it through map instead: split(array).map(sort).

Also, you don't need the two extra while loops to yield the elements of xs and ys in your merge function; you can simply delegate the yielding to the arrays themselves:

yield* xs;
yield* ys;

In all, I'd write something like:

const sort = array => {
  const split = array => {
    const middle = array.length >> 1; // should be a safe use of bitwise trickery
    return [array.slice(0, middle), array.slice(middle)]
  };

  const merge = function* (a, b) {
    while(a.length && b.length) {
      yield a[0] <= b[0] ? a.shift() : b.shift();
    }

    yield* a;
    yield* b;
  }

  if(array.length < 2) {
    return array.slice(0); // always return a copy
  }

  return [...merge(...split(array).map(sort))];
}

I've skipped the head function as it'd only be used twice - in the same line even. The remaining helper functions are nicely "symmetrical": Split and merge.

Edit: Just realized something: Your sorting isn't stable. In fact, it's precisely not stable. A quick test:

 var test = [1, "1", 2, "2", "3", 3]; // already sorted

 test = sort(test) // =>  ["1", 1, "2", 2, 3, "3"]
 test = sort(test) // =>  [1, "1", 2, "2", "3", 3]
 test = sort(test) // =>  ["1", 1, "2", 2, 3, "3"]
 // ...

Long story short: The merge branching should use <= rather than < when deciding which array to shift from. I've corrected the code in this answer.

Addendum: It might be more declarative and pattern-matching'y to use a switch statement to determine whether to return early:

const sort = array => {
  const split = array => {
    const middle = array.length >> 1;
    return [array.slice(0, middle), array.slice(middle)]
  };

  const merge = function* (a, b) {
    while(a.length && b.length) {
      yield a[0] <= b[0] ? a.shift() : b.shift();
    }

    yield* a;
    yield* b;
  }

  switch (array.length) {
    case 0:
    case 1:
      return array.slice();
    default:
      return [...merge(...split(array).map(sort))];
  }
}


I find your code amusing but since this is not Code Golf but Code Review I'll review it from our perspective this is, as clean-code first.

Even if you try to write compact code you should not use magic exressions and sacrifice readability. Instead encapsulate them in (local) function or use proper constants. You also should not use unrelated variable names like here i for char where c would be more appropriate. Alternatively you can also use the Aggregate to loop over the string and collect the results in a StringBuilder. The (char)0 can be replaced with the much prettier default.

const char caseOffset = (char)(1 << 5);

char SwapCase(char c) => c ^= (char.IsLetter(c) ? caseOffset : default);

var result =
    "heLLo, woRLd"
        .Aggregate(
            new StringBuilder(),
            (b, c) => b.Append(SwapCase(c))
        ).ToString();

One more option would be to use Select and new string and feed it with the new result.

var result = new string("heLLo, woRLd".Select(SwapCase).ToArray())

The advantage of Select is that you don't need the => lambda anymore.


Showing events on a multi room scheduler

I asked you how you would do it in jQuery and you said that you would do something like:

$.each(events, function(event){
    var el = $("

")
        .addClass("event")
        .css({ "height": event.duration + "px", "top": event.start + "px" })
        .text(event.title);
    $('.room').data('place', event.place_id).append(el);
});

And sure, this would only loop through the events array once. But what happens in every iteration? It does a jQuery search for $('.room').data('place', event.place_id), which is not a constant-time lookup operation, so this approach might be slower than what you think it is.

Now, for your Vue approach. You said:

  maybe I need to do it on backend to make a rooms array look like that: { id: 1, title: 'Room 1', events: [{ id: 1, title: 'Event 1', start: 90, duration: 30 }] }

And yes, I agree with this. Putting the events inside your rooms makes much more sense.

As for your Vue template, overall the code looks fine. I'm not a CSS expert so I don't know if there's something you can improve there, but there probably is. Maybe consider using CSS Grids, where each room could be one column, and time-slots could be rows? The current approach of having 1px = 1 minute seems a bit unnatural to me.

As for this part:

  {{ room.title }}

{{ event.title }}

The only thing I would change is to put v-for and v-if before your :style-binding, as they are more important to be aware about, this is mostly my personal opinion though.

  {{ room.title }}

{{ event.title }}

It would be nicer if your events would be inside the rooms, as then you could write:

  {{ room.title }}

{{ event.title }}

I would recommend in the future to use a Room component and a RoomEvent component so that you could write:

<Room v-for="room in rooms" :key="room.id" />

And the room-component:

  {{ room.title }}
  <RoomEvent v-for="event in room.events" />

I think that the
{{ event.title }}
 belongs inside the RoomEvent

Overall a nice job!


Coursera: Calculating sum of numbers in the fibonacci sequence between two specific points in the series

Runtime improvement

If you take a look at the last digit of the first few fibonacci numbers you will see that the digits are repeated after 60 numbers. As the digits in this range have a sum of 0 you can calculate the sum for [from%60,to%60] instead.

Bug

The task states that the given integer are non-negative, 0 is a valid value. Currently you are returning i.e. 1 for the range [0,2] as 0 is treated as 2, the initialization of sum has to be changed to:

if (from <= 1) {
    sum = 1;
} else {
    sum = 0;
}

(I would initialize sum with a ternary operator long sum = from <= 1 ? 1 : 0 instead.)

Types

As the values of sum, prev and cur are always in the range [0,10), you can use int instead of long for these variables, int arithmetic is likely to be faster than long arithmetic.

Alternative implementation

The remaining range is quite small -> you could cache the results for every number in the range [0,60) to avoid calculating the sum on each invocation.

private static final byte[] DIGIT_SUM = {
        0, 1, 2, 4, 7, 2, 0, 3, 4, 8,
        3, 2, 6, 9, 6, 6, 3, 0, 4, 5,
        0, 6, 7, 4, 2, 7, 0, 8, 9, 8,
        8, 7, 6, 4, 1, 6, 8, 5, 4, 0,
        5, 6, 2, 9, 2, 2, 5, 8, 4, 3,
        8, 2, 1, 4, 6, 1, 8, 0, 9, 0};

private static int fibonacciPartialSum(long m, long n) {
    assert m <= n & (m | n) >= 0;
    int v = fibSumLastDigit(n);
    return m == 0 ? v : (v -= fibSumLastDigit(m - 1)) + (10 & v >> -1);
}

private static int fibSumLastDigit(long n) {
    return DIGIT_SUM[(int) (n % 60)];
}


Security

This can be bypassed by /\...

You are currently checking if / is followed by . and reject the input if that is the case. But as you can see, it is possible to traverse with different sequences (null bytes would be another candidate for bypasses).

It would be a bit more secure if you checked for ... To really prevent directory traversal, you should check if the resolved path is inside the desired directory.

Misc

dieing inside a function is always a bad idea, as you have no more control over the code. The calling function can't recover, the function can't be reused, etc.
You are vulnerable to XSS.
I would put each statement on it's own line (e.g. if/else on the same line is a bit difficult to read).


It does not matter whether a > b or b > a, two cases should be enough for positive integers:

def gcd(a, b)
  b == 0 ? a : gcd(b, a.modulo(b))
end

Check also Integer#gcd.


Faster way to determine largest prime factor

My problem is finding a way to streamline the algorithm to greatly reduce the processing time.

Well, if we take into account that we are on Code Review, than an answer to this could be a little bit off the scope, as @HosamAly has already written, too. I will investigate this a little bit further.

Problems related to prime numbers are studied very extensive. The conclusion of this is, whatever you do, you will most probably just reinvent the wheel.

So the question should not be "how to reduce the processing time", it should be "how to handle my problem" which leads to the question of the problem definition. If your problem definition is just as mentioned "What is the largest prime factor of the number 600851475143?", then take the number, put it into Wolfram Alpha, and be done in 5 seconds.

If your problem definition is more like "How can I calculate the largest prime factor of a given integer?" Then find any algorithm/library, check if it is suitable and be done.

If your problem definition is a real world requirement, then find out the time constraint. It is always about time constraints for real world problems like this. Without a time constraint, you could improve it literally forever.

If your problem definition is more like "I want to improve my knowledge about coding and optimization in Java and I will try the problem xyz" Then there is no real answer to this. You could ask probably for some solutions on stackoverflow (as far as I got it, they do not like questions for euler problems there, so hide it a little bit. I would post an answer there if you link it).

Some suggestions about your code were already done, but I do not see the point in giving advices in optimization here.

My suggestions about the code:

long lgstPrime = 1;

Please write the full name, so everyone can read and understand it. Is it longestPrime, largestPrime, logarithmstPrime? You do not save real time or space by saving some characters (assuming we are in Java and not something like fortran77).

long max = 600851475143L;
for (int i = 2; i < max; i++) {
    ...
}

I do not think that your code will work and output anything. This is an infinite loop. Why? Because i is an integer, it will overflow at Integer.MAX_VALUE (2^31 - 1 or 2147483647) starting at Integer.MIN_VALUE or -2147483648 again. This will never reach max which is greater than 2147483647. So the loop will run forever.

Example to test:

final long max = 600851475143L;
for (int i = 0; i < max; i++) {
    if (i == Integer.MAX_VALUE)
        System.out.println("will overflow now");
}

Better:

long max = 600851475143L;
for (long i = 2; i < max; i++) {
    ...
}

For readability, stick to one coding style:

for (int i=2; i<max; i++){
      for (int j=2; j<=i; j++){
          if ((i % j == 0) && (j != i))

Better:

for (int i = 2; i < max; i++) {
    for (int j = 2; j <= i; j++) {
        if ((i % j == 0) && (j != i))


Simple ES6 Truncate method for character, word, and sentence limits

The parameters of sentences and words appear to be out of order when passed to prune(). Not sure why the parameters passed to prune are hard-coded at the example, though still passed to prune(). Since words does not pass a parameter for at, 10 is used, which is not the expected result, though can be remedied by defining the parameter at at words and sentences functions, given that each function call expects all three parameters, and at is not defined at any of the functions at the code at the question; instead num is set to int.

Adjusted body of prune to include an immediately invoked arrow function to handle the resulting array of .split() where delimiter character ! is not contained in string by checking if the element at index 0 of array is equal to val, if true spread val to array else use existing array to chain .splice() to, then concatenate an empty string or at following .join() call. At which point the same function can be substituted for sentences, words and characters.

const truncate = ((
  value = '',
  int = 0,
  elipsis = '\u2026', /* ... */
  prune = (val, at, num) =>
            ((s, k = s[0] === val) =>
              `${(k ? [...val] : s)
                 .splice(0, num)
                 .join(k ? '' : at)}${k ? at : ''}`)
            (val.split(at))
) => {
  const sentences = (val = value, at, num = int, end = elipsis) => prune(val, at, num) + end;
  const words = (val = value, at, num = int, end = elipsis) => prune(val, at, num) + end;
  const characters = (val = value, at, num = int, end = elipsis) => prune(val, at, num) + end;
  return {sentences, words, characters};
})();

console.clear();
console.log([
  truncate.sentences("This is a sentence. There are many like it but you won't see the 2nd one", '.', 1),
  truncate.words("These are words but you won't see what's after this because it'll be hidden", ' ', 10),
  truncate.characters("This won't exceed 31 characters so we cutting off the ending", '!', 31)
]);

Alternatively, though not consistent with the sentences, words can be composed with at being set as a default parameter

const words = ({val = value, at = ' ', num = int, end = elipsis} = {}) => prune(val, at, num) + end;

which would be called with

truncate.words({val: "These are words but you won't see what's after this because it'll be hidden", num: 10})

providing the ability to call the function without explicitly setting and passing at as a parameter.

Substituting a single function for sentences, words and characters

const truncate = (
  value = '',
  at = '',
  num = 0,
  elipsis = '\u2026', /* ... */
) => ((val, k = val[0] === value) =>
       `${(k ? [...value] : val).splice(0, num)
          .join(k ? '' : at)}${k ? at : ''}${elipsis}`)
     (value.split(at));

console.clear();
console.log([
  truncate("This is a sentence. There are many like it but you won't see the 2nd one", '.', 1),
  truncate("These are words but you won't see what's after this because it'll be hidden", ' ', 10),
  truncate("This won't exceed 31 characters so we cutting off the ending", '!', 31)
]);


Streamline code for checking if a directory exists and saving a file

Since CreateDirectory does nothing if a directory already exists, you can do this:

MyFile = f;
SaveFolder = Path.Combine(Server.MapPath("\\"), "returns");
System.IO.Directory.CreateDirectory(SaveFolder);
MyFile.SaveAs(SaveFolder, "2011000-00-0000.xlsx");


std::function alternative with no dependencies

Self-assignment may be expensive, but it should be a no-op instead of UB. I suggest copy-and-swap.
Omitting move-semantics will most certainly cost you.
Your naming of the internal class suggests all callables are lambdas. Not true!
You cannot store any move-only callables. Admittedly std::function is also crippled in that respect. Just throw an exception if the non-copyable object needs to be copied.
If your function has return-type void, it should simply discard the callables return-value. You don't.
std::function throws an exception if empty when called. Using assert() is less than a pale imitation.
delete p; if p is a null pointer is a no-op. No need to double-check.
Conversion to bool should be explicit. Otherwise, conversion to any arithmetic type can happen.
As you said, yours is less efficient. That's especially the case when std::function benefits from mandatory small-object-optimization.
You don't use SFINAE when creating from a callable. That can be inconvenient.


Instance of one class to contain arbitrary number of instances of another class in Python

In Habitat.__init__, you've committed a classic beginner's fallacy: using a list as a default argument.

In Python, every call to a function with a default argument will use the same default object. If that object is mutable (e.g. a list) any mutations to that object (e.g. .append) will affect that one object. In effect, all your Habitats will end up using the exact same list unless you specify a non-default argument.

Instead, use None as the default argument, and test for it:

def __init__(self, animals=None):
    if animals is None:
        animals = [Male(), Female()]


You can streamline the code by caching the selectors; this will improve performance as well. Next, you should use prop instead of attr as the jQuery documentation states:

  The .prop() method should be used to set disabled and checked instead
  of the .attr() method.

Lastly, instead of using an if..else statement, you can write the condition inline, since checked expects a boolean, and the expression resolves to a boolean. In other words:

// Cache selectors
var $all = $('#checkall');
var $checks = $('input[type="checkbox"]').not($all);

$all.on('click', function () {
  $checks.prop('checked', $(this).is(':checked'));
});

$checks.on('click', function() {
  var checked = $checks.filter(':checked').length;
  $all.prop('checked', checked === $checks.length);
});

Here is a demo: http://jsfiddle.net/z7qy10nn/


Replacing all the 'u' with specific character that is given by the user

Rather than rewrite your code here are some pointers for your next interview.  Yes, I have sat on the interviewer's side of the table a few times.

Whenever you are taking input directly from a user, as here, a rule-of-thumb is that you need to spend about one third of your code checking that the input is valid.  For example, you ignore multiple character input for the second line.  If your user types in "armadillo" at least give warning that the input is too long and you are ignoring the "rmadillo" part.  A few on-screen user prompts would have been nice as well.

One of the things the interviewer is testing is how well you know the more common Java libraries.  As @Adriano said, using String.replaceAll() would be both easier to code and show that you know the libraries.

Another thing being tested is if you are aware of the memory/processing penalties of working with Strings.  Java Strings are immutable so only the built-in methods can change things under the hood.  If you are going to make multiple changes from the outside then do not make the changes directly to the original string.  Convert the String to either a char[] or to a StringBuilder.  Make the changes there and convert the final result back to a String.

Did the interviewer ask you to print a message if there was no 'u' present in the original string?  If not then don't add extra stuff like that.  In a programmer job you have to code what is specified, no more and no less.  The replaceChar() method is the type of general-purpose function that is buried somewhere in a library.  Library users do not want extraneous messages popping up from apparently nowhere.  Unless otherwise specified, the only output from a method should be void, a return value or possibly an exception.  Your printing is a side-effect, and so to be avoided unless specifically required.  I would have written the method as:

private static String replaceChar(String str, char ch) { ... }

and done the printing from main().

You have a 'magic number', the constant 'u'.  Better to pull that out as a declared constant so it is obvious what it is, and to show you are aware of the need to avoid 'magic numbers' in code.

As a minor tweak, you could have checked if the input character was 'u' and immediately returned the original string unchanged.


Not really
I think that's about as succinct as it will get. You could improve readability somewhat with some line breaks though, like this:
.navbar-inverse .emphasis-text,
.navbar-inverse:hover .emphasis-text,
.emphasis-text {
    color: #1caa98; /* Teal */
}


TicTacToe where the computer plays random moves against itself

Some of your functions can use list comprehensions.

As you seem to know maths, you may have come across 'set-builder notation',
and that's what list comprehension are based off:

\$S = \{2 \times x | x \in \{0, 1, ..., 9\}, x^2 > 3\}\$

Which in Python is:

[2 * x for x in range(10) if x ** 2 > 3]

I would use it in:

find_move for an improvement in clarity.

def find_move(board, player):
    return random.choice([pos for pos in range(9) if board[pos] == 0])

write_board to use less prints. It's harder to read however.

print '\n'.join([
    ''.join([letter[row + col] for col in range(3)])
    for row in range(0, 3, 9)
])

check_winner you can make your for pos in seq one.
Using all.

for player in [1, 2]:
    for seq in winning_rows:
        if all([board[pos] == player for pos in seq]):
            return player

I'm surprised you didn't make a new_board function. Which could be:

def new_board():
    return [0 for _ in range(9)]

Alternatively, as noted by @i-live-in-a-storm-drain, if you are ok with shallow copy's you could change it to:

def new_board():
    return [0] * 9

The down-side to this is if you mutate any of the items, then you mutate all of them. For example you wouldn't want to make a 2D list with it.

>>> a = [[0] * 3] * 3
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Your function make_move seems, kinda pointless...
I would use board[move] = player over the function.
You should use is when comparing to singletons, None.

# Bad
if winner != None:

# Good
if winner is not None:

You could make the win conditions a list, and print from that.

win_statments = ["Player 1 (X) wins!", "Player 2 (O) wins!", "Game is a draw!"]
print win_statments[winner]

For check_winner you can use the fact 0 == False (Not 0 is False).
With Python's builtin all to check if all of them are not 0.

if not all(board):
    return None

As this is Python2 it's recommended to use xrange rather than range for almost everything.
You'll get a, minimal, speed increase in most situations.

However as noted by @Janos, you could opt to keep them as range, for an easier transition to Python3. This is as there is no xrange in Python3.
You should only need to change your prints to functions for this to work in Python3.

# Change to these:
print("Player 1 (X) wins!")

# in `make_move`
for col in range(3):
    print(letter[board[row*3+col]], end='')
print()


Find all words in a dictionary that can be made with a string of characters (Recursion/Binary Search)

Favor interfaces over implementations

private ArrayList<String> dict = new ArrayList<>();

This would more commonly be written as

private List<String> dict = new ArrayList<>();

Using the interface is more flexible and easier to change.

Dictionary types

That said, the more common type for a dictionary is

private Set<String> dictionary = new HashSet<>();

Then you can generate all the words and check them.

If you are committed to a binary search, consider using a NavigableSet.

private NavigableSet<String> dictionary = new TreeSet<>();

This would give you code like

    for (char letter : letterPool.toCharArray()) {
        String current = word + letter;

        String bound = word + (letter + 1);
        NavigableSet<String> prefixed = dictionary.subSet(current, true, bound, false);

        if (prefixed.isEmpty()) {
            // no need to keep looking if we didn't find anything
            continue;
        }

        // current will be the first element of the Set if present
        if (prefixed.first.equals(current)) {
            possibleWords.add(current);
            prefixed.pollFirst();
        }

        // if there's more than one letter left in the pool
        if (letterPool.size > 1) {
            // recurse with it out of the pool
            String remaining = letterPool.substring(0, i) + letterPool.substring(i + 1);
            getAllValidWords(remaining, current, prefixed);
        }
    }

I changed the names of currWord to word, newLetterPool to remaining, and curr to current, as I find that easier to read.  Your mileage may vary.

We don't need to check if letterPool or word are empty.  The code works for those cases.

I added prefixed to the recursive call.  The reason is that we don't need to search the whole tree.  We only need the subtree.

I moved generation of newLetterPool to the point where I know it will be used.  Prior to that we may never use it, so why waste time generating it?

Trie

This is the application for which a Trie is designed.  That said, my experience is that they tend to be slow and memory intensive.  It takes too long to build the structure to get the gains from fast prefix searches.

You might well find the brute force solution with a HashSet to be faster.  In that solution, you basically generate each possible permutation and then filter out just the ones that are words.  The downside is that you may check a lot of words like zxqjv.

A Trie works best in situations where it's prebuilt and easy to load into memory or where it stays as it is for long periods of time.  Also, you should not be memory constrained.

If you do attempt to use a Trie, consider using it only for the first few letters.  Then you can go back to something more like this.


As to the security of this:

if [ -x /usr/local/libexec/path_helper ]; then
  eval `/usr/local/libexec/path_helper`
fi

This runs the path_helper script, which presumably outputs a string, and then the command represented by the output string is run in the local context.  So this initially presumes you trust path_helper to run anything it wants.  I don't think path_helper could much more damage by running something in your shell instead of what it already ran in a sub-shell.


Percentage of questions that are unanswered or answered - Part 2

Your code has certainly improved from last time, however there's a few things that could be improved:

AND AnswerCount <= 1: that could be AND AnswerCount < 0.
You don't need to recreate the amount of unanswered questions twice:

DECLARE @AnsweredPercentage FLOAT =
  100.0 - ((@UnansweredQuestions / @TotalQuestions) * 100.0);

DECLARE @UnansweredPercentage FLOAT =
  (@UnansweredQuestions / @TotalQuestions) * 100.0;

into:

DECLARE @UnansweredPercentage FLOAT =
  (@UnansweredQuestions / @TotalQuestions) * 100.0;

DECLARE @AnsweredPercentage FLOAT =
  100.0 - @UnansweredPercentage;


This code doesn't work, as can be shown by including <algorithm> and changing the output:

std::cout << std::is_sorted(tobesorted.begin(), tobesorted.end()) << std::endl;

Other things that are surprising:

We pass pointers but always assume they are not null.  That suggests we should be using references instead.
Misspelt std::srand and std::time - though I'd recommend using <random> instead.
std::endl used where there's no need to flush output - just write \n instead.
Why are we using int rather than std::size_t for our left and right indices?
Use of floating-point multiplication for integer arithmetic.
Unused variable j.

There's a risk of overflow here:

int mid = (left+ right)/2;

Better would be

auto mid = left + (right - left) / 2;

This code can be re-written:

std::vector<int> leftvec;
std::vector<int> rightvec;

for(int i= left; i <= mid; i++){
    leftvec.push_back(pvec[0][i]);
}
for(int i= mid+1; i <= right; i++){
    rightvec.push_back(pvec[0][i]);
}

Those vectors will likely re-allocate several times as they are filled, because we didn't reserve() capacity.  Instead of those loops, we could use the appropriate constructor:

std::vector<int> leftvec(pvec->begin()+left, pvec->begin()+mid);
std::vector<int> rightvec(pvec->begin()+mid, pvec->>begin()+right+1);

It would be easier if we passed iterators rather than indices here.


BDD in PHP, Testing search in Wikipedia with Behat and Mink (Selenium2 Driver)

There is one major point that we can do here. In the FeatureContext.php, if class FeatureContext extends MinkContext, then you do not need to write any of the function definitions at all!

Applying what I just said, will result to have FeatureContext.php to be as:

<?php

use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext; //This line is add

class FeatureContext extends MinkContext // This line is changed
    implements Context, SnippetAcceptingContext
{
    public function __construct()
    {
    }
}

Note: To make the point more clear, I have removed the comments that are generated by behat.


a standalone client that consumes messages from the queue every time a message exists

If you want to process the messages in real time, implementing a message listener is the most practical way -- this way you let ActiveMQ and JMS handle the continuous checking that you're currently doing. As you said, you could do this in a WAR, but a JAR, or thread could accomplish the same task.

If you weren't implementing runnable and coding inside your current while (isRunning) { loop, your current setup would be more appropriate for retrieving one message at a specific time.  Since you are, you're basically telling the JVM to create a connection, create a session, retrieve one message, kill everything, and start over.  This just adds a ton of overhead best left to the API.


A couple of things I noticed:

No Identification Division. "The IDENTIFICATION DIVISION has no effect on the execution of the program but is, nevertheless, required as a means of identifying the program to the computer" - Stern & Stern
There is no real reason for the first REDEFINES. Also, you seem to be using it wrong. A redefines clause is simply another way to reference the same working storage location. If you want to store different data, that will require different variables. While you can keep redefining the same variable and using it in different way, it can get messy and storing things gets harder.
While you can have level 3 variables, I have found it to be best practice to go up in increments of 5
A lot of the time, if you are working in a real COBOL environment, you will need an environment division. Clearly here you don't, but keep that in mind
You should start all variable names in the WORKING-STORAGE SECTION with WS- because if this program need to interact with any other programs, you will have a LINKAGE-SECTION with its own set of variables.
Only use periods to end paragraphs. Technically, you can use a period to end anything. This leads to messy code. Also, a period closes ALL open statements. If you have a triple nested IF and you end with one period, it will close all 3. When you get to that point, use the proper scoop terminators such as END-IF and END-PERFORM
Spacing is important as well.

The logic problems have already been address in another answer, so I will not address that here. I have included the code below with my suggestions added to it:

        INDENTIFICATION DIVISION
        PROGRAM-ID. THE-TIMER.
        AUTHOR. name.
        DATE-WRITTEN. date.
        DATE-COMPILED. date.
        *****************************************************************
        *header comment about the program change logs ect               *
        *****************************************************************

        DATA DIVISION.
        WORKING-STORAGE SECTION.

        01 TIME-STORAGE.
            05 WS-CURRENT-TIME        PIC 9(8).
               10  WS-CURRENTHOUR     PIC 99.
               10  WS-CURRENTMINUTE   PIC 99.
               10  WS-FILLER          PIC 9(4).

            05 WS-ARIVAL-TIME         PIC 9(8).
               10  WS-ARRIVALHOUR     PIC 99.
               10  WS-ARRIVALMINUTE   PIC 99.
               10  WS-FILLER          PIC 9(4).

            05 WS-ETA                 PIC 9(8).
               10 WS-ETAHOUR          PIC 99.
               10 WS-ETAMINUTE        PIC 99.
               10 WS-FILLER           PIC 9(4).

        PROCEDURE DIVISION.

            BEGIN-BUG-NORMAN.

            DISPLAY "when will you be ariving?"
            DISPLAY "HH [enter]"
            ACCEPT WS-ARRIVALHOUR
            DISPLAY "MM [enter]"
            ACCEPT WS-ARRIVALMINUTE

            ACCEPT WS-CURRENT-TIME FROM TIME
            SUBTRACT WS-ARIVAL-TIME
                FROM WS-CURRENT-TIME
                GIVING WS-ETA

            DISPLAY "RESULTING ETA: "
            DISPLAY ETA-NUMERIC
            DISPLAY "HOURS: "
            DISPLAY CURRENTHOUR
            DISPLAY "MINUTES: "
            DISPLAY CURRENTMINUTE

            IF WS-ETAHOUR > 5
               DISPLAY " It could be a while"
            END-IF

            STOP RUN.