Linked List Interview Code methods, runtime, and edge cases refactored

I see a number of things that could help you improve your code.

Don't define a default constructor that only initializes data

Instead of writing this:

class LinkedList
{
    Node* _head;
    Node* _tail;
 public:
    LinkedList() : _head(nullptr) { }
    // etc.
};

write this:

class LinkedList
{
    Node* _head = nullptr;
    Node* _tail = nullptr;
 public:
    // no need to explicitly write default constructor
    LinkedList() = default;
};

See Cpp Core Guidelines C.45 for details.  Note also that this initializes both member data items.

Think about whether the destructor should be virtual

For an interview, you should be prepared to answer why the class destructor is not virtual and to explain circumstances in which it should be virtual.

Eliminate redundant variables

The current code contains this constructor:

LinkedList(int data) { // O(1)
    Node* n = new Node(data);
    _head = n;
    _tail = n;
}

I'd prefer to see n eliminated and to see it written instead like this:

LinkedList(int data) :
    _head{new Node{data}}, _tail{_head} {}

Use for rather than while where appropriate

The desructor currently looks like this:

~LinkedList() { // O(n)
    Node* current = _head;
    Node* n;
    while(current) {
        n = current;
        current = current->next;
        delete n;
    }
    _head = nullptr;
}

Rather than introducing two extra variables, I'd write it using a for loop like this:

~LinkedList() { // O(n)
    if (_head == nullptr) {
        return;
    }
    for (auto current{_head->next}; current; current = current->next) {
        delete _head;
        _head = current;
    }
}

Fix the memory leak

The current code has this member function:

void append(int new_data) { // O(1)
    auto n = new Node(new_data);
    if(!_head) {
       _head = n;
       _tail = n;
    }
    else {
        _tail->next = new Node(new_data);
        _tail = _tail->next;
    }
}

The problem is that we create two nodes but only use one unless the list is empty.  I'd fix that like this:

void append(int new_data) { // O(1)
    auto n{new Node(new_data)};
    if(_head == nullptr) {
       _head = _tail = n;
    } else {
        _tail->next = n;
        _tail = _tail->next;
    }
}

Simplify your code

The remove function is much more longer than it needs to be.  Right now it looks like this:

    void remove(int target_data) { // O(n)
        if(!_head) { return; }
        Node* previous = nullptr;
        auto current = _head;
        for(; current->data != target_data; current = current->next) {
            if(!current->next) {
                return;
            }
            previous = current;
        }
        if(!current->next) {
            if(previous) {
                delete current;
                previous->next = nullptr;
            }
            else {
                 delete current;
                _head = nullptr;
            }
        }
        else {
            auto dangling_ptr = current->next;
            current->data = current->next->data;
            current->next = current->next->next;
            delete dangling_ptr;
        }
    }

It could be made somewhat simpler by creating a temporary Node that points to _head:

void remove(int target_data) { // O(n)
    Node headptr{0};
    headptr.next = _head;
    for (Node* curr{&headptr}; curr && curr->next; curr = curr->next) {
        if (curr->next->data == target_data) {
            auto victim = curr->next;
            if (victim == _tail) {
                _tail = curr;
            }
            if (victim == _head) {
                _head = victim->next;
            }
            curr->next = victim->next;
            delete victim;
            return;
        }
    }
}

Rethink the interface

It's not unreasonable to expect that one might want to actually do something with the things inserted into a list.  Right now, there's no way to do anything except print which suggests an incomplete interface.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Make test success obvious

The current test code exersizes the list, but it doesn't indicate what is expected to be printed.  I'd instead write both test scenarios and also the expected result so that it would be clear to anyone running the code whether everything was working as expected or not.

Consider using a template

A linked list is a fairly generic structure that could hold any kind of data if the class were templated, and not just an int.

Consider possible uses

For any code production, but especially if you're in an interview, think about how the class is being used and whether there are any restrictions or limits inherent in the design.  For example, think about copy and move operations.  If you write this, does the code do the right thing?

LinkedList a;
a.append(1);
a.append(2);
a.append(3);
a.append(4);
auto b{a};
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
a.remove(1);
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';

Also consider multithreaded code.  Would it be thread-safe to insert nodes from one thread and remove them from another?  If not, what would be needed to make that work?


What I don't like about your approach is that the lock objects are never removed from FooServiceCacheLocks, even when the object is removed from the cache.

One way to simplify your code would be to combine MemoryCache with Lazy: instances of Lazy are cheap (as long as you don't access its Value) so you can create more of them than needed. With that your code would look something like this:

public IEnumerable<Foo> GetFoosForBar(int barId)
{
    var newLazy = new Lazy<IEnumerable<Foo>>(
        () => this.ExplicitService.GetFoosForBar(barId));

    var lazyFromCache = (Lazy<IEnumerable<Foo>>)MemoryCache.Default.AddOrGetExisting(
        barId.ToString(), newLazy, DateTime.Now.AddMinutes(5));

    return (lazyFromCache ?? newLazy).Value;
}


Convert Tail-Call Recursive Code to Loop

A quick search for "python tail call optimization" results in this SO answer which has a PyPI package, tco. Converting your code to return lists rather than generators should be all you need.

  recursion is the only way to do looping in a logic programming language

This is wrong.

If you want it to stay as a generator, then you'll have to manually handle the stack. The following doesn't account for order so if you need that then you'll have to figure that out yourself.

def evaluate_and(and_clauses, binds={}):
    stack = [(clauses, binds)]
    while stack:
        and_clauses, binds = stack.pop()
        if and_clauses == []:
            yield binds
        else:
            head, *tail = and_clauses
            possible = evaluate(head, binds)
            for p in possible:
                stack.append((tail, p))


Project Euler # 49 Prime permutations in Python

Micro optimisations in is_permutation

In is_permutation, you could call the str functions after checking whether n1 == n2.

Also, you could simplify the end of the function with a single return to_str_1_digits == to_str_2_digits.

Taking into account these comments and shortening a bit the variable names, we get:

def is_permutation(n1, n2):
    """returns True if n1 is permutation of n2"""
    if n1 == n2:
        return False
    str1 = str(n1)
    str2 = str(n2)
    digits1 = {digit: str1.count(digit) for digit in str1}
    digits2 = {digit: str2.count(digit) for digit in str2}
    return digits1 == digits2

Improving the algorithm

We generate a set of primes and iterate over it with nested loops. A faster way would be to be able to group primes which correspond to the same permutation.

An efficient way to do it would be to use a dictionnary mapping a hashable value to the list of primes being permutations of each other. That value should be chosen to be some kind of signature which would be the same if and only if values are permutations. For instance, we could use the string representation of prime p sorted alphabetically: ''.join(sorted(str(p))).

Once they are grouped, we can easily get the different permutations:

def get_permutations(n):
    """generates tuples of 3 permutations each within range n."""
    permut_primes = dict()
    for p in sieve(n):
        permut_primes.setdefault(''.join(sorted(str(p))), []).append(p)
    for perms in permut_primes.values():
        for a, b, c in itertools.combinations(perms, 3):
            assert c > b > a
            yield a, b, c

This also needs a minor change in check_substraction to ensure we do not find the already provided result:

def check_subtraction(n):
    """checks permutations within range n for subtraction rules.
    returns valid permutations."""
    permutations = get_permutations(n)
    for x, y, z in permutations:
        if abs(x - y) == abs(y - z) and x != 1487:
            return x, y, z

The corresponding code is more than 500 times faster than the original code.


I think the main problem of your implementation is that lock() performs Busy waiting. This will cause a thread that is waiting to get the lock to repeatedly waste CPU-cycles by polling (multiple times in one time slot) whether the lock has been released.

Easiest fix for that is to perform a call to Thread.yield() after trying to acquire the lock. This will cause the thread to exit its time slot and therefore let the other threads do their work.

public void lock() {
    while (true) {
        if (locked.compareAndSet(false, true)) {
            threadLocal.set(true);
            return;
        }
        Thread.yield();
    }
}

Oh and I would rename the method unLock() to unlock() since it is an existing english word.


Party Invitation - Trimming the Invitation List

for loop

You're right.  Not much point in checking the boundary condition twice.

        // right now, it is doing 1 more calculation than necessary
        // before exiting the for loop
        int indexToRemove = 0;

        for (int i = 0; indexToRemove < friendList.size(); i++) {
            // what I'm trying to say is that if the index you're
            // cutting is longer than the friendList, then exit the for
            // loop
            // but the indexToRemove here is from the last iteration, so
            // it doesn't work
            indexToRemove = ((roundNumber[h] - 1) + (i * (roundNumber[h] - 1)));
            System.out.println("Removing index: " + indexToRemove);
            if (indexToRemove < friendList.size()) {
                friendList.remove(indexToRemove);
            }
            System.out.println(friendList);

        }

You need to update indexToRemove at the end of the loop, not the beginning.

        int indexToRemove = roundNumber[h] - 1;

        for (int i = 1; indexToRemove < friendList.size(); i++) {
            System.out.println("Removing index: " + indexToRemove);
            friendList.remove(indexToRemove);
            System.out.println(friendList);
            indexToRemove = ((roundNumber[h] - 1) + (i * (roundNumber[h] - 1)));
        }

Perhaps this would be clearer as a while loop:

        int indexToRemove = roundNumber[h] - 1;
        int i = 1;

        while ( indexToRemove < friendList.size() ) {
            System.out.println("Removing index: " + indexToRemove);
            friendList.remove(indexToRemove);
            System.out.println(friendList);

            indexToRemove = ((roundNumber[h] - 1) + (i * (roundNumber[h] - 1)));
            i++;
        }

Remember that you can always write a for loop as a while loop.  It's just syntactic sugar.  Or vice versa:

        for (int indexToRemove = roundNumber[h] - 1, i = 1; indexToRemove < friendList.size(); i++, indexToRemove = ((roundNumber[h] - 1) + (i * (roundNumber[h] - 1))) ) {
            System.out.println("Removing index: " + indexToRemove);
            friendList.remove(indexToRemove);
            System.out.println(friendList);
        }

Although that's a bit long and complicated for a single line.  Note that we can rewrite the first line as

        for (int indexToRemove = roundNumber[h] - 1, i = 1; indexToRemove < friendList.size(); i++, indexToRemove = (i + 1) * (roundNumber[h] - 1) ) {

That's a bit better, but we can still do better:

        for (int indexToRemove = roundNumber[h] - 1; indexToRemove < friendList.size(); indexToRemove += roundNumber[h] - 1 ) {

That seems more like a for loop.  We've done away with i altogether and only work with indexToRemove.


Is my approach not a Brute force?

Nope, you've implemented dynamic programming

n = []
for i in range(100):
    n.append(map(int,raw_input().split()))
newresult = [int(59)]

I'm not clear why you pass 59 to int, it doesn't do anything.
    n.pop(0)

why didn't you do newresult = n.pop() instead of recreating the first row in the code?

for i in range(99):
    x = n.pop(0)
    result = list(newresult)

This makes a copy of newresult, which is pointless here since you don't keep the original around anyways

    newresult =[]
    t = len(x)
    for j in range(t):

        if(j==0):

You don't need the parens

            newresult.append(result[0]+x.pop(0))

I think the code is a bit clearer if you don't use x.pop just calculate the appropriate indexes

        elif(j==t-1):
            newresult.append(result[0]+x.pop(0))
        else:
            newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0)))

Figuring out the logic of what happens with all this popping is tricky. Again, I think calculating the index will be more straightforward. Also it'll probably be faster since popping the first element of a list is expensive.

print max(newresult)

A brute force solution would iterate over every possible path down the triangle. You are iterating over every possible position in the triangle which is much much smaller.

EDIT

The dynamic programming solutions starts with a recursive definition of the solution:

cost(i) = number(i) + max( cost(j) for j in predeccesors(i) )

Where i, j corresponds to positions on the triangle, and predecessors(i) is the set of all positions which can move onto i.

The top-down approach works by using memoization, remembering a value of cost(j) after it has been calculated. When cost(j) is needed again, it is simply reused.

However, you can also use the bottom-up approach to dynamic programming. In this case, you calculate the values of cost(i) starting from the first cells and work your way forward. Ever cost(i) only depends on the costs of cells before the current cell, and since those have already been calculated they can be reused without even using memoization.

If you look at your code, you'll find that the innermost loop is calculating the same formula as above. Furthermore, you'll find that it is calculating the cost of reach each cell starting from the cells at the top of the triangle and moving its way down. That's why I characterize it as dynamic programming.

I think you don't see this as DP, because you really didn't follow any DP logic in coming up with the solution. I think you are viewing it in terms of repeatedly reducing the complexity of the problem by eliminating the top row. In the end you are doing the same calculations as the DP version although you came at it from a different angle.

  I think dp uses the same solution again and again, wheras there is
  no need of such memorization here

All that's necessary for DP is to reuse solutions more than once. In this case, every number you calculate gets used in two places (one for the right, one for the left)


As a recommendation for readability i suggest you replace

if len(tempList) > 0:

with

if tempList:

as the Empty List resolves to False.

It's also recommended to use the "with statement" when dealing with files to avoid errors.

with open('file') as f:
   ...

This will free any locks on the filesystem once this block is exited.


There is no native way to do this so your general logic seems sound.  Here's some improvements, you might consider:

Make sure the pushMax function is not enumerable so people who iterate arrays with for (var index in array) won't see the pushMax property.
Ensure the array stays below max length even if it was previously above max
Return the new length of the array, the same as .push():

Here's a working snippet:

Object.defineProperty(Array.prototype, "pushMax", {
    configurable: false,
    enumerable: false,
    writable: false,
    value: function(value, max) {
        if (this.length >= max) {
           this.splice(0, this.length - max + 1);
      }
      return this.push(value);
    }
});

var x = [0,1,2,3,4,5,6,7,8,9,10];
x.pushMax(11, 10);
x.pushMax(12, 10);
x.pushMax(13, 10);

// wrong way to iterate an array, but just testing enumerability
for (var i in x) {
    document.write(i + ": " +  x[i] + "<br>");
}

You could also consider making the max length be a non-enumerable property of the array so you don't have to pass it to .pushMax() every time.

I'd really rather see this in a subclass of an Array rather than modifying the built-in Array object, but alas we can't subclass the Array object yet in most browsers.


Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds

Imports

Use import java.util.Timer; and import java.util.TimerTask; at the top of the file.  This will allow you to simplify this:

new java.util.Timer().schedule(new java.util.TimerTask() {

to this:

new Timer().schedule(new TimerTask() {

which requires less typing and less reading, and so is arguably easier to understand.

Naming

command is a decent name for a Command argument; n is a terrible name for an int.  Is that the count of the number of command objects you want submitted?  You have to consult the documentation for Timer#schedule() to discover that it is the number of milliseconds to wait before executing the command.

milliseconds, or delay_ms would be better names.

Similarly, solution() is a terrible name.  Solution to what?  schedule_command() might be a better choice.

Reuse existing interfaces

The difference between interface Command and interface Runnable is that the former uses execute() where as the latter uses run().  Oh, and the latter also adds the marker @FunctionalInterface.

By creating your own Command interface, you would force anyone who wants to use your scheduler, who already has classes that implement the standard Runnable interface, to add another interface to their class and forward the execute() method to the run() method (or vis versa).

Timers and Threads

Every Command passed to solution() will cause the creation of a new Timer() object, with its own timer thread.  Each Timer object can schedule multiple tasks.  Additionally, all tasks owned by a Timer execute sequentially in the same thread, reducing concurrency issues.  Consider:

for (int i=0; i<3; i++) {
    solution( () -> { System.out.print("Hello from command #");
                      Thread.sleep(1);
                      System.out.print(i);
                      Thread.sleep(1);
                      System.out.println("!"); }, 1000 );
}

When executed, the output might become:

  Hello from command #Hello from command #0Hello from command #!
  12!
  !

If your scheduler used a single, common Timer object ...

private static Timer timer = new Timer();

public static void solution(Command command, int n) {
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            command.execute();
        }
    }, n);
}

Then you would be guaranteed this output instead:

  Hello from command #0!
  Hello from command #1!
  Hello from command #2!

even though each Command was scheduled to run at the same time.

Program Termination

From the Timer documentation:

  After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.

If you want your program to terminate quickly, you need to call .cancel() on all Timer objects you create, once the last scheduled task has completed (or at least been started).  This could be done by scheduling a task to cancel the task timer:

timer.schedule( () -> timer.cancel() );

Job Control

You can .cancel() a TimerTask before it has begun executing.  However, nothing is returned from schedule(), so the caller cannot cancel any submitted tasks.

Better Implementation

Again, from the Timer documentation:

  Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor ...

private static ScheduledExecutorService executor;

public static void main(String args[]) {
    executor = Executors.newSingleThreadScheduledExecutor();

    ScheduledFuture<?> future = solution( () -> System.out.println("Hello World"), 1000);

    // Use future here, if desired.

    // Cleanup
    executor.shutdown();
    executor = null;
}

public static ScheduledFuture<?> solution(Runnable command, int delay_ms) {
    return executor.schedule( command, delay_ms, TimeUnit.MILLISECONDS );
}


Multiple PEP8 Style Violations

There's a bunch of style violations here, and it really irks me.  You are also violating fundamental parts of Python syntax with some of these things, especially with indentation, so you should try and correct style issues as well as my other concerns/suggestions.  I try not harping on style, but there's enough issues here that it irks me enough to put this first.

import statements must be at the beginning of the file.
Function definitions need to be padded by two line breaks.  That is, from the end fo one function to the start of the next, you need two blank lines between them (except inside a Class definition, which you don't have here).
Function names should be all lowercase, and multiple-word names for functions should be lowercase and separated with underscores (getGuessedWord should be get_guessed_word, etc.)
Variable names should be all lowercase, not CamelCase.  (The exception are module-wide constants, which should be in all CAPS.).  Multi-word variable names (such as lettersGuessed) should be lowercase and separated with underscores (letters_guessed)
Docstrings should be triple-quoted, not triple-apostrophe'd.  (""", not ''')
You have indentation problems that make your code error out in certain cases under hangman where you will have unexpected indentation. (note that I suppress these when testing code here for review, but it's a critical issue).  Use 100% consistent indentation - this should be 4 spaces per indentation level, not tabs, and you should not have some lines indented where they are not supposed to be.

User input can be condensed to one line

You currently use this for getting user input:

user_input = input('Please guess a letter: ')
user_input = str(user_input)
user_input = user_input.lower()

This can be condensed into one line, and we can also trim off the line break at the end too (so later recommendations for validation work without much issue):

user_input = input('Please guess a letter: ').lower().strip('\r\n')

No checking for valid inputs

You are expecting only letters to be provided, correct?  That's the basis of Hangman.

We should probably test to see if we're actually getting letters provided to us, and make a warning.  So, let's do this right after the user enters input:

user_input = input('Please guess a letter: ')).lower().strip('\r\n')
while user_input not in string.ascii_lowercase:
    print("You have not provided a letter, please only use letters!")
    user_input = input('Please guess a letter: ').lower().strip('\r\n')

Output messages: Code repetition

You've got this in here three times:

print('-----------')

You can instead use only one of these, and place it after the if/else block, and thereby not have to repeat this three times in a row inside the if block (note that I've snipped out all other contents of the if/else block, to shorten this post slightly).

if user_input not in letters_guessed:
    ....
else:
    ....

print('-----------')

Use augmented assignment statements.

This is currently in your code in getGuessedWord:

if letter in letters_guessed:
    word_guessed = word_guessed + letter
else:
    word_guessed = word_guessed + '_ '

Two things here: both of these can be condensed using augmented assignment statements, and you may wish to just use underscores without extra spaces between characters in the word, because it looks messy when I have some letters guessed and others not guessed (inconsistent spacing in output):

if letter in letters_guessed:
    word_guessed += letter
else:
    word_guessed += '_'

Use if __name__ == "__main__": to define what to execute when script is called from command line

python3 hangman.py will call hangman("stackoverflow"), but this is not really a good way to achieve it.

We should primarily define something like this at the end of the program to make sure that what runs is what we want to run when this is executed at the command line:

if __name__ == "__main__":
    hangman('stackoverflow')

Note though that you are always going to have "stackoverflow" as the string; you should strongly consider providing a file with valid words for usage, and then random selection therein rather than using a static string as an assignment.

  This has an added benefit of 'guarding' the call to hangman() (which is the replacement for a call to main() as some would have) if, for some reason, I was importing parts of the module and importing into another one.  This is more or less, also, a personal preference to guard whether I plan on importing or not, it's something I do regardless, just to protect calls to 'start' the program/script.

Unnecessary creation of variables

In get_available_letters, you do this:

fullstring = string.ascii_lowercase
....
for letter in fullstring:

Why do we create fullstring here?  It's not needed - we can just use this instead and not have to create the fullstring variable:

for letter in string.ascii_lowercase:


All the methods in InvokeRequest are basically the same. The only part that differs is the URL. Just pass that in instead of passing in the parts of the URL and constructing the URL in the function.

Before I show the function that I came up with though, I'll note that there's no reason InvokeRequest should be a class, and there's also no reason that self.URL and self.response in those methods should be instance attributes. I'm far from practiced in OOP, but making arbitrary bits of code into classes isn't helpful. If you were passing the self.server data into the constructor, then maybe there would be some justification. As it stands now though, I'm going to get rid of the class and instance attributes.

To start out with, here's the basic part that was repeated in all the methods:

def get_response(url):
    response = requests.get(url, auth=(username, PAT), verify=False)
    return response.json()

It now expects that the url will be passed in like I mentioned. You can ease making the URL though using a helper:

def build_url(*parts):
    return BASE_URL + "".join(parts)

If you haven't encountered var-args before, *parts just means that the function accepts as many arguments as you want, and bundles them into a tuple.

Now you can write:

json = get_response(build_url(project, "/_apis/git/repositories"))  # Was getRepositories
json = get_response(build_url(releaseID, "/_apis/git/releaseID"))  # Was getReleaseDefinitions
json = get_response(build_url(project, "/_apis/build/definitions/", str(ID)))  # Was getBuildDefinitionID

You could also put the call to build_url inside get_response and have *parts as the parameter to get_response:

def get_response(*parts):
    url = build_url(*parts)
    response = requests.get(url, auth=(username, PAT), verify=False)
    return response.json()

json = get_response(project, "/_apis/git/repositories")
json = get_response(releaseID, "/_apis/git/releaseID")
json = get_response(project, "/_apis/build/definitions/", str(ID))

Which you want to use depends on if get_response will always use a URL returned by build_url, or if it can differ.

You could wrap the calls to get_response in some functions too to avoid needing to manually put the URL together each time:

def get_build_definition_ID():
    return get_response(project, "/_apis/build/definitions/", str(ID))

Also note the naming convention I used. Python uses snake_case, not camelCase.


I'm not at all sold on TRANSFORM being part of your enum. The API for this enum lets you make nonsense calls like WORLD.from(WORLD).to(TRANSFORM). Always try to prevent invalid use of your APIs. I'm not really sure why you wouldn't use a naive approach like two static methods Transformer.worldToScreen(Vector2) and Transformer.screenToWorld(Vector2). Are you anticipating needing additional conversions later?

If you're really hankering for a fluent API for some reason, you could do Transform.value(Vector2D).from(Sizes).to(Sizes). You can control the return types to prevent at least some of the possible errors, but there are still some invalid calls like Transform.value(...).from(WORLD).to(WORLD).

**** EDIT ****

Since you're interested in the fluent approach, here's something to get you started. Obviously it needs documentation and input checking. The DisplayType enum can either belong to Transform or it can be top-level, depending on your needs. Likewise, the two inner classes can easily be split out.

As far as not instantiating objects, you can't really do a fluent API correctly without new objects. Do you have a real, demonstrated performance issue with creating new objects? Many people wrongly assume that object creation and garbage collection will be a big issue without testing.

If you really need to do this without new object instances, then your only good option as I see it is static methods. Your Sizes enum is too easy to use incorrectly.

public final class Transform {

    public static enum DisplayType {
        SCREEN(new Vector2(800f, 480f)),
        WORLD(new Vector2(25.806f, 15.48f));

        private final Vector2 size;

        private DisplayType(final Vector2 size) {
            this.size = size;
        }
    }

    private Transform() {
        super();
    }

    public static From value(final Vector2 value) {
        return new From(value);
    }

    public static final class From {

        private final Vector2 value;

        From(final Vector2 value) {
            this.value = value;
        }

        public To from(final DisplayType sourceDisplayType) {
            return new To(this.value, sourceDisplayType);
        }
    }

    public static final class To {

        private final Vector2 value;
        private final DisplayType from;

        To(final Vector2 value, final DisplayType from) {
            this.value = value;
            this.from = from;
        }

        public Vector2 to(final DisplayType targetDisplayType) {
            /* TODO: Do math here */
            throw new UnsupportedOperationException();
        }
    }
}


Simple trie implementation in JavaScript

Well, first of all, my optimization is an overhaul of your method. The concept is still tries. But I went for the JS route for several reasons:

We're in JavaScript. Linked lists in C would be like Arrays/Objects in JS. Since we have them available, why not use them instead?
In tries, you use a key for each entry. You'd have to loop over and find it when using linked lists or arrays. In JS, we have objects that are key-value pairs, which make it a bit easier to implement.
Performance is a bit better, except on Opera browsers. Performance may be due to the lesser loops and property access.
The code is shorter

The structure:

{
  "t": {
    "key": "t",
    "r": {
      "key": "r",
      "u": {
        "key": "u",
        "e": {
          "key": "e",
          "value": "yes",
          "name": "true"
        },
        "c": {
          "key": "c",
          "k": {
            "key": "k",
            "value": "vehicle",
            "name": "truck"
          }
        }
      },
      "o": {
        "key": "o",
        "w": {
          "key": "w",
          "e": {
            "key": "e",
            "l": {
              "key": "l",
              "value": "dig",
              "name": "trowel"
            }
          }
        }
      }
    }
  },
  "h": {
    "key": "h",
    "a": {
      "key": "a",
      "t": {
        "key": "t",
        "value": "head",
        "name": "hat"
      },
      "l": {
        "key": "l",
        "t": {
          "key": "t",
          "value": "hold it",
          "name": "halt"
        }
      },
      "m": {
        "key": "m",
        "value": "pig",
        "name": "ham",
        "m": {
          "key": "m",
          "e": {
            "key": "e",
            "r": {
              "key": "r",
              "value": "nail",
              "name": "hammer"
            }
          }
        }
      }
    }
  }
}

As for the code that operates this, notes are on the comments:

function Trie(key) {
  this.key = key;
  this.value;
  //children are merged with this object since collision is minimal
}

Trie.prototype.put = function (name, value) {

  var node = this,
    nameLength = name.length,
    i = 0,
    currentLetter;

  //the only major change is this single loop which zips through the collection
  //if the node exists, make it current and proceed
  //if not, we create it, make it current and proceed
  for (i = 0; i < nameLength; i++) {
    currentLetter = name[i];
    node = node[currentLetter] || (node[currentLetter] = new Trie(currentLetter));
  }

  node.value = value;
  node.name = name;

};

Trie.prototype.get = function (name) {

  var node = this,
    nameLength = name.length,
    i, node;

  //same idea, zip through the collection
  //in this case we break if we hit a dead end
  for (i = 0; i < nameLength; i++) {
    if (!(node = node[name[i]])) break;
  }

  //only when the loop went over all letters will we find a value
  //if not, well, we don't find anything
  return (i === nameLength) ? node.value : 'not found';
};


Let's compare your version to the % 15 version:

public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            if (i % 15 == 0) {
                System.out.println("FizzBuzz")
            } else if (i % 3 == 0) {
                System.out.println("Fizz");
            } else if (i % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(String.valueOf(i));
            }
        }
    }
}

The % 15 version is simpler and easier to read. This version neatly delineates the problem into the 4 different cases, and handles each case. In contrast, your version introduces a boolean logic flag (which I consider to be a significant anti-pattern) and a not entirely intuitive dependence on the order of the if statements.


C# API Wrapper with Static Function Calls

public static void Initialize(string key,string url)
    {
        APIClient.url = url;
        APIClient.apiKey = key;
    }

This is a dead give away that this class shouldn't be a bunch of static methods. I have to call this initialize method before using it or it'll blow up with null reference exceptions.

Worse, let's say I parallelize the main process and have multiple processes using this class. What happens when one of processes changes the uri? That's right, now all the processes are hitting that other uri. You'll get results, they'll just be the wrong one.

Thankfully, it's a simple fix. Just turn your Initialize method into a constructor and remove all instances of the static keyword.

public class APIClient
{
    private readonly string url;
    private readonly string apiKey;

    public APIClient(string key,string url)
    {
        this.url = url;
        this.apiKey = key;
    }


It seems like you could do this:

var results =
    (from d in ctx.Dramas
     where !d.Resolved
     group d by new { d.Student, DateHappened = d.DateHappened.ToString("ddMMyy") } into g
     select new
     {
         Student = g.Key.Student,
         DateHappened = g.Key.DateHappened,
         EquipmentDrama = g.Any(d => d.DramaType == DramaType.Equipment),
         HomeworkDrama = o.Any(d => d.DramaType == DramaType.Homework),
         IsFlagged = o.Any(d => d.DramaType == DramaType.Flagged),
         Dramas = g.Select(d => new
             {
                 d.Id,
                 TeacherName = d.Teacher.FirstName + " " + d.Teacher.LastName,
                 d.DateForDetention
             })
     });

NOTE: as far as I can tell, there's nothing limiting Teacher (or DateForDetention) to be the same in all grouped dramas; each drama could have a different Teacher. Here's an alternative that includes the teacher in the grouping:

var results =
    (from d in ctx.Dramas
     where !d.Resolved
     group d by new { d.Student, d.Teacher, DateHappened = d.DateHappened.ToString("ddMMyy") } into g
     select new
     {
         Student = g.Key.Student,
         DateHappened = g.Key.DateHappened,
         EquipmentDrama = g.Any(d => d.DramaType == DramaType.Equipment),
         HomeworkDrama = o.Any(d => d.DramaType == DramaType.Homework),
         IsFlagged = o.Any(d => d.DramaType == DramaType.Flagged),
         TeacherName = d.Key.Teacher.FirstName + " " + d.Key.Teacher.LastName,
         Dramas = g.Select(d => new
             {
                 d.Id,
                 d.DateForDetention
             })
     });

Of course, you could do the same for DateForDentention if you wanted.


Most of the following can be summed up as the ol' Rails rule-of-thumb: Skinny controller, fat model

1. Move logic to the model, and make it automatic

If you're doing this:

@payment.kind = @payment.determine_kind

it means that the logic should move to the model itself. If the model's doing the logic already and the result is saved to the very same model, why involve the controller at all?

Instead, you should do this:

class Payment < ActiveRecord::Base
  before_create :set_kind # determine and set the :kind attribute
  # ...

  private

  def set_kind
    self.kind = ... code ...
  end
end

However, there may be an even cleaner solution. As far as I can tell, determine_kind probably relies solely on information already in the payment record.

If that's the case, there may not be a reason to have a kind attribute/column at all. Just add a kind method to the Payment model:

class Payment < ActiveRecord::Base
  # ...
  def kind
    # same code as `determine_kind`
  end
  # ...
end

Now you can say some_payment.kind and get the kind without storing it in the database at all.

Note: this won't work if kind must be "kind as determined at the time of creation" or if you're doing database queries that involve the kind column. If either of those is the case, you can still use the before_create approach above.

2. Add calculate_cost to the collection

Here's what I'd do:

First, I'd move COURSE_COST to a COST constant on the Course model (accessible as Course::COST). That seems the most logical place to keep it. It'd probably be smart to also move EXCHANGE_RATE to Payment::EXCHANGE_RATE while you're at it.
Oh, and "exchange rate" is a little ambiguous: It's the rate from what to what? Pesos to USD? Or the other way around? Would be good to make the name more descriptive.

Then, assuming "user has_many subscriptions", you can first of all do this:

@unpaid_subs = current_user.subscriptions.unpaid.includes(:course)

but it also means that you can define modules that should be added to the collection. In your case, you make a module like so:

# in app/modules/subscription_collection.rb
module SubscriptionCollection
  def cost
    pesos = count * Course::COST
    usd   = pesos / Payment::EXCHANGE_RATE
    (usd * 100).round
  end
end

(I skipped the BigDecimal stuff because I didn't think it necessary, but as covered in the comments, it might be. I'll leave the code as is, though. BigDecimal or not, the procedure's the same.)

And then include that module in the relation declaration

class User < ActiveRecord::Base
  has_many :subscriptions, :extend => SubscriptionCollection
  # ...
end

Now, whenever you get a collection of subscriptions via a user model you can simply call cost on the collection itself, and get the total cost.

Now you should be able to say:

def create
  @unpaid_subs = current_user.subscriptions.unpaid.includes(:course)
  @payment = current_user.payments.new(params[:payment])

  @payment.amount = @unpaid_subs.cost

  if @payment.save_with_payment
    redirect_to dashboard_url, :notice => "Thank you for Paying!"
  else
    render :action => 'new'
  end
end

Last little thing: This is just me, but the name save_with_payment is a little iffy, since the model's already called payment. So, "save payment with payment" seems semantically messy. I'd suggest something like charge_and_save instead. You might also want to raise an exception if someone tries to call the method on an already-charged payment. You don't want to accidentally charge people multiple times!


Looks pretty good over all, but I have a few suggestions.

Don't call threeNOneValueFor twice when you could store it in a variable instead (or you can use Math.max). There's a chance that the compiler will optimize that, but that's a risky thing to assume.

The do-while seems a bit odd and unintuitive. I would go with a for loop instead.

int maxCycleLength = 0;
for (; inputOne <= inputTwo; ++inputOne) {
    maxCycleLength = Math.max(threeNOneValueFor(inputOne), maxCycleLength);
}
return maxCycleLength;

inputOne and inputTwo are pretty bad names. If you didn't already know what they were, the names would really mean much to you. Something like minimumValue, rangeBegin, etc might be better.

inputNumber is a pretty meh name as well. Considering the problem domain, I'd probably just call it n since that has a well defined meaning in this context and inputNumber could mean pretty much anything (it's an int parameter -- of course it's an input number).

I would call solveFor maximumCycleLength. solveFor has the same problem as inputNumber. You could be solving for pretty much anything that takes two inputs.

public int maximumCycleLength(int minN, int maxN) {

Seems significantly clearer as to what the method does. Couple that with a javadoc and it becomes very well explained:

/**
 * Calculate the maximum cycle length for the {@code 3n + 1} sequence over every {@code n} such that
 * {@code minN <= n <= maxN}. Note that {@code maxN} must be greater than or equal to {@code minN}.
 * @param minN The beginning (inclusive) of the range over which to find the maximum cycle length.
 * @param maxN The end (inclusive) of the range over which to find the maximum cycle length.
 * @return The maximum cycle length of the {@code 3n + 1} sequence for all {@code n} in the provided range.
*/
public int maximumCycleLength(int minN, int maxN) {

(I would probably omit the @param and @return parts if I were to write this javadoc for my own code, but people tend to vehemently disagree with that.)

I'm probably getting pretty annoying at this point, but I don't much like the name threeNOneValueFor either. It doesn't find the valueFor; it finds the cycle length.

public int threeNOneCycleLength(int n) {

Considering it's on a class that already mentions the 3n + 1 problem, I would probably name it just cycleLength.

In it's current form, I would probably make solveFor static. There's no state, so there's no real reason in having it be an object. Typically I lean far more towards non-static than static, since it's much better to regret something being non-static than it is to regret having made it static, but in this case, since it's pretty much a mathematic function, I doubt it's ever going to manipulate state (hopefully not anyway).

In fact, I'd probably take this a step farther and have threeNOneCycleLength be public. It could be useful on it's own, and since both methods are static utility-like methods, there's not too much concern about having the class do too many things.

All in all (woo boring Saturday afternoons!), I might do something like this:

/**
 * Provides methods related to the {@code 3n + 1} sequence.
 *
 * @see Collatz conjecture.
*/
public class ThreeNPlusOne {

    /**
     * Calculate the maximum cycle length for the {@code 3n + 1} sequence over every {@code n} such that
     * {@code minN <= n <= maxN}. Note that {@code maxN} must be greater than or equal to {@code minN}.
     *
     * @param minN The beginning (inclusive) of the range over which to find the maximum cycle length.
     * @param maxN The end (inclusive) of the range over which to find the maximum cycle length.
     * @return The maximum cycle length of the {@code 3n + 1} sequence for all {@code n} in the provided range.
    */
    public static int maximumCycleLength(int minN, int maxN) {
        int maxCycleLength = 0;
        for (; minN <= maxN; ++minN) {
            maxCycleLength = Math.max(maxCycleLength, cycleLength(minN));
        }
        return maxCycleLength;
    }

    /**
     * Calculates the cycle length for the provided {@code n}.
     *
     * @param n The value of {@code n} for which the
     * @return The cycle length for the provided {@code n}.
    */
    public static int cycleLength(int n) {
        int cycles = 1;
        while (n != 1) {
            n = (n % 2 == 0) ? n / 2 : 3*n + 1;
            cycles += 1;
        }
        return cycles;
    }

}

I'm not very happy with some of my namings (is "Collatz sequence" a recognized thing? I don't know what to call all of this), and some of the javadocs could use some better wording and whatnot, but hopefully this shows the structure and approach well enough.


You can do it in 2 way.

The first is by implementing the interface on your main class, so you don't have to create an anonymous class on the fly but just pass your this.

UPDATE

Here is an example on how to do it:

public class MyActivity extends AppCompatActivity
                        implements Preference.OnPreferenceClickListener {

        // You implement the listener method in your main
        // class, so you just pass the current this object
        @Override
        public boolean onPreferenceClick(Preference preference) {
           SongLoader.generateXml(this);
           return true;
        }

        // ... other code

       // when you record the listener your main class is the
       // listener now.
       rebuildDB.setOnPreferenceClickListener(this);

}

The second is by creating a specific class that implement the interface.

This class is going to take in the constructor a parameter that is an instance of your main class.

So you will pass a new instance of this class instead of an instance of an anonymous class.

Here is an example of what I mean.

private static class MyOnPreferenceClickListener implements Preference.OnPreferenceClickListener {

    MyActivity myActivity;

    public MyOnPreferenceClickListener(MyActivity myActivity) {
        this.myActivity = myActivity;
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        SongLoader.generateXml(myActivity);
        return true;
    }
}

I defined private and static considering to declare this class inside your main class.

UPDATE

The fist method is the quick and fast way, not considering the anonymous listener class, but could drive on very fat classes implementing many different listeners, depends on the Activity you're writing.

The second method, helps to decouple the listeners from your business code, and organize it in a better way.


My implementation of lexicographic permutation in F# is 3x slower than C#

You're not comparing apples to apples. The F# code is generic whereas the C# only works with int arrays. Remove every occurrence of inline and add a type annotation to toNextLexicographic:

let toNextLexicographic (myArray: int[])

In my tests, that takes the time from 2.152 to 0.146 seconds.

The reason for the poor performance is inline isn't working. You can see this by decompiling. Most of the time is spent in LanguagePrimitives.HashCompare.GenericGreaterThanIntrinsic as a result. This is much more expensive than op_GreaterThan.

I'm not sure under what conditions inline is ignored, but I can only guess, in this case, it's due to the complexity of your code and the closures.


Your code seems really good, I would change the ITestingRepository methods to return IEnumerable<> instead of List<>.

Also, I suggest you would add a method signature to your generic repository interface that would let you query your DbContext.

public interface IGenericRepository<T> where T : class
{
    T Get(int id);
    void Create(T entityToCreate);
    void Edit(T entityToEdit);
    void Delete(T entityToDelete);
    IEnumerable<T> Get(Expression<Func<T,bool>> whereClause)
}

Then you can use it this way

//Class example, I don't know what Testing class is
public class Testing
{
    public string PropertyOne { get; set;}
    public string PropertyTwo { get; set;}
}

public class TestingRepository
{
    //Method implementation
    public IEnumerable<Testing> Get(Expression<Func<Testing,bool>> whereClause)
    {
        IQueryable<Testing> result = _entities.Testing;

        if(whereClause != null)
            return result.Where(whereClause);

        return result.ToList();
    }
}

public static void AMethod() //Just to show an example at work!
{
    List<Testing> testings = new TestingRepository().Get(x => x.PropertyOne == "Hello" && x.PropertyTwo == "World").ToList();
}

Finally, you might want to implement a generic repository class that implements your interface (a public class GenericRepository<T> : IGenericRepository<T>, I won't write it down for you but you could check this http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in


Get information about the USB device from Win32_DiskDrive and Win32_LogicalDisk

1: Add() doesn't appear to access any class members, so it can be declared static. But then again, it looks like it wants to return the name, serial number, and free space. Make it do so - create a quick container type

public sealed class DriveInfo
{
    public DriveInfo(string name, string serialNumber, ulong freeSpace)
    {
        this.Name = name;
        this.SerialNumber = serialNumber;
        this.FreeSpace = freeSpace;
    }

    public string Name { get; }

    public string SerialNumber { get; }

    public ulong FreeSpace { get; }
}

usage becomes:

return new DriveInfo(
    (string)volume["Name"],
    (string)drive["SerialNumber"],
    (ulong)volume["FreeSpace"]);

2: The parameter letter is completely unused in the method and the comment is a lie. Remove the parameter and comment or use the parameter appropriately.

3: Invert your if blocks, to prevent so much indention as well as keeping the tests looking cleaner (equality vs. non-equality):

if (partition == null) continue;
...
if (logical == null) continue;

4: Both ManagementObject and ManagementObjectSearcher descend from Component, which implements IDisposable. Their lifetime should therefore be wrapped in a using statement:

using (var searcher = new ManagementObjectSearcher($"ASSOCIATORS OF {{Win32_DiskDrive.DeviceID='{drive["DeviceID"]}'}} WHERE AssocClass = Win32_DiskDriveToDiskPartition"))
using (var partition = searcher.First())
{
}

5: Your extension method's body can be replaced by a quick one-liner:

return searcher.Get().Cast<ManagementObject>().FirstOrDefault();


Why make it so complicated? Just use basic java 8 streaming operations and the new-ish BufferedReader.lines() method:

public static void main (String[] args) {
    Set<String> uniqueOrderedNames = new TreeSet<>();
    try(BufferedReader br = new BufferedReader(new InputStreamReader (System.in))){
        br.lines().forEach(uniqueOrderedNames::add);
    } catch (Exception e) {
        // don't do this, use the most specific exception type and handle it
    }
    System.out.println(uniqueOrderedNames.size());
    uniqueOrderedNames.forEach(System.out::println);
}

That much for your approach. Before you now copy paste that, I have some more things to say:

Indent correctly: Methods are indented by one level, blocks are indented 1 level. Levels add up. Your method is missing one level of indentation and your created Scanner should be indented 2 more spaces
Add spaces around binary operators: for(int i=0;i<n;i++){ becomes for (int i = 0; i < n; i++) {, which is significantly easier on the eyes.
Use clear names Set set is nonsensical, it doesn't shed any light whatsoever on what the thing does. Give it a proper name so you can understand what happens.


How about removing the loop at all like:

if (!index.HasValue)
{
     breaks.Clear();
}
else
{
     breaks.RemoveAt((int)index);
}

if you want/need to keep the loop, i would change your second way like:

foreach (Break b in breaks)
{
    if (!index.HasValue || index == count)
    {
        b.Remove();
    }
    count++;
}


The only weak point is that the implementation is not copy safe nor there exist mechanism for ensuring copy protection. I would hide its underlying type and return as sync.Locker, so it can't be mis-used:

type spinLock uint32

func (sl *spinLock) Lock() {
    for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
        runtime.Gosched() //without this it locks up on GOMAXPROCS > 1
    }
}

func (sl *spinLock) Unlock() {
    atomic.StoreUint32((*uint32)(sl), 0)
}

func SpinLock() sync.Locker {
    return &spinLock{}
}

An alternative I've seen in sync.Cond is to embed an auxiliary type for copy-protection, although it would complicate the implementation unnecessary.


Method on Laravel model to find courses related to a course

No, this code belongs in the Model (or a related repository if you where using such a design, though thats kind of overkill with Active Record).

You can however reduce the number of queries by using the foreach loop to build a single query, instead of making a query per word:

public function relatedCourses()
{
    $words = explode($this->name, " ");
    return Course::where(function($query) use ($words) {
        $query->where('id', '<>', $this->id);
        foreach ($words as $key => $word) {
            if($key==0){
                $query->where('name_es', 'LIKE', "%$word%")->orWhere('name_cat', 'LIKE', "%$word%");
            }else{
                $query->orWhere('name_es', 'LIKE', "%$word%")->orWhere('name_cat', 'LIKE', "%$word%");
            }
        }
    })->get();
}


I like the idea of your code but you defenitely have some bugs and convention issues that should be dealt with:

Major bug: call does not remove funcArr[name] after iterating them so if you add something to the "first" queue and call the first queue, adding something to the first queue will still have the functions from before you called the queue earlier. I created a (demo of the issue); as you see the alert will be shown twice as funcArr[name] is never emptied
You're storing keys (function names) in the array funcArr. funcArr should be a hash object rather than an array.
You're using for..in on an array (why this is bad) and moreover, the variable func will be global. Use a regular for loop instead here. I'd recommend using $.each here. With $.each you'd write the loop

$.each(funcArr, function(i, fn) {
    var dfd = $.Deferred();
    fn(dfd);
    promiseArr.push(dfd.promise());
});

You're module pattern seems off... 1) its common convention that a class name should be capitalized, ie MyQueue, 2) theres no real reason to use the this keyword if you're not planning to add these functions on prototype, 3) In this.start your line this.call(ord.pop()); is a bit confusing.
As you were not making use of prototype in your function I adapted your code to use the "module pattern". This allows your module to be created without the new keyword whereas before it would of caused major issues.

Here's how I would write your queue. I added comments on most of my cahnges

function myqueue(){
    var ord=[];
    var funcHash = {}; // Use a hash as you're using keys rather than indicies
    var me = $(document);//(minor)convention would be to name this $doc

    var plugin = {
        add: function (func, name) {
            if(!funcHash.hasOwnProperty(name)) {//name does not exist yet
                funcHash[name] = [];
                ord.unshift(name);
            }
            funcHash[name].push(func);//now just queue the function
        },

        call: function (name) {
            me.queue("deferQueue", function () {
                var promiseArr=[];
                var funcArr = funcHash[name];

                //funcArr is a hash of arrays don't use for in
                //also func was a global variable!]

                $.each(funcArr, function(i, fn) {
                     var dfd = new jQuery.Deferred();
                     fn(dfd);
                     promiseArr.push(dfd.promise());
                });

                //I assume you want to remove the functions after you call them so requeing the same name doesn't add to the old queue
                delete funcHash[name];

                $.when.apply($,promiseArr).then(function () {
                    console.log("Success "+name);
                    me.dequeue("deferQueue");
                }, function () {
                    console.log("Fail "+name);
                });
            });
        },

        start: function () {
            while(ord.length>0) {
                plugin.call(ord.pop());
            }
            me.dequeue("deferQueue");
        }
    };

    return plugin;
};

http://jsfiddle.net/g55PC/2/

As for the second question of having to do the .resolve() in the timeout, you may want to consider adding a helper to your myqueue module along the lines of

//helper function for automatically managing a delay using timeout
addDelayed: function(fn, name, delay) {
    this.add(function(dfd) {
        setTimeout(function () {
            fn(dfd);
            dfd.resolve();
        }, delay || 250);
    }, name);
}

So your old pattern code be reduced to just:

myPlugin.addDelayed(function (dfd) {
    $("#result").append("
1
");
}, "first", 1000);


Recording loans of access cards to people in a company

Inline comments should only be used sparingly, and definitely not on already long lines. Your #returns a list of objects is pretty unnecessary both because it's overly long, but also because it's inferrable and doesn't seem to matter. You only pass the loans on unchanged so the user doesn't care that they're a list of objects. You can infer that it's a collection of something because of the name loans and the len usage. And that's all you need to know in this function, so forget that comment.

You should also format your docstring so it contains just one line summarising the function, a blank line and then the further details. You just have one long block but it's hard to read from it what the function should do. Instead you detail the possible results.

Instead of using str and concatenation, just use str.format. It's a convenient way of formatting strings and coverting their type at the same time:

    successMsg = "Card {} has been marked as returned".format(value)

Also note that you haven't correctly inserted this value in the failureMsg of numLoans > 1. You just have the string literal " + str(value) + ". You'd need the extra quotation marks to do it your way:

    failureMsg = """
    More than one loan for """ + str(value) + """ exists. Please select
    the correct loan to return from the next screen.
    """

But instead I'd suggest using str.format again.


You could remove the first range by initialising maxNumber with math.MinInt(32|64) depending on the architecture. E.g. on 32-bit systems:

func max(numbers map[int]bool) (maxNumber int) {
    maxNumber = math.MinInt32
    for n := range numbers {
        if n > maxNumber {
            maxNumber = n
        }
    }
    return maxNumber
}

You can make it work with either system using build tags.


Your code is missing automatic tests.

One test case you definitely need is to ensure that PolyAdd and the related functions do not modify their arguments. As far as I can see by reading the code, the current version of PolyAdd modifies the bigger of its arguments, which is unexpected.

The reason that the argument is modified is that slices are essentially pointers, and when passing them as arguments, their content is not copied.

You should define a constructor function NewPoly(deg int) to hide all the implementation details. Using this constructor will also solve the aliasing problem mentioned above.

Regarding the long code for Str, you can merge some of the duplicate code:

    c := p.Coeffs[i]
    if c == 0 {
        continue;
    }

    if c > 0 {
        s += " + "
    } else {
        s += " - "
    }

    if (c != 1 && c != -1) || i == 0 {
        s += strconv.FormatFloat(c, 'g', -1, 64)
    }
    if i > 1 {
        s += "x^" + strconv.Itoa(i)
    } else if i == 1 {
        s += "x"
    }

By extracting the expression p.Coeffs[i] into a variable, the code gets a bit cleaner.

If you need to speed up Str, use a strings.Builder instead of the += operator.


DateTime internal representation to FILETIME

This function always returns 0, but you haven't stated why that's important for this use (if it's intended).  Since it doesn't also return 1 or another non-0 value for failure, I assume that it's not returning error codes.  Otherwise, it should return void, and the return 0 should then be removed.
Since this is also tagged with c++, I'll also provide the C++ equivalent of the constants given in @chux's answer:

constexpr unsigned long long FT_SECONDS_PER_DAY = 24ULL * 60 * 60;
constexpr unsigned long long FT_SECOND = 10000000ULL;

(constexpr has them evaluated at compile time.)

Or for brevity, they can use auto instead:

constexpr auto FT_SECONDS_PER_DAY = 24ULL * 60 * 60;
constexpr auto FT_SECOND = 10000000ULL;


Avoid magic numbers.

It is not immediately clear what 2 and 3 in find_next_match stand for (same for 3 and 4 in main). Even though the matrix is hardcoded, I recommend to infer its dimensions, rather then hardcode them also.
Avoid globals.

Passing std::string& line as an additional parameter to find_next_match is cleaner then reliance on the global, and obviates the (pretty strange)

    chars.clear();
    chars = line;

tuple vs custom class.

Using a tuple makes the code too verbose to my taste. I'd invest into a struct position with an operator+ overloaded to perform what

    make_tuple(get<0>(cur_pos) + get<0>(dir), get<1>(cur_pos) + get<1>(dir));

does.
Nitpicks.

You should test if infile is opened correctly.
Final print may use a ternary

    std::cout << (found? "True": "False") << '\n';

I don't want to start a holy war, but I'd return 0; from main.
Kudos for not using namespace std;


Finding the order of sorting of an array

The cleanest would be an enum and a switch (current) with three cases:

In each case you can then check if you stay in the current_order or if you
switch to another or if you can return 0/1/-1.

Simplified:

current=NONE;
for()
    a=... b= ..
    switch(current)
        case NONE: if (a>b) current=DEC; else if (a<b) current=INC; break;
        case INC:  if (a>b) return NONE; break;
        case DEC:  if (a<b) return NONE; break;
return current;

I don't know if it's the right term, but I think that is a finite state machine. You could read about those to get more information; it's always good to use for parsing stuff.

From the comments:

  What should be returned if the array is one element long?

Good point. I would introduce another return value MIXED:

current=NONE;
for()
    a=... b= ..
    switch(current)
        case NONE: if (a>b) current=DEC; else if (a<b) current=INC; break;
        case INC:  if (a>b) return MIXED; break;
        case DEC:  if (a<b) return MIXED; break;
return current;


Grouping

If you need to group anything using; groupby is probably the easiest way

Here we can use a itertools.groupby recipe to group the consecutive ranges:

>>> for _, g in groupby(enumerate(lst), lambda i_x : i_x[0] - i_x[1]):
...     print([x for _, x in g])
[-6]
[-3, -2, -1, 0, 1]
[3, 4, 5]
[7, 8, 9, 10, 11]
[14, 15]
[17, 18, 19, 20]

Yielding the correct representation

Now all is left is to check whether there are more then 2 items in the range, and return the range. Else return all the numbers in the range normally

We can make this a generator, which yields either the range or a number, and afterwards join them together.

Full Code

def group_consecutives(lst):
    for _, g in groupby(enumerate(lst), lambda i_x : i_x[0] - i_x[1]):
        r = [x for _, x in g]
        if len(r) > 2:
            yield f"{r[0]}-{r[-1]}"
        else:
            yield from map(str, r)

def range_extraction(lst):
    return ','.join(group_consecutives(lst))


Semantic of methods

The implementation or the signature of the method "int getCount(String term);" does not make sense. Either you delegate the parameter "term" to the search algorithm with a stateless implementation or you omit it and have a stateful implementation. In the last case your "term" should be given to the constructor. I prefer a stateless implementation and all further comments are related to that.

Programming using interfaces

You are not using the interface "WordSearch". The assigment

BruteForceSearch bSerch = new BruteForceSearch(file);

be to the abstraction:

WordSearch search = new BruteForceSearch(file);

Avoid passing working list references

The code

Set<File> list = new HashSet<File>();
search.getFiles(folder, list);

should be refactored to:

Set<File> list = search.getFiles(folder);

The "List" should be instantiated within the method "getFiles(...)".

Make directory recursion part of WordSearch through template pattern

Currently you are collecting all files recursively within the main-method. Make the algorithm part of the WordSearch objects. To do so, refactor the WordSearch-Interface to an abstract class and implement the directory recursion as a Template Method.

public abstract class WordSearch {

    ...

    public int getCount(String term) {
        File folder = ...;
        return getCountInFolder(folder);
    }

    /**
     * Template method pattern
     */
    protected abstract int getCountInFile(File file, String term);

    private int getCountInFolder(File folder, String term) {
        int count = 0;
        File[] files = folder.listFiles();
        for (int j = 0; j < files.length; j++) {
            if (files[j].isDirectory()) {
                count = count + getCountInFolder(files[j], term);
            } else {
                count = count + getCountInFile(files[j], term);
            }
        }
        return count;
    }

    ...

}

Introduce strategy pattern

Associate a WordSearch-Object within "Searcher" and delegate to it. This is called Strategy pattern.

public class Searcher {

    private WordSearch wordSearch;

    public Searcher(String dir, WordSearch wordSearch) {
        this.wordSearch = wordSearch;
        ...
    }

    public int getCount(String term) {
        return this.wordSearch.getCount(term);
    }

    public void setWordSearch(WordSearch wordSearch) {
        this.wordSearch = wordSearch;
    }

    ...

}

The WordSearch-Object may be set through the constructor and changed by a setter.


There is no point in having the constructor for Node require the 'next' node. It is never part of the constructor, in your code.
The default constructor is useless code here. You may as well remove it, it does nothing.
the method getCount should be called size to be conformant with other classes.
I prefer when people use just one signal for the system state. In your code, you use size == 0 in some places to determine if the queue is empty, and in other places you use front == null

Otherwise the code looks functional, and neat.


Dollar value of coins and calculating interest compounded annually

Choose the right types

You used double for the coin types, for example:

System.out.println("How many quarters do you have?");
double quarters = keyboard.nextDouble();
quarters = quarters * (0.25);

To the question "how many quarters ...",
it's logical to get an integer (whole number) as the answer, not a double.

I can guess that you choose the double type because you want to use the quarters variable for two different purposes:

Count the quarters
Count the dollar value of the quarters

These are conflicting meanings, and the right thing to do is to not mix them,
for example:

int quarters = keyboard.nextInt();
double dollarValueOfQuarters = quarters * .25;

The Single Responsibility Principle

The main is doing too much: it has too many responsibilities:

Calculate the dollar value of coins
Calculate the compound interest

It would be better to split the method into, and give them a name according to their main responsibility, for example:

private static void calculateDollarValueOfCoins(Scanner scanner, NumberFormat moneyFormat) { ... }

private static void calculateCompoundInterest(Scanner scanner, NumberFormat moneyFormat) { ... }

public static void main(String args[]) {
    Scanner scanner = new Scanner(System.in);
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();

    calculateDollarValueOfCoins(scanner, moneyFormat);
    calculateCompoundInterest(scanner, moneyFormat);
}

Now the responsibilities are clearly separated.
I also renamed some variables to better match their purposes:

scanner instead of keyboard, because you don't really "scan" things from a keyboard. A scanner is a more abstract concept than a keyboard: for all you care, the input values could come as radio signals from the moon, as long as it implements the Scanner's API, your method can work.
moneyFormat instead of priceFormat, which works for both responsibilities nicely: the dollar value of your coins is certainly not a "price", and the worth of your investment is not exactly a "price". They are both about money, and formatting money, so this more general name seems appropriate.

Modeling coins

It might be a good idea to model coins using an enum:

enum Coin {
    NICKLE(.05),
    DIME(.1),
    QUARTER(.25);

    private final double value;

    Coin(double value) {
        this.value = value;
    }
}

And to add a helper class for adding coins:

private static class CoinAdder {
    private double value = 0;

    CoinAdder addCoins(Coin coin, int number) {
        value += coin.value * number;
        return this;
    }

    public double getValue() {
        return value;
    }
}

This way, the calculateDollarValueOfCoins method I suggested above can be implemented in a somewhat more natural way,
and without embedding the dollar value of coins in it:

private static void calculateDollarValueOfCoins(Scanner scanner, NumberFormat moneyFormat) {
    System.out.println("How many quarters do you have?");
    int quarters = scanner.nextInt();

    System.out.println("How many dimes do you have?");
    int dimes = scanner.nextInt();

    System.out.println("How many nickles do you have?");
    int nickles = scanner.nextInt();

    double total = new CoinAdder()
            .addCoins(Coin.QUARTER, quarters)
            .addCoins(Coin.DIME, dimes)
            .addCoins(Coin.NICKLE, nickles)
            .getValue();
    System.out.println("You have: " + moneyFormat.format(total));
}

Now we have separated the responsibilities even further:
calculateDollarValueOfCoins doesn't know anymore the value of the different types of coins, and it doesn't know how to add them.
Those responsibilities are delegated to the Coin enum and the CoinAdder class,
which is a good thing.

Quick tips

Instead of this:

quarters = quarters * (0.25);

Better:

quarters *= 0.25;

You can write 0.25 as .25.

You can write 5. instead of (double) 5.

Suggested implementation

Putting the above suggestions together, something like this would be better:

class InterestCalculator {

    enum Coin {
        NICKLE(.05),
        DIME(.1),
        QUARTER(.25);

        private final double value;

        Coin(double value) {
            this.value = value;
        }
    }

    private static class CoinAdder {
        private double value = 0;

        CoinAdder addCoins(Coin coin, int number) {
            value += coin.value * number;
            return this;
        }

        public double getValue() {
            return value;
        }
    }

    private static void calculateDollarValueOfCoins(Scanner scanner, NumberFormat moneyFormat) {
        System.out.println("How many quarters do you have?");
        int quarters = scanner.nextInt();

        System.out.println("How many dimes do you have?");
        int dimes = scanner.nextInt();

        System.out.println("How many nickles do you have?");
        int nickles = scanner.nextInt();

        double total = new CoinAdder()
                .addCoins(Coin.QUARTER, quarters)
                .addCoins(Coin.DIME, dimes)
                .addCoins(Coin.NICKLE, nickles)
                .getValue();
        System.out.println("You have: " + moneyFormat.format(total));
    }

    private static void calculateCompoundInterest(Scanner scanner, NumberFormat moneyFormat) {
        System.out.println("What is the initial investment?");
        double investment = scanner.nextDouble();

        System.out.println("At what intrest rate is the intrest compounded annually?");
        double intrestRate = scanner.nextDouble();

        double futureValueFive = investment * Math.pow(1 + intrestRate, 5.);
        System.out.println("In five years the investment will be worth : " + moneyFormat.format(futureValueFive));

        double futureValueTen = investment * Math.pow(1 + intrestRate, 10.);
        System.out.println("In ten years the investment will be worth : " + moneyFormat.format(futureValueTen));

        double futureValueTwenty = investment * Math.pow(1 + intrestRate, 20.);
        System.out.println("In twenty years the investment will be worth : " + moneyFormat.format(futureValueTwenty));
    }

    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();

        calculateDollarValueOfCoins(scanner, moneyFormat);
        calculateCompoundInterest(scanner, moneyFormat);
    }
}


This can definitely be optimized. First, though, a few style points. Don't use #define N as Hosch250 says. Jamal points out to use std:array; this can make some later aspects nicer, too.

Sort your imports. Don't use using namespace std. I'm not sure why you imported cstdio or cstdlib... so don't. Space your operators, even <<. Use braces around all blocks.

This:

if (x == true)
if (x == false)

should be

if (x)
if (!x)

Be consistent with spacing (eg. don't add spacing inside brackets in only one place). Use const in printSolution.

Remove return 0 from main and the useless // Main comment. Similarly for the /* print solution */ comment. I'm personally not a fan of /* this comment style */ although I admit that's particularly subjective.

I'd rename printSolution to printBoard, since it doesn't require a solution.

Convert ints to bools where appropriate.

You should use ++i and --i over the postfix forms by convention.

Now the tiny things are out of the way, consider improving printSolution with range-based for loops:

void printSolution(const std::array<std::array<int, N>, N> &board)
{
    for (auto row : board)
    {
        for (auto val : row)
        {
            std::cout << val << "  ";
        }
        std::cout << std::endl;
    }
}

Consider giving a better description of isSafe and what it assumes:

// Check if a queen can be placed at (row, col)
// This assumes that there is exactly one queen in each column
// less than col and none in any other.

This can be simplified by compressing the array to a 1-dimensional array of integers, since we know that the positions are bounded to one-per-column. This speeds up isSafe, improving timings.

It looks like this:

#include <array>
#include <iostream>

const int N = 25;

void printBoard(const std::array<int, N> &board)
{
    for (int i = 0; i < board.size(); ++i)
    {
        for (auto val : board)
        {
            std::cout << (val == i) << "  ";
        }
        std::cout << std::endl;
    }
}

// Check if a queen can be placed at (row, col)
// This assumes that there is exactly one queen in each column
// less than col and none in any other.
bool isSafe(std::array<int, N> &board, int row, int col)
{
    for (int i = 1; i <= col; ++i)
    {
        if (board[col-i] == row)
        {
            return false;
        }

        // Up diagonal
        if (board[col-i] == row - i)
        {
            return false;
        }

        // Down diagonal
        if (board[col-i] == row + i)
        {
            return false;
        }
    }

    return true;
}

bool solveNQRecurse(std::array<int, N> &board, int col)
{
    if (col >= N)
    {
        return true;
    }
    for (int i = 0; i < N; ++i)
    {
        if (isSafe(board, i, col))
        {
            board[col] = i;
            if (solveNQRecurse(board, col + 1))
            {
                return true;
            }
        }
    }
    return false;
}

/* solves the N Queen problem using Backtracking.*/
bool solveNQ()
{
    std::array<int, N> board{};
    if (!solveNQRecurse(board, 0))
    {
        std::cout << "Solution does not exist" << std::endl;
        return false;
    }
    printBoard(board);
    return true;
}

int main()
{
    solveNQ();
}

The next thing to do is optimize isSafe by converting it to a bitset. Since it will be useful later, I will use an uint64_t instead of an std::bitset; this is fine since a 65x65 grid won't be quickly solvable anyway. The idea is expressed in the Java version of this question; you keep track of three masks of which diagonals and rows are free. You then shift these and combine them with &. This makes isSafe just

bool isSafe(uint64_t rowsFree, uint64_t upDiagFree, uint64_t downDiagFree, uint64_t col) {
    return (rowsFree & upDiagFree & downDiagFree) & (1ULL << col);
}

However, there's a special trick to just enumerate the set bits in a value, making this unneeded. I'll just convert the code from the Java version, since it's what I'd get to anyway.

This optimization takes it from a good 23 seconds for N=30 to to just 0.36; or a speed improvement of almost 100x. This gives

#include <array>
#include <bitset>
#include <iostream>

uint64_t const N = 30;

void printBoard(std::array<uint64_t, N> const &board)
{
    for (uint64_t i = 0; i < N; ++i)
    {
        for (auto val : board)
        {
            std::cout << (val == (1 << i) ? "♛" : "·") << " ";
        }
        std::cout << std::endl;
    }
}

// Use bit hackery to extract lowest bit from spaces,
// mutating both.
void splitLowestBit(uint64_t &bits, uint64_t &bit) {
    // Copy all of the bits
    bit = bits;

    // Remove the lowest bit from the original
    bits &= bits - 1ULL;

    // Remove the rest of the bits from the copy
    bit ^= bits;
}

bool solveNQRecurse(
    std::array<uint64_t, N> &board,
    uint64_t const rowsFree,
    uint64_t const upDiagFree,
    uint64_t const downDiagFree,
    uint64_t const col
)
{
    if (!rowsFree) {
        return true;
    }

    uint64_t spaces = rowsFree & upDiagFree & downDiagFree;

    while (spaces)
    {
        uint64_t bit;
        splitLowestBit(spaces, bit);
        board[col] = bit;

        bool solvable = solveNQRecurse(
            board,
            (bit ^ rowsFree),
            ((bit ^ upDiagFree) >> 1ULL) | (1ULL << N),
            ((bit ^ downDiagFree) << 1ULL) | 1ULL,
            col + 1ULL
        );

        if (solvable) { return true; }
    }
    return false;
}

/* solves the N Queen problem using Backtracking.*/
bool solveNQ()
{
    std::array<uint64_t, N> board{};
    uint64_t fullMask = (1ULL << N) - 1ULL;

    bool solvable = solveNQRecurse(
        board,      // board
        fullMask,   // rowsFree
        fullMask,   // upDiagFree
        fullMask,   // downDiagFree
        0           // col
    );

    if (solvable)
    {
        printBoard(board);
    }
    else
    {
        std::cout << "Solution does not exist" << std::endl;
    }

    return solvable;
}

int main()
{
    solveNQ();
}


Fastest way of removing a substring from a string

It should be possible to optimize a global search-and-replace by doing all the moves in one pass.

void rmSubstr(char *str, const char *toRemove)
{
    size_t length = strlen(toRemove);
    char *found,
         *next = strstr(str, toRemove);

    for (size_t bytesRemoved = 0; (found = next); bytesRemoved += length)
    {
        char *rest = found + length;
        next = strstr(rest, toRemove);
        memmove(found - bytesRemoved,
                rest,
                next ? next - rest: strlen(rest) + 1);
    }
}

Output using your test code:

Function ran in 351851 clock cycles
Produced output: test this out

Function ran in 1349681 clock cycles
Produced output: test this ...........slightly............ longer thing which contains a sub out

Function ran in 197570 clock cycles
Produced output: string

Function ran in 416682 clock cycles
Produced output: this is not a test

Program ended with exit code: 0


How clean is this mustache template for a listing page?

By using excessive markup for presentational purposes, the template is the exact opposite of clean.

{{{telefon}}}

vs.

{{{telefon}}}

If you're not able to do this because of a library you're depending on, my recommendation is to find a better library.

By moving away from tables, you've committed a sin that's just as bad as using tables for layout:  you're using non-tabular markup for tabular data.  It is understandable that you don't want it to look like a table (either for aesthetic or responsive reasons), but tables don't have to look like tables any more than a list has to look like a list.

Go back to using tables and make adjustments to your CSS instead:

http://jsfiddle.net/SGK8Q/

What the markup should end up looking similar to this:

            Lab
            Contact
            Phone
            Website

            ABC
            Johnny
            555-1234
            http://abc.example.com/

            DEF
            Billy
            555-1234
            http://def.example.com/

            GHI
            Dave
            555-1234
            http://abc.example.com/

The CSS:

table, tbody, tr, td, th {
    display: block;
}

thead {
    display: none;
}

/* everything past here is optional */
tr + tr {
    margin-top: 1em;
}

.name {
    font-size: 1.2em;
    font-weight: bold;
}

.url {
    color: blue;
    text-decoration: underline;
}


Simple tkinter application that choose a random string

Standards

Follow the PEP8 coding standard.  One violation that immediately is obvious is the lack of a space following a comma.  For example, (row=0, column=1, sticky=E, pady=2, padx=5) is much easier to read.  Use pylint (or similar) to check your code style against the recommended standard.

Import grouping

My personal preference is to keep import ... statements together, and from ... import ... statements together, not interleave them.

Private class members

"Private" members should be prefixed with an underscore.  Such as self._champ_list and def _scan(self):.  This doesn't actually make them private, but some tools will use the leading underscore as a key to skip generating documentation, not offer the member name in autocomplete, etc.

Remove useless members

self.randombutton is only used in the constructor; it could just be a local variable, instead of a member.

Use correct comments

The # layout comment above the Button and Text construction is misleading; it is not doing any layout.

Self documenting names

Use understandable names.  I have no idea what LRG is.  Good variable names go a long way towards creating self-documenting code.

Use Doc-Strings

Add """doc-strings""" for files, public classes, public members, and public functions.  Using LRG as a class name could be fine (in may be a common acronym at your company), but adding a doc-string for the class could spell out what the acronym stands for at least once.

Avoid hard-coded information

You have hard-coded reading the data/champs.csv file into the constructor.  Consider making it more flexible, such as passing in a filename with that as a default.

class LRG:
    """Literal Random Generator"""

    def __init__(self, master, csv_filename="data/champs.csv"):
        # ...etc...

Or, move the reading of the data outside of the class, and pass the champ_list in as a constructor argument.


A dynamic array based stack will use less memory, as it does not have to store an address with each element. It will probably be faster for push because it doesn't need to make an allocation each time.

The main benefit of using a linked list is immutability. With a linked list, you can make stack operations that leave the previous stack as it is.
However this is difficult without garbage collection.

Since you are not going for an immutable stack, I would recommend changing the signatures of you push() and pop() functions to something like this:

void push(Node **top, int value);
int pop(Node **top);

This way, you don't leave users of your utility with pointers to freed values, so they can't screw up their stack by popping and using the original stack, which is now invalid.


Creating an async consumable object in Node

There is an error that needs to be handled correctly:

      self.objects[name].method(msg, function(err, results){

        if (err) {
           return callback(err);
        }
        return callback(null, results);

      });

You need to return the callback on the error, otherwise if an error comes down, you will hit both callbacks.


Firstly, I really don't like your indentation, particularly with the method header, so I've pasted into Visual Studio and will be working from the code as it appears below:

    public object DistanceFrom(IEnumerable<Coordinate> coordinates)
    {
        IEnumerable<DbGeography> addresses = coordinates.Select(c =>
            DbGeography.FromText(String.Format("POINT ({0} {1})", c.Longitude, c.Latitude)));
        IEnumerable<VehicleGeography> vehicles = this.GPSInsightProvider.Query().Document.Placemarks.Select(p =>
            new VehicleGeography
            {
                DriverName = p.DriverName,
                Point = DbGeography.FromText(String.Format("POINT ({0} {1})", p.Point.Longitude, p.Point.Latitude))
            });
        ICollection<object> technicians = new List<object>();

        foreach (DbGeography address in addresses)
        {
            technicians.Add(
                vehicles
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = v.Point.Distance(address) / 1609.344
                        })
                    .Where(v =>v.Distance.HasValue)
                    .OrderBy(v =>v.Distance)
                    .Take(3)
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = String.Format("{0:#.#}", v.Distance)
                        }));
        }

        return technicians;
    }

My first question: Why does this return an object? I'm strongly against returning anonymous types, you really should be creating a class or struct for this data combination. Secondly, you know that at the bare minimum, it returns a List of these anonymous types, so at the least your should return a List<object>

Secondly:

ICollection<object> technicians = new List<object>();

Why are you specifically reducing the functionality that you're returning? Require least on parameters, return most.

Use var on variable declarations where the right-hand-side makes the type obvious. This saves you extra typing when you want to change that variable's type later.

e.g.

ICollection<object> technicians = new List<object>();

becomes

var technicians = new List<object>();

Is there a special reason you return only the top 3 results from your query? If so, that magic number should be a const somewhere with a reasonable name. If not, it should be a variable somewhere, again with a reasonable name.

The same goes for 1609.344. I'm guessing that's a conversion from meters to miles, but it doesn't make a ton of sense on its own.

I think your LINQ is doing a little bit too much. I'd recommend splitting it up a bit so it's clearer what it's doing. Afterall, you're already looping through addresses, so split it up a little.

            technicians.Add(
                vehicles
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = v.Point.Distance(address) / 1609.344
                        })
                    .Where(v =>v.Distance.HasValue)
                    .OrderBy(v =>v.Distance)
                    .Take(3)
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = String.Format("{0:#.#}", v.Distance)
                        }));

maybe becomes

            var vehiclesByDistance =
                vehicles
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = v.Point.Distance(address) / 1609.344
                        })
                    .Where(v =>v.Distance.HasValue)
                    .OrderBy(v =>v.Distance);

            technicians.Add(
                vehiclesByDistance
                    .Take(3)
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = String.Format("{0:#.#}", v.Distance)
                        }));

Finally, I'm pretty sure your LINQ is breaking the Single Responsibility Principle. It appears to be performing distance unit conversion, sorting and formatting. It might be wise to split this up a bit.


How to improve this array manipulation function?

Seems you might be overusing Linq since you are manipulating an array.  Here is an example that to me is a bit more readable (although the readability could be improved further) and it is faster.

private static int[] EquivalentOutput(int cap, int[] permutation)
{
    int[] copy = permutation.ToArray();

    for (int i = 0; i < copy.Length; i++)
    {
        if (copy[i] == 0)
            continue;

        var consecutiveElements = copy.Skip(i).TakeWhile(x => x != 0).ToArray();
        var max = consecutiveElements.Max();
        if (max == cap)
        {
            for (int j = 0; j < consecutiveElements.Length - 1; j++)
                copy[i++] = 1;
            copy[i++] = cap;
        }
        else
        {
            for (int j = 0; j < consecutiveElements.Length; j++)
                copy[i] = copy[i++] == max ? max : 1;
        }
    }
    return copy;
}

Update:
@svick pointed out that it feels a bit "weird" changing the loop variable inside the loop so I am providing an alternative which some people will consider easier to read...

private static int[] EquivalentOutput(int cap, int[] permutation)
{
    int[] copy = permutation.ToArray();

    int i = 0;
    while (i < copy.Length)
    {
        if (copy[i] > 0)
        {
            var consecutiveElements = copy.Skip(i).TakeWhile(x => x != 0).ToArray();
            var max = consecutiveElements.Max();
            if (max == cap)
            {
                for (int j = 0; j < consecutiveElements.Length - 1; j++)
                    copy[i++] = 1;
                copy[i++] = cap;
            }
            else
            {
                for (int j = 0; j < consecutiveElements.Length; j++)
                    copy[i] = copy[i++] == max ? max : 1;
            }
        }

        i++;
    }
    return copy;
}


This is the the way singletons are usually implemented in apple's code samples.

+ (ItemsManager *)sharedInstance
{
    static ItemsManager *sharedInstance = nil;
    static dispatch_once_t once;

    /* Doing the allocation inside dispatch_once queue ensures the code
       will run only once for the lifetime of the app. */

    dispatch_once(&once, ^{
        sharedInstance = [[ItemsManager alloc] init];
    });

    return sharedInstance;
}


Create a class

class MyPageHandler(custom.PageHandler):
     def veryUserNotLoggedIn(self):
         if users.getCurrentUser():
             self.renderPage("customMessage.htm", custom_msg=msg)
             return False
         else:
             return True

Then you can write you class like

class Login(MyPageHandler):
    def get(self):
        if self.verifyUserNotLoggedIn():
             self.renderPage('login.htm')


I haven't attempted to measure the timing of this, in part because I don't know how you're planning to use it, but here are some ideas for improving your code.

Consider returning something useful from functions

Your Split function doesn't return anything, which isn't an error, but it's an odd design.  I'd expect it to be declared like this instead:

std::vector<std::string> Split(const std::string& subject)

Understand sizeof

The sizeof operator is defined as always returning 1 for sizeof(char), so having that expression as part of your code probably isn't useful.

Use "range for" to simplify your code

The code to print the vector could be made much simpler and shorter by using a "range for" that was introduced in C++11:

for(const auto &item : container) {
    std::cout << item << "!\n";
}

Use standard library algorithms

I'd be inclined to write this using C++ rather than C functions.  One way to do this is to use std::copy and std::stringstream:

std::vector<std::string> Split(const std::string& subject)
{
    std::istringstream ss{subject};
    using StrIt = std::istream_iterator<std::string>;
    std::vector<std::string> container{StrIt{ss}, StrIt{}};
    return container;
}

I've also been playing with std::sregex_token_iterator lately.  Here's how that might look:

std::vector<std::string> Split(const std::string& subject) {
    static const std::regex re{"\\s+"};
    std::vector<std::string> container{
        std::sregex_token_iterator(subject.begin(), subject.end(), re, -1),
        std::sregex_token_iterator()
    };
    return container;
}


Edit Oh well, not using nested for... Sorry about that

int inc = 2;
for (int i = 1; i >= 1; i += inc){
    std::cout<<std::string(i,'*')<<endl;
    if ( i == 5 )
        inc = -2;
}