Starting and stopping a thread for a command handler

Your approach is works for a single start-stop cycle. Afterwards, things may go wrong. Let's look at the simple scenario first, though:

You should keep in mind that you want to halt the running threads as soon as possible whilst maintaining system functionality. That is, when I say stop, and there's no calculating or whatever going on, the system ought to stop. But in your case, it might not.

You see, what you have here,

    while (isRunning()) {
        String userInput = Input.readLine();

        commandHandler.handle(userInput);
    }

Is either a spin loop or does not check the isRunning fast enough. Or so I think.

If there is no timeout for Input.readLine() and it does block until input is required, then stopping the application whilst it is waiting for input will lead to the application only actually shutting down AFTER the input has arrived and been handled. In case of a system shutdown, or programmed shutdown, this input may never arrive. The JVM will handle power situations for you, forcibly killing your thread, but if you were to use this as a library and another thread was told to shutdown the application your application thread wouldn't be shut down.

If there is no timeout for Input.readLine() and it does not block until input is required, then you've got a spin loop. When running, the application will check thousands of times whether you've got input, and then pass the non-existing input (maybe as empty string, maybe null), through your commandhandler. This is a waste of system resources.

By setting a timeout on the input reading, you can resolve this issue: By blocking for only 100ms (or so) for input, you can reduce the amount of checks to about 10 per second (which is easily handled by processors), whilst at the same time maintaining a fast response upon shutdown.

Secondly, your code is not threadsafe. There are certain cases which will cause things you do not want to happen.

If two threads call start() at the same time, then...

public void start() {

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            setRunning(true);
        }
    } else {
        System.out.println("Starting " + threadName + "...");

        thread = new Thread(this, threadName);
        thread.start();

        System.out.println("Started " + threadName + ".");
    }
}

Both threads start at the top of the function.

First line is this:

if (thread != null)

Well, thread is null in both cases. Thread 1 goes into the else statement, and so does thread 2.

    else {
        System.out.println("Starting " + threadName + "...");

        thread = new Thread(this, threadName);
        thread.start();

        System.out.println("Started " + threadName + ".");
    }

No checks occur here, so both threads start the application. You now have 2 application threads running.

Now, there are a few more scenarios I could describe, but there are some structural flaws in the code which should be addressed before we go into that.

First, you keep track of your state like this:

public Application() {

    Handler handler = new Handler(this);

    this.commandHandler = new CommandHandler(handler);

    this.running = true;
}

In the constructor you set running to true. But the application isn't running yet! What you should do is set running to true in the start function. That way, whenever start is called, the result is that the application is running (either it was running before, or it was started).

Secondly, whenever a thread needs to be "resumed", you check like this:

        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            setRunning(true);
        }

That's not going to work, sadly. When you call stop, and set running to false, the thread can leave the while loop and terminate. A terminated thread cannot be restarted. So you must use a new thread!

But even this is not that easy - let's go with the naive approach first.

First, since we are going to be making threads both in the regular (no thread running) and resuming (thread was running but has terminated) functions of start, let's extract threadmaking to a separate function:

private void startApplicationThread(){
    thread = new Thread(this, threadName);
    setRunning(true);
    thread.start();
}

Next, add the startApplicationThread to the start function like so...

public void start() {

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            startApplicationThread();
        }
    } else {
        System.out.println("Starting " + threadName + "...");

        thread = new Thread(this, threadName);
        thread.start();

        System.out.println("Started " + threadName + ".");
    }
}

But, like this, we have another case of thread unsafe code: If thread 1 and thread 2 resume application via start at the same time, they will both reach startApplicationThread!

So let's fix that.

It's pretty easy to fix - just add synchronized. What synchronized does is say "only 1 thread can be in any method that is synchronized per instance at the same time". For now, this is good enough, but later you may want to use locking objects to prevent other possible coding errors.

public synchronized void start()
public synchronized void stop()

But it's still not threadsafe!

Let's say we have 1 thread running the application and 1 external thread. The external thread first calls stop. It goes through and running is now false. The application thread, however, is still busy with Input.readLine. That is to say, it's still waiting for input - as a result, it's still in the while loop and won't be going anywhere.

Quick overview of the situation:

Application thread is here:

    while (isRunning()) {
        String userInput = Input.readLine(); // <= applicationthread

        commandHandler.handle(userInput);
    }

External thread is here:

//external code
application.stop();

// <= externalthread
application.start();

And running is false.

Next, the external thread calls start. Because there is no other thread busy with start or stop, it can go into the method. It goes through the checks, thread != null is true, !isRunning() is also true, and starts a new thread (because the old one is "dead"). running is set to true again... and... oh snap.

Application threads:

    //<= applicationthread 2
    while (isRunning()) {
        String userInput = Input.readLine(); // <= applicationthread

        commandHandler.handle(userInput);
    }

External thread is here:

//external code
application.stop();

application.start();
// <= externalthread

And running is true, so application thread 2 will soon be moving into the while loop.

Now we've got 2 application threads again! Darn it.

So, before we start a new thread, we should make sure that it's actually dead. Now, whilst it is possible to save the running thread, it makes things hard, so lets discard the running thread - wait for it to die first.

Looking through the Javadoc of Thread, we can find Thread.join, which does this: "Waits for this thread to die." Great!

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            thread.join();
            startApplicationThread();
        }
    }

Now you get a compiler error because you need to catch InterruptedException - maybe you ought to deal with that in a cleaner way, but for now I'm going to ignore it.

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            try {
                thread.join();
            } catch (InterruptedException ie){
                //ignore
            }
            startApplicationThread();
        }
    }

Oh wait, now we could get InterruptedException whilst waiting. Not good. Let's just throw a while loop around it: (not the cleanest solution, but it'll work)

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            boolean stoppedRunningThread = false;
            while(!stoppedRunningThread){
                try {
                    thread.join();
                    stoppedRunningThread = true;
                } catch (InterruptedException ie){
                    //ignore
                }
            }
            startApplicationThread();
        }
    }

Might even make it do-while, since we have to do this at least once anyway.

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            boolean stoppedRunningThread = false;
            do {
                try {
                    thread.join();
                    stoppedRunningThread = true;
                } catch (InterruptedException ie){
                    //ignore
                }
            } while(!stoppedRunningThread);
            startApplicationThread();
        }
    }

So, now we are done, right?

Well... not quite. You see, what would happen if the thread that wants to restart the application is the application thread?

Well, we'd go through start, and wait for the currently running thread to... die... Yeah, that's not going to work! In that case, we can use Thread.currentThread() to compare! If we find that the thread that is restarting the application is the application thread, then we don't need to wait for it to die, we can just set running to true again, because we know it is still in the while loop and won't go out of the while loop whilst we are setting the variable.

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            if (thread != Thread.currentThread())
            {
                boolean stoppedRunningThread = false;
                do {
                    try {
                        thread.join();
                        stoppedRunningThread = true;
                    } catch (InterruptedException ie){
                        //ignore
                    }
                } while (!stoppedRunningThread);
                startApplicationThread();
            } else {
               setRunning(true);
            }
        }
    }

So now, finally, everything is threadsafe, yes?

Well no. You see, this method here is public:

public void setRunning(boolean running) {

    this.running = running;
}

And that ruins pretty much everything. You can kill the application at any time by just calling setRunning(false). What's worse, an application that's been stopped and been told to setRunning(true) can't be restarted! So you should make it private, and access it via start and stop.

private void setRunning(boolean running) {
    this.running = running;
}

So, total overview of how the class is looking right now:

package com.ozankurt;

import com.ozankurt.utilities.Input;

public class Application implements Runnable {

    private CommandHandler commandHandler;

    private boolean running = false;

    private volatile Thread thread;
    private String threadName = "ApplicationThread";

    public Application() {

        Handler handler = new Handler(this);

        this.commandHandler = new CommandHandler(handler);
    }

    public synchronized void start() {

        if (thread != null) {
            System.out.println(threadName + "is already running.");

            if (!isRunning())
            {
                System.out.println("Resuming " + threadName + "...");
                if (thread != Thread.currentThread())
                {
                    boolean stoppedRunningThread = false;
                    do {
                        try {
                            thread.join();
                            stoppedRunningThread = true;
                        } catch (InterruptedException ie){
                            //ignore
                        }
                    } while (!stoppedRunningThread);
                    startApplicationThread();
                } else {
                   setRunning(true);
                }
            }
        } else {
            System.out.println("Starting " + threadName + "...");

            startApplicationThread();

            System.out.println("Started " + threadName + ".");
        }
    }

    public synchronized void stop() {
        System.out.println("Halting " + threadName + "...");

        setRunning(false);

        System.out.println("Halted " + threadName + ".");
    }

    @Override
    public void run() {

        while (isRunning()) {
            String userInput = Input.readLine();

            commandHandler.handle(userInput);
        }
    }

    public boolean isRunning() {

        return running;
    }

    private void setRunning(boolean running) {

        this.running = running;
    }
}

Okay.

So is it threadsafe NOW?! Hmmmm... well... no.

Here's a new situation - an external thread stops the application, and then starts it again, but meanwhile the application thread ALSO wants to stop the application.

Basically like so:

//external code
application.stop();

application.start();

//... inside application.start()...

    if (thread != null) {
        System.out.println(threadName + "is already running.");

        if (!isRunning())
        {
            System.out.println("Resuming " + threadName + "...");
            if (thread != Thread.currentThread())
            {
                boolean stoppedRunningThread = false;//<= external thread
                do {
                    try {
                        thread.join();
                        stoppedRunningThread = true;
                    } catch (InterruptedException ie){
                        //ignore
                    }
                } while (!stoppedRunningThread);
                startApplicationThread();
            } else {
               setRunning(true);
            }
        }
    }

And the application thread is here:

        while (isRunning()) {
            String userInput = Input.readLine();

            commandHandler.handle(userInput);//<= applicationthread
        }

Which is going to stop the application because the user typed "quit".

What happens is that because the external thread is in the start function, the application thread cannot enter stop, and as a result, it has to wait. But it's still alive. So the external thread, waiting in thread.join for the applicationthread to die, will have to wait forever.

A deadlock again!

Resolving this would be hard, but possible:

You could make the quit command break out of the while loop instead of calling stop
You could forcibly kill the thread after a bit of time
You could ignore the issue, how likely is it that this happens?
You could rewrite the locking to use a lock object, so that you can handle this in the stop method
You could make an application a single-use object, instantiating a new Application instead, making the whole restart-locking moot and everything a whole lot easier
You could make "quit" set a flag in the applicationthread, so that the application thread knows that it should stop the while loop even if running is true because the thread has quit...
Use "InterruptedException" to check if applicationthread is blocking you with a smart locking system
Use Locking libraries to be able to conditionally gain a lock before quitting, if you cannot gain a lock, and running is false and thread is not currentthread, then exit function

A whole list of options.

Here's mine:

        while (isRunning() && thread == Thread.currentThread()) {
            String userInput = Input.readLine();

            commandHandler.handle(userInput);
        }

    public synchronized void stop() {
        System.out.println("Halting " + threadName + "...");

        setRunning(false);
        thread = null;

        System.out.println("Halted " + threadName + ".");
    }

This should take care of most of the issues with minimum effort. The rest, I opt to ignore because I think them too rare to occur.

Alternatively, I'd rewrite my application flow so that I don't get into all sorts of crazy start-stop-start-start-stop situations. I'd prefer to change the flow to use Application only once per instance - a simple lifecycle of "start, stop, remain dead".


Truncate 160-bit output from SHA-1 to 64-bit uint64_t

Both your methods should work. As far as I know, there is no alignment problem
on the current OS X and iOS architectures in your first method (see below).

The code from the second method can be simplified a tiny bit:

- (uint64_t)digestFromString: (NSString *)s {
    NSData *input = [s dataUsingEncoding: NSUTF8StringEncoding];
    union { // uint64_t-aligned
        uint64_t      digest;
        unsigned char bytes[CC_SHA1_DIGEST_LENGTH];
    } output;
    CC_SHA1(input.bytes, (CC_LONG)input.length, output.bytes);
    return output.digest;
}

The first element in the union need not be an array, and casting output.bytes
to unsigned char * is not necessary (the array automatically becomes a pointer
to the first element when passed as a function argument).

But the easiest method to extract a 64-bit integer from the digest would be to use the inline function

OS_INLINE uint64_t _OSReadInt64(
    const volatile void               * base,
    uintptr_t                     byteOffset
)

from OSByteOrder.h that comes with the OS X and iOS SDKs:

uint64_t digest = _OSReadInt64(output, CC_SHA1_DIGEST_LENGTH - sizeof(uint64_t)); // last 8 bytes
uint64_t digest = _OSReadInt64(output, 0); // first 8 bytes

This function is implemented as

return *(volatile uint64_t *)((uintptr_t)base + byteOffset);

which indicates that there is no alignment problem when casting an
arbitrary pointer to uint64_t *. But that may be different on future
architectures, with using the above function you are on the safe side.

Alternatively, you can use memcpy:

uint64_t digest;
memcpy(&digest, output, sizeof digest);

Instead of

NSAssert(CC_SHA1_DIGEST_LENGTH >= sizeof(uint64_t), nil);

you could use a "compile-time/static assertion":

_Static_assert(CC_SHA1_DIGEST_LENGTH >= sizeof(uint64_t), "");

_Static_assert is a GCC extension which is also understood by the Clang
compiler, so you can use it in your Xcode projects.

The advantage is that it causes a compiler error if the condition is
not satisfied, instead of failing later at runtime.


if (model == null || UserInfo.UserID == 0)
{
  throw new Exception("GroupBillingPayment object or Current User Id is NULL , Please Contact Administrator.");
}

You should split this into two ifs and two different exceptions.

The first one should only check the parameter passed and throw the ArgumentNullException because we don't throw the Exception directly but some more specific ones that convey more information.

The other one should be the InvalidOperationException which means that the object is in an invalid state which would be when the UserInfo.UserID is 0.

 ServiceManager.GroupBilling.IsBillAlreadyCancelled(
       groupBillingPayment.GroupBillingID,
       THROW_ERROR);

If the second parameter does what I think it does, this is, indicates whether the method should throw an exception or not then this is a very bad idea. If you need a method that does not throw then you should create another one by following the try-something pattern.

  if(ServiceManager.GroupBilling.TryGetBillAlreadyCancelled(
       groupBillingPayment.GroupBillingID,
       out bool canceled))
  {
      ...
  }


A possible solution that is very close to your example could be

var services = isMandatory ? x.MandatoryServices
                           : x.OptionalServices;
services.ForEach(y =>
{
    if (!y.IsSelectedByUser)
    {
        containsRemovedSrvcs = true;
        return;
    }
});

This require that MandatoryServices and OptionalServices can be assigned to the same variable (i.e. same type, shared interface, ..)

I don't understand why you explicitly return return from your lambda expression, since it does not change anything. The "body" of the lambda will be executed for each element in your collection, regardless of your return.

So you could just remove the return:

if (!y.IsSelectedByUser)
{
    containsRemovedSrvcs = true;
}

And since it looks like you just want to see if any element in the collection is not selected by the user, you can use the Any extension method

containsRemovedSrvcs = services.Any(y => !y.IsSelectedByUser);

Applying all this will give you:

var services = isMandatory ? x.MandatoryServices
                           : x.OptionalServices;
containsRemovedSrvcs = services.Any(y => !y.IsSelectedByUser);


Regarding min(string): Python exceeding your expectations. It happens a lot.

assert

All assert statements can be disabled with a switch to the interpreter, and sometimes are. Therefore, they're not suitable for flow control. I think you should replace:

for character in string:
    assert ord(character) <= 127

With:

for character in string:
    if ord(character) > 127:
        raise ValueError(f"Character {character} is out of range.")

or to optimize with a generator instead of the loop (requires Python 3.8+ if you want to report the character that violates the condition):

if any(ord(character := char) > 127 for char in string):
    raise ValueError(f"Character {character} out of range")

(Thanks to @Graipher for proper handling of the := token in 3.8+, which I hadn't worked with myself yet.)

That's all I can see being wrong here, though.


if I quite understand your problem, to do a proper incr() method I would do so :

public class BooleanTriple {
    private boolean a,b,c;
    private int i;
    public BooleanTriple(boolean a, boolean b, boolean c){
        this.a =a; this.b=b; this.c=c;
        this.i = (a ? 1 : 0)*4+(b ? 1 : 0)*2+(c ? 1 : 0)*1;  // not sure if this compile, but the idea is here
    }

    public void incr(){
        i = (i + 1) % 8;
        a = (i & 0x4) != 0;
        b = (i & 0x2) != 0;
        c = (i & 0x1) != 0;
    }
    public boolean logProduct(){ return a && b && c;}
}

With i going from 0 (000 binary) to 7 (111 binary) you have all the possible values for a, b and c


Your code is great so far.
The only tip I can think of is to wrap grouped variables inside a namespace / singleton.
This would make it easier to debug and perform operations of group of related elements.

    // GENERAL VARS
var UpRate = 250,
    DownRate = UpRate,
    OpenHeight = "25px";

// SET IPP VARS
var $IPP = {};
$IPP.Wrapper = $("div.iqPaginItemsPerPageWrapper");
$IPP.Default = $IPP.Wrapper.children("div.iqPaginDefault");
$IPP.NonDefault = $IPP.Wrapper.children("div.iqPaginNonDefault");
$IPP.Options = $IPP.Wrapper.children("div.ItemsPerPage");
$IPP.Value = $("span#ItemsPerPageValue");

// SET SB VARS
var $SB = {};
$SB.Wrapper = $("div.iqPaginSortByWrapper");
$SB.Default = $SB.Wrapper.children("div.iqPaginDefault");
$SB.NonDefault = $SB.Wrapper.children("div.iqPaginNonDefault");
$SB.Options = $SB.Wrapper.children("div.SortBy");
$SB.Value = $("span#SortByValue");

// CREATE SB TEXT ARRAY
var SBTextArray = [];
SBTextArray[1] = "Company Name A - Z";
SBTextArray[2] = "Company Name Z - A";
SBTextArray[3] = "Product Name A - Z";
SBTextArray[4] = "Product Name Z - A";
SBTextArray[5] = "Model Number A - Z";
SBTextArray[6] = "Model Number Z - A";

1) Use a namespace for related elements and functionality.

2) It depends. In most cases it doesn't matter unless if you different tags with the same classes. Like p.class1 and dd.class1. More info here

3) You could just use an object literal to store the message by a reference name.
Something like this.

var listing = { az: {}, za: {} };
listing.az.company = "Company Name A - Z";
listing.az.product = "Product Name A - Z";
listing.az.model = "Model Number A - Z";
listing.za.company = "Company Name Z - A";
listing.za.product = "Product Name Z - A";
listing.za.model = "Model Number Z - A";

I think your current code is good enough though.


A couple of comments:

String[] strArray = s.split("\\s+"); will create a Pattern object each time this is called, which might hurt the performance. It would be better to reuse the same pattern. Declare it as a constant:

private static final Pattern PATTERN = Pattern.compile("\\s+");

and then you can use

String[] strArray = PATTERN.split(s);

Use a for-each loop instead of a loop using index. This is both easier to read and to maintain when you don't need the index. So instead of having

for (int i=0; i<strArray.length; i++){
    sb.append(strArray[i]);

you can have

for (String str : strArray){
    sb.append(str);

If you can use Java 8, you could have

public static String sortString(String s){
    return PATTERN.splitAsStream(s).sorted().collect(Collectors.joining(" "));
}

This splits the input String into a Stream<String> using splitAsStream. Then the stream is sorted and finally collected with a collector joining all elements together, separated by a space, using Collectors.joining(" "). As a side-note, this will not include the last white-space at the end of the joined Strings, unlike the code in your question.


Tree structure with support for inorder and preorder traversal

Your instinct to question the appropriateness of tree.size(tree) is right.  You should be able to write tree.size() instead.  The problem is that you've written the methods to take a node parameter, when in fact self is a Node.

Therefore, you should define

def size(self):
    return 1 + (self.left.size()  if self.left  is not None else 0) \
             + (self.right.size() if self.right is not None else 0)

so that you can write tree.size().

The __str__ method isn't right: there's nothing that says that data is a string.  (In fact, in your example, they are integers.)  A more reasonable implementation would be

def __str__(self):
    return str(self.data)

It would be better to avoid hard-coding the print() calls in inorder and preorder, so that they can be used to do more than just printing.  In Python, it would be better to yield each datum, so that inorder() and preorder() act as generators.  (Note that this uses yield from, introduced in Python 3.3.)

def inorder(self):
    if self.left is not None:
        yield from self.left.inorder()
    yield self.data
    if self.right is not None:
        yield from self.right.inorder()

… to be called like

for data in tree.inorder():
    print(data)

You would then have the flexibility to write something like sum(data for data in tree.inorder()) to add all of the nodes.


Possible issues

1 Follow a style guideline. It is common convention to camel case local variable names.

var theFile = new FileInfo(...)  instead of  var TheFile = new FileInfo(...).

Format your file equally (i.e. either all methods are separated by a blank line or none).

2 Keep lines short and use more variables to get better readability and easier debugging:

var newPath = Path.Combine(file.DirectoryName, file.Name, file.LastWriteTime.ToString(), file.Extension)
file.MoveTo(newPath);

instead of

TheFileInfo.MoveTo(string.Format(@"{0}\{1}_{2}{}", TheFileInfo.DirectoryName, TheFileInfo.Name, TheFileInfo.LastWriteTime.ToString(), TheFileInfo.Extension));

3 Use meaningful names.

RollingTextWriterTraceListener instead of MyTextWriterTraceListener

[MethodImpl(MethodImplOptions.NoInlining)] instead of [System[...]NoInlining)]

What do you do if you need an other implementation - MyOtherTextWriterTraceListener?
The same applies to TheFileInfo, ConsoleApplication1.

4 Remove redundant qualifiers to remove clutter.

public MyTextWriterTraceListener(Stream stream) : base(stream) { }

instead of

public MyTextWriterTraceListener(System.IO.Stream stream) : base(stream) { }

var file = new FileInfo(...) instead FileInfo file = new FileInfo(...)

5 Are you sure you need the [MethodImpl(MethodImplOptions.NoInlining)] attribute?

What I like

1 if (TheFileInfo.Exists == false) return;

because the return statement reduces nesting (see arrow head anti pattern) and == false because its more obvious and than !TheFileInfo.Exists. A lonely ! can quick be overseen. I would recommend the same procedure for the following if statement, too:

if (TheFileInfo.LastWriteTime.Date >= DateTime.Today) return;

instead of

if (TheFileInfo.LastWriteTime.Date < DateTime.Today) { ... }

General recommendations

1 As k3b mentioned I would recommend using log4net, too. It has more flexibility you will ever need and you can configure it via config file which means you can change your logging output without recompiling.


Let me first assume that your unique_ptr is supposed to be movable. Then, any basic test case whould have unrevealed this:

unique_ptr<int> ptr1(new int());
unique_ptr<int> ptr2 = std::move(ptr1); // Fails to compile

Recall that = delete-ing special member functions means user-declaring them. And user-declared copy and copy assignment constructors prevent compiler-generated move (assignment) constructors! You have to manually define them. This case is by the way covered by the rule of five/C.21 Core Guidelines, and also have a look at the table posted in this SO answer for an overview of compiler-generated/-deleted/not-declared special member functions.
Is the non-availability of an implicit conversion to bool intended? Checking if a (smart) pointer is in an empty/null state is so common in ordinary control flow statements that clients will expect this to compile:

unique_ptr<SomeType> ptr = ...;

if (ptr) ... // currently fails to compile

But not that this might be debatable. Implicit conversions can cause a lot of pain, so if you intend to not allow them for the sake of a more explicit

if (ptr == nullptr) ...

that's a design decision. But one that should be documented in a comment at the top of the class.
Except the non-explicit-ness of the second constructor (thanks to @Deduplicator for pointing that out) taking a std::nullptr_t, it is superfluous. You can construct an empty unique_ptr by

unique_ptr<SomeType> empty{nullptr};

which simply invokes the first constructor taking a T* argument. I would remove the second constructor.
... and add a default constructor that initializes ptr_resource to nullptr, as

unique_tr<SomeType> empty;

might be a way of constructing an empty smart pointer that users would expect to compile.
Move-constructing the ptr_resource in the constructor initializer by ptr_resource(std::move(raw_resource)) doesn't make much sense. Just copy the pointer instead. The comment // std::move is used because it is used to indicate that an object may be moved from other resource. is rather confusing, because T* raw_resource is already a pointer, and hence a handle to a resource, not the resource itself.
The release member function can be implemented more conveniently as

T* release() noexcept
{
    return std::exchange(ptr_resource, nullptr);
}

I wouln't let the reset member function throw when the input is a nullptr. Why shouldn't it be allowed to reset a unique_ptr with a nullptr, turning it back into an empty state?
The only facilities you use from the standard library are std::move and std::swap. Those are in <utility>, so you don't need to include <algorithm>, which is probably much heavier in terms of compile times.
I would omit the this-> prefix, it's unnecessarily verbose. But that might be a matter of taste.
Have you considered custom deleters? This makes the class template more reusable in scenarios other than pointers to heap resources, e.g. closing a file upon destruction etc.


Simplifying these methods for iterating through object and modifying string fields

As always simplicity is king. In my opinion you have done a lots of extra effort which might not be necessary.
Let's look at the problem from 10 000 feet high:

You receive an arbitrary object as input
You need to produce a string output where the SN data are masked out

What if you first serialize the data and then mask it?
public static string MaskOut(object toBeMaskedObject,
    string regexPattern = @"\d{6}-?\d{4}[0-9]*",
    string mask = " XXXXXX-XXXX ")
{
    var serializedData = JsonConvert.SerializeObject(toBeMaskedObject);
    return Regex.Replace(serializedData, regexPattern, mask);
}

And that's it.
I've used the following data structures for testing:
var simpleWithoutSN = new
{
    Desc = "123",
    Id = 1
};

var simpleWithSN = new
{
    SN = "123456-7891",
    Id = 1
};

var nestedWithSN = new
{
    Id = 1,
    Items = new []
    {
        new { SN  = "123456-7891",},
        new { SN  = "123456-7892",},
    }

};

Console.WriteLine(MaskOut(simpleWithoutSN));
Console.WriteLine(MaskOut(simpleWithSN));
Console.WriteLine(MaskOut(nestedWithSN));

The output will be:
{"Desc":"123","Id":1}
{"SN":" XXXXXX-XXXX ","Id":1}
{"Id":1,"Items":[{"SN":" XXXXXX-XXXX "},{"SN":" XXXXXX-XXXX "}]}


Method decomposition

The main method reads and parses the input,
and does a large part of the calculation logic too.
It would be better to move the calculation outside.
That is, after the input is read and parsed,
it will be better to leave just this in main:

System.out.println(findEqualHeight(h1, h2, h3));

And all the calculation logic can be in findEqualHeight.

Simplify the algorithm

The algorithm is a bit complicated and hard to understand.
It's also inefficient.
As you knock off cylinders from the 3rd stack,
you check if you can reduce the others from the top.
This can lead to recalculating the sums multiple times.

Consider this alternative implementation:
knock off cylinders from the highest stack,
until they are all of the same height:

static int findEqualHeight(int[] h1, int[] h2, int[] h3) {
    int sum1 = sum(h1);
    int sum2 = sum(h2);
    int sum3 = sum(h3);

    int i1 = 0;
    int i2 = 0;
    int i3 = 0;

    while (true) {
        if (sum1 > sum2 || sum1 > sum3) {
            sum1 -= h1[i1++];
        } else if (sum2 > sum1 || sum2 > sum3) {
            sum2 -= h2[i2++];
        } else if (sum3 > sum1 || sum3 > sum2) {
            sum3 -= h3[i3++];
        } else {
            break;
        }
    }

    return sum1;
}

static int sum(int[] arr) {
    return IntStream.of(arr).sum();
}


The principal performance issues are on the database side (or maybe you could do some kind of caching or pre-loading), but your code could be made much clearer and shorter (there should be also some minor performance improvements):

string[] columnNames = new[] { "sub_id", "sibheadername" };

var categories = db.allcategories().ToList();

if (categories.Count == 0)
{
    return;
}

var dt = new DataTable();
dt.Columns.Add(columnNames[0]);
dt.Columns.Add(columnNames[1]);

foreach (var category in categories)
{
    var selectedCategories = db.selcategories(Convert.ToInt32(category.sub_id)).ToList();
    int count = Convert.ToInt32(selectedCategories.First().Column1);

    DataRow dr = dt.NewRow();
    dr[0] = category.sub_id;
    dr[1] = count != 0
                ? category.sibheadername + " (" + count + ")" // btw. this is FASTER (in this case) than a StringBuilder!
                : category.sibheadername;

    dt.Rows.Add(dr);
}

areaDropdown.DataSource = dt;
areaDropdown.DataTextField = columnNames[1];
areaDropdown.DataValueField = columnNames[0];
areaDropdown.DataBind();
areaDropdown.Items.Insert(0, "");


It's a design choice.
A class is "meant to be" a collection that encapsulates functionality and "behavior" in code. The purpose is to expose specifically an interface where a class's instances can live on their own.

A function/method is an independent piece of code that in theory "shouldn't" relate to other pieces of code outside of it.

So for the example you've described, you could create a class named "User". And user can include these functions as it's members.
This does make it more readable and easier to debug.
However do not take unrelated functions and dump them into a class just cuz!
Examples are utility type functions, they could be kept in the vicinity of each other but should not be clubbed together as a class.

An additional benefit of classes is that they can be Inherited from. So more complex classes can inherit the basic functionality and add to it, while using the features already in the base class. You can achieve a similar effect by having "higher" versions of functions that calls more basic level functions. There again at least in my design perspective, I make a class where the whole functionality will be inherited as opposed to functions that are stand-alone.


Lazily combine ranges dependent on modulo with one loop

Code is read far more often than written.
So I prefer to make code as readable as possible.
Clever code is very often not good code.

I find the posted code very hard to read,
and I don't see why it has to be that way.

I believe this simple, straightforward implementation meets your posted requirements and very easy to read.

def gen(n):
    for x in range(n - 1, divisor - 1, -1):
        if x % divisor == 0:
            yield x
    yield 0
    for x in range(n):
        if x % divisor:
            yield x


Animal, Dog, and IDangerous - Using interfaces and inheritance with C#

Dog obj1 = new GoldenRetriever();

    obj1.Name = "Fluffy";
    obj1.IsVaccinated = true;
    Console.WriteLine(obj1.Name + obj1.IsVaccinated + obj1.Color);

Variable names: avoid name s like obj1 why not
Dog fluffy=new GoldenRetriever();
You have derived GoldenRetriever and Beagle from Dog. Obviously this is an incomplete example and you may have wanted to add further methods according to breed. In this case however it is often best to modify the implmentation at the time you are introducing the extra methods.
Unless there are different implementations best not to create new classes. So you could have had a member property Breed in the Dog class.
The IDangerous interface looks like it should be called  IDangerousDog
If you had a tiger in data tightening the leash is not a likely scenario except if tigers in the data can only be circus tigers. Even then I am not sure I would want to pull an angry tiger closer to me.
When you construct your Dogs it may be better to use a constructor to instantiate the Name and colour properties. This allows you then to have read only members. This is debateable in your example as you could argue that the name of a dog may change if the owner changes. It is best to keep properties immutable where they should be considered so.
If you stored the date of birth rather than the age then this could be immutable too.
It is much easier then to be confident that the age has been corrupted by a bug. Consider what would happen if a bug where to cause the Update age to be fired more than once or at the wrong time. It would be difficult to go back and identify what the correct age of a dog is. However if the Date of birth is stored you can always calculate the age and if there is a bug in the calculation you have not lost the value on which the age calculation is based.


If you want to be completely safe, I would also check the 'choice' to make sure that it was not a negative number.

Goto's should be avoided. You can easily refactor your code to use a while loop and break.

In your function GameResult(), I would use a switch statement instead of the if chain.

I am also thinking that CheckWin() might be a bit too cumbersome with all of the if statements and the checking of the individual cells. I might keep a "shadow board" behind the scenes, where a cell is 1 if it is an X and -1 if it is an O. Some simple addition and a test to see if the Math.Abs(sum) == 3 is an easy way to test for a win. For example:

if (Math.Abs(board[1] + board[2] + board[3]) == 3)
  result = Result.Win;

You can even refactor what I wrote above by keeping a list of the triplets to check.

Good luck with your studies of C#.


Bugs

calculateQuadraticFormula() calculates wrong results for double roots.  Watch your operator associativity!

if( temp == 0 ) {
    results.add(-b / 2 * a);}

The "exit" feature doesn't work.  The prompt would never be "exit", would it?

private static double promptUserUntilValidInput(String prompt){
    if (prompt.equals("exit")) {
        sc.close();
        System.exit(0);
    }

Design issues

Class names should be nouns, and the name should reflect their purpose.  I recommend QuadraticSolver as the class name.
The calculateQuadraticFormula() function could then be simply named solve().
The class should not hold a Scanner as a member variable, as that would violate the Single Responsibility Principle.  It can be a local variable in main() that gets passed to the prompting function.  (The scanner should be created using a try-with-resources block.)
Returning null from the solver is annoying for the caller to handle.  I suggest returning an empty set if there are no real roots.
I suggest returning two copies of the result if it is a double root, but that is a matter for debate.

Style issues

You assign the expression (b * b) - (4 * a * c) to a variable named temp.  Why not use a descriptive name discriminant?
The promptUserUntilValidInput() function could be better if you removed its tryParse() helper, I think.  (Furthermore, promptUser… is redundant — who else are you going to prompt?)

Also, since there is a System.exit() hidden inside, it needs to be documented.  (Actually, @rolfl's suggestion to throw an exception is better.)

/**
 * Prompts the user to enter a number, and retries until the input is a
 * valid double.  Calls System.exit(0) if the input is "exit", or if EOF
 * is encountered.
 */
private static double promptUntilValidInput(String prompt, Scanner sc) {
    do {
        try {
            System.out.print(prompt);
            String input = sc.nextLine();
            if ("exit".equals(input)) {
                System.exit(0);
            }
            return Double.parseDouble(input);
        } catch (NoSuchElementException eof) {
            System.out.println();
            System.exit(0);
        } catch (NumberFormatException retryOnBadInput) {
        }
    } while (true);
}


Loading Active Directory users by username and by SID

I have limited knowledge in C#, but could you not extract something like this?

private static ADUser InternalLoad( IdentityType type, string identity ) {
    using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
    using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity(pc, type, identity))
    {
        if (user != null)
        {
            return Utilities.LoadUser(user);
        }
    }

    return null;
}


def remove():
    ''' see if any existing registrations match our python version and register ours if not '''

    if CurrentUser:

The python style guide reserves CamelCase for class names. If this is a global constant it should be CURRENT_USER. If its not a global constant, it shouldn't be accessed as a global variable.

        match = True if our_version in CurrentUser else False

Just use match = our_version in CurrentUser

        versions = CurrentUser
    elif AllUsers:
        match = True if our_version in AllUsers else False
        versions = AllUsers

    else:
        print '\nOur version (%s) not registered to "%s", skipping...' % (our_version, versions[our_version])

    try:
        if match:
            print '\nVersion matches ours, calling deRegisterPy...'
            deRegisterPy(pycore_regpath,our_version)
    except:
        raise

What??? the try..except does nothing if you just raise the error right away

def deRegisterPy(pycore_regpath, version):

Python style guide recommends lower_case_with_underscores for functions names

    ''' remove this python install from registry '''
    pycore_regpath = pycore_regpath + version   # e.g. 'SOFTWARE\Python\Pythoncore\2.7'
    try:
        reg = OpenKey(HKEY_LOCAL_MACHINE, pycore_regpath)
        installpath = QueryValue(reg, installkey) # win32

Why are you taking the time to point out that its win32 here?

        if installpath == our_installpath:
            print '\nexisting python matches ours, removing...\n'
            # print '(%s vs %s)' % (installpath, our_installpath)

Don't leave dead code in comments

            for subkey in ['\\InstallPath', '\\PythonPath']:
                DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath + subkey)
            DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath)
            print "--- Python %s, %s is now removed!" % (our_version, our_installpath)
        CloseKey(reg)
    except EnvironmentError:
        print 'EnvironmentError', EnvironmentError()

What are you trying to do here? You construct a new EnviromentError object, and then print it. But that's a pointless thing to do

        raise

If you are just going to raise the error again, not a whole lot of point in printing it anyways
            return

Do you realize that nothing after the raise will be executed, so this return will have no effect?

    except WindowsError:
        print "Strange, we've hit an exception, perhaps the following will say why:"
        print WindowsError()

You seem to be confused about how to catch errors, you want:

except WindowsError as error:
    print error

But really you don't need to do that: just let the exceptions fly and python will print them when it exits due to the error

        raise
        return

Again, the return will never be reached

    CloseKey(reg)

If an exception occurs, this will never be called. You should put it in a finally block or something

# main
if args['action']=='install':
    install()
elif args['action']=='remove':
    remove()

You should really put logic like this in a main function.

Any my rewrite of your whole linked file. No testing has been done. But it should give you something of an idea of what you can do.

#!/usr/bin/env python

import sys
from _winreg import *

import argparse, sys
import os.path

PYTHON_VERSION = "%d.%d" % sys.version_info[0:2]

# the registry key paths we'll be looking at & using
PYCORE_REGISTRY_PATH = ("SOFTWARE","Python","Pythoncore")
INSTALL_KEY = "InstallPath"
PYTHON_KEY = "PythonPath"
PYTHONPATH = ";".join( os.path.join(sys.prefix, sub) for sub in ["", "Lib", "DLLs"])

class RegisteryKeyNotFound(Exception):
    pass

class RegisteryKey(object):
    def __init__(self, hive):
        self._key = key

    def _path_from(self, segments):
        if not isinstance(segments, tuple):
            segments = (segments,)

        return "\\".join(segments)

    def __getitem__(self, segments):
        try:
            subkey = _winreg.OpenKey(self._key, self._path_from(segments))
        except WindowsError:
            # should really check the error
            # to make sure that key not found is the real problem
            raise RegisteryKeyNotFound(path)
        return RegisteryKey(subkey)

    def get_or_create(self, segments):
        subkey = _winreg.CreateKey(self._key, self._path_from(segments))
        return RegisteryKey(subkey)

    def value(self, segments):
        return _winreg.QueryValue(self._key, self._path_from(segments))

    def delete(self, segments):
        _winreg.DeleteKey(self._key, self._path_from(segments))

    def set_value(self, segments, value):
        _winreg.SetValue(self._key, self._path_from(segments), REG_SZ, value)

    def __iter__(self):
        index = 0
        while True:
            try:
                yield RegisteryKey(EnumKey(key, index))
            except WindowsError:
                # add check to make sure correct here was gotten
                break
            else:
                index += 1

    def __del__(self):
        _winreg.CloseKey(self._key)

HIVE_LOCAL_MACHINE = RegisteryKey(HKEY_LOCAL_MACHINE)
HIVE_CURRENT_USER = RegisteryKey(HKEY_CURRENT_USER)

def get_existing(hive):
    ''' retrieve existing python registrations '''

    try:
        key = hive[PYCORE_REGISTRY_PATH]
    except RegisteryKeyNotFound:
        return {}

    versions = {}
    for version in key:
        versions[version] = version.value(INSTALL_KEY)                           # e.g. {'2.7' = 'C:\\Python27'}

    return versions

def register_python(version):
    ''' put this python install into registry '''
    try:
        reg = HIVE_LOCAL_MACHINE[PYCORE_REGISTRY_PATH][version]
    except RegisteryKeyNotFound:
        reg = HIVE_LOCAL_MACHINE.get_or_create(PYCORE_REGISTRY_PATH).get_or_create(version)
        reg.set_value(INSTALL_KEY, sys.prefix)
        reg.set_value(PYTHON_KEY, PYTHONPATH)
        print "--- Python %s is now registered to %s!" % (PYTHON_VERSION, sys.prefix)
    else:
        print reg.value(INSTALL_KEY)

    if reg.value(INSTALL_KEY) == sys.prefix and reg.value(PYTHON_KEY) == PYTHONPATH:
        print "=== Python %s is already registered!" % (PYTHON_VERSION)
    else:
        print "*** Unable to register!"
        print "*** You probably have another Python installation!"

def deregister_python(version):
    ''' remove this python install from registry '''
    reg = HIVE_LOCAL_MACHINE[PYCORE_REGISTRY_PATH][version]
    install_path = reg.value(INSTALL_KEY)
    if install_path == sys.prefix:
        print '\nexisting python matches ours, removing...\n'
        for subkey in ['InstallPath', 'PythonPath']:
            reg.delete(subkey)
        reg.delete()
        print "--- Python %s, %s is now removed!" % (PYTHON_VERSION, sys.prefix)

def install(installed_versions):
    ''' see if any existing registrations match our python version, and if not, register ours '''

    print '\n...installing'

    if PYTHON_VERSION in installed_versions:
        print '\nOur version (%s) already registered to "%s", skipping...' % (PYTHON_VERSION, installed_versions[PYTHON_VERSION])
    else:
        print '\nPutting python from environment into registry...\n'
        register_python()

def remove(installed_versions):
    ''' see if any existing registrations match our python version and register ours if not '''
    #print args
    if PYTHON_VERSION in installed_versions:
        deregister_python()
    else:
        print '\nOur version (%s) not registered, skipping...' % (PYTHON_VERSION)

# @url http://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argum
# display the usage message when it is called with no arguments
class MyParser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)

def main():
    parser=MyParser()
    parser.add_argument('action', help='one of "install" or "remove" ')
    args = parser.parse_args()

    current_user_versions = get_existing(HIVE_CURRENT_USER)
    local_machine_versions = get_existing(HIVE_LOCAL_MACHINE)

    print '\nFound in Current User:'
    for key, value in current_user_versions.items():
        print "\t%s - %s" % (key, value)
    print '\nFound in All Users:'
    for key, value in local_machine_version.items():
        print "\t%s - %s" % (key, value)

    all_versions = {}
    all_versions.update(current_user_versions)
    all_versions.update(local_machine_versions)

    if args.action == 'install':
        install(all_versions)
    elif args.action == 'remove':
        remove(all_versions)
    else:
        print '\nInvalid action specified. I only understand "install" and "remove". '

if __name__ == '__main__':
    main()

Some notes:

The _winreg interface is rather low level. You can make code a lot clearer by wrapping it in something more pythonic. I've only taken a first stab at an interface, and it probably could be done a lot better.
You split out CurrentUser and LocalMachine but treated them pretty much exactly the same. The code can be simplified by merging them into a giant dictionary of versions
you remove python from LocalMachine but not CURRENT_USER. That seems odd but I've not changed it.


Closest greater lexicographical permutation

Headers and namespaces

We don't use <vector>, but do need <string>.

Bringing all names in from a namespace is problematic; namespace std particularly so.  It can silently change the meaning of your program when you're not expecting it.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

Bug

This loop fails when w is the empty string:

for (auto rit = next(w.rbegin()); rit!=w.rend(); ++rit) {

This can be fixed with an early return:

if (w.empty())
    return w;

Algorithm

There's a standard algorithm called std::next_permutation() that does most of what we need.  The one difference is that if its input is already the last permutation, it will wrap around to the first one and indicate (by its return value) that it has done so. We can use that to return the original input string in that case.

Tests

You've included no tests.  I think we need to test the trivial case (empty string) and at least one case where we must return a new string and one where we already have the last possible permutation.

Improved code

#include <algorithm>
#include <string>

std::string closest_greater_lexicographical_permutation(const std::string& input) {
    auto word = input;
    return std::next_permutation(word.begin(), word.end())
        ? word   // we changed it
        : input; // no change - already the last permutation
}

// Test program

#include <iostream>
static bool test(const std::string& input, const std::string& expected)
{
    auto const actual = closest_greater_lexicographical_permutation(input);
    if (actual == expected)
        return 0;

    std::cerr << "FAIL (\"" << input << "\"): "
        "got \"" << actual << "\" "
        "instead of \"" << expected << "\"" << std::endl;
    return 1;
}

int main()
{
    return 0
        + test("", "")
        + test("aabb", "abab")
        + test("cba", "cba")
        ;
}


Calculating GetHashCode efficiently with unordered list

If the order does not matter, use an kommutative operator to combine the hashCodes of the elements.

Possible candidates are:
^ binary xor   // THIS WOULD BE MY CHOICE
+ addition       // problem may be the overflow
* multiplication         // problem may be the overflow
| binary or    // not recommended, because after some of this operations it is likely that all bits are set, so the same hashCode would appear for quite different instances)


Calling functions with variable functions

I agree, it does feel dirty to compute the function name like that.

A typical way to do dynamic dispatching is using polymorphism.  You could formalize the mechanism for determining which function to call by making some property-extracting objects:

abstract class PropertyExtractor {
    public abstract function getProperty($group);
}

class SumTotalExtractor extends PropertyExtractor {
    public function getProperty($group) {
        return $group->getSumTotal();
    }
}

class SumCountExtractor extends PropertyExtractor {
    public function getProperty($group) {
        return $group->getSumCount();
    }
}

Your buildChartGroups() would take one of those extractors as the second parameter:

private function buildChartGroups(PropelCollection $groups, $propertyExtractor) {
    $chart = array();
    foreach ($groups as $group) {
        $chart[] = array('name' => $group->getName(),
                         'y' => $propertyExtractor->getProperty($group));
    }
    return $chart;
}

Here it is in use:

$result = $this->buildChartGroups($groups, new SumTotalExtractor());


private boolean isBloomFilterExistsByName(String name)
{

The brace belong on the previous line.

isBloomFilterExistsByName(String name)

is...Exists sounds strange.

 private void newBloomFilter(String name)

From the name, I'd expect this method to return a new Bloom Filter instead of putting it somewhere.

 private void NotExistsThenPut(String name)

Java method names starts with lowercase. A better name would be putIfNotExists.

I'd actually prefer a method like getOrCreate.

public boolean contains(String name, String key)

contains and isPresent are wrong names for this. A Bloom Filter is like a Set, but an undependable one. A much better name is mayContain.

This method is an invitation to inefficiency. Imagine a tight loop calling it. On every iteration you look up the Bloom Filter twice (once to make sure that it exists and once to use it). This may easily dominate the cost of the filter's isPresent operation.

I'd suggest to provide methods allowing to use it like

 bloomFilterInCache.getOrCreate("name").mayContain("element");

which allows efficiency via "extract local variable".

 public void add(String name, String key)

Again, an invitation to inefficiency.


Nested LINQ Nightmare, calculating %completed

Break it down into more methods. StudentTracks has multiple responsibilities, you could extract a private method whose job would be to CalculatePercentCompletion(studentTrack), making your method look like this:

public IQueryable<StudentTrack> StudentTracks(int employeeId)
{
    IQueryable<StudentTrack> EducationPortalStudentTracks =
        from studentTrack in _dbContext.EducationPortalStudentTracks
        join track in _dbContext.EducationPortalTracks on studentTrack.TrackId equals track.Id
        orderby track.Id
        where studentTrack.EmployeeId == employeeId
        select new StudentTrack
        {
            Id = studentTrack.Id,
            TrackId = studentTrack.TrackId,
            Name = track.Name,
            Deadline = studentTrack.Deadline,
            PercentComplete = CalculatePercentCompletion(studentTrack)
        };

    return EducationPortalStudentTracks;
}

Then CalculatePercentCompletion could look like this:

private int CalculatePercentCompletion(StudentTrack studentTrack)
{
    return (from doesntMatter in _dbContext.EducationPortalStudentCourses
            let courses = (from studentCourse in _dbContext.EducationPortalStudentCourses
                           join studentTrack_ in _dbContext.EducationPortalStudentTracks on studentCourse.TrackId equals studentTrack_.TrackId
                           where studentTrack.Id == studentTrack.Id && studentTrack.EmployeeId == studentCourse.EmployeeId
                           select studentCourse)
            select courses.Where(x => x.Status == true).Count() * 100 / courses.Count()).FirstOrDefault();
}

...Which is still horrible.

Why are you using the query syntax? If you have navigation properties on your entities (assuming EF), I find this would be much easier to parse:

public IQueryable<StudentTrack> StudentTracks(int employeeId)
{
    return _dbContext.EducationPortalStudentTracks
                     .Where(studentTrack => studentTrack.EmployeeId == employeeId)
                     .OrderBy(studentTrack => studentTrack.Track.Id)
                     .Select(studentTrack =>
                         new StudentTrack
                         {
                             Id = studentTrack.Id,
                             TrackId = studentTrack.TrackId,
                             Name = studentTrack.Track.Name,
                             Deadline = studentTrack.Deadline,
                             PercentComplete = CalculatePercentCompletion(studentTrack)
                         });
}

In CalculatePercentCompletion the doesntMatter part makes it pretty confusing, I'm not sure but I think this could be equivalent:

private int CalculatePercentCompletion(StudentTrack studentTrack)
{
    var courses = _dbContext.EducationPortalStudentCourses
                            .Where(course => course.TrackId == studentTrack.Id
                                          && course.EmployeeId == studentTrack.EmployeeId)
                            .ToList();
    return courses.Count(course => course.Status == true) * 100 / courses.Count
}

Why the .ToList() call? You want to materialize your query only when you need to - this method needs to know what the courses are for a given studentTrack, in order to count the number of courses with Status == true, multiply that by 100 and divide by the total number of courses.

Your code iterates courses twice, in the two Count() calls.

And the intent is not exactly clear because of the doesntMatter in the from clause, and the .FirstOrDefault() call makes it look like we're looking at an IEnumerable<int> when we're really all materialized at that point and we either have zero or one values selected (if I get this correctly).

The status == true part is confusing. Normally I would have written it as .Where(course => course.Status) to avoid comparing a Boolean with a Boolean value, but Status is really a poor name and doing that would have made it harder to understand what's going on. I suggest you rename Status to whatever IsCompleted, so the where condition can read as .Where(course => course.IsCompleted), which is crystal-clear.

I think exposing IQueryable<T> to your UI is a bad idea. StudentTracks should return an IEnumerable<StudentTrack> instead, your grid should be able to work off that just as well.

I would leave the last Select to Linq-to-Objects, and materialize the query just after the OrderBy call:

public IEnumerable<StudentTrack> GetStudentTracks(int employeeId)
{
    return _dbContext.EducationPortalStudentTracks
                     .Where(studentTrack => studentTrack.EmployeeId == employeeId)
                     .OrderBy(studentTrack => studentTrack.Track.Id)
                     .ToList()
                     .Select(studentTrack =>
                         new StudentTrack
                         {
                             Id = studentTrack.Id,
                             TrackId = studentTrack.TrackId,
                             Name = studentTrack.Track.Name,
                             Deadline = studentTrack.Deadline,
                             PercentComplete = CalculatePercentCompletion(studentTrack)
                         });
}

The problem with exposing IQueryable<T> to your client code, is that you allow that code to modify the SQL being generated, and potentially to break your query with calls that Linq-to-Entities cannot translate to SQL. The grid in your UI doesn't need an IQueryable<T>.


Let's have async implementation:

async def async_next(url):
    if url is None:
        return

    try:
        response = await async_send(url)
        return response.json()
    except HTTPError as e:
        if e.response.status_code == 404:
            return
        else:
            raise

Then you can provide following sync bridge:

def next(url):
    return asyncio.run(async_next(url))

Or the following if the event loop is available and running:

def next(url):
    return loop.run_until_complete(async_next(url))

Note: check asyncio high level commands for more details


Python - Activity Selection - Greedy Algorithm

Code readability and style -

I believe that good code should have good style and should be more readable and concise.

Let's introduce you to f-strings -

  To create an f-string, prefix the string with the letter “ f ”.
  The string itself can be formatted in much the same way that you would
  with
  str.format().
  f-strings provide a concise and convenient way to embed python
  expressions inside string literals for formatting.

Which means, instead of using the outdated way of formatting strings -

print(ls, '>>>', len(ls), 'out of', len(pair), 'activities.')

You could make it more concise -

print(f'{ls} >>> {len(ls)} out of {len(pair)} activities.')

NOTE - Requires Python 3.6 and above.

If you don't have Python 3.6 and above, you could use str.format() -

  str.format() is one of the string formatting methods in Python 3, which
  allows multiple substitutions and value formatting. This method lets
  us concatenate elements within a string through positional formatting.

So you could write it like this -

print('{} >>> {} out of {} activities.'.format(ls, len(ls), len(pair)))

I would also put your code into a function -

  A function is a block of organized, reusable code that is used to
  perform a single, related action. Functions provide better modularity
  for your application and a high degree of code reusing.

  As you already know, Python gives you many built-in functions like
  print(), etc. but you can also create your own functions. These
  functions are called user-defined functions.

With this as the function name -

def activity_selection():

You should also consider using an if __name__ == '__main__': guard, like this -

if __name__ == '__main__':
    activity_selection()

Your variables should be more descriptive -

ls = list()

could be -

activity_list = list()

So, overall, your code would then look like this (in terms of code readability and style) -

import random
import operator

def activity_selection():
    begin = [random.randint(1, 10) for i in range(10)]
    end = [x + random.randint(1, 4) for x in begin]
    pair = sorted(list(zip(begin, end)), key=operator.itemgetter(1))
    activity_list = list()
    activity_list.append(pair[0])
    for i in pair[1:]:
        if i[0] >= activity_list[-1][1]:
            activity_list.append(i)
    print(f'{activity_list} >>> {len(activity_list)} out of {len(pair)} activities.')
    # or
    # print('{} >>> {} out of {} activities.'.format(activity_list, len(activity_list), len(pair)))

if __name__ == '__main__':
    activity_selection()

To remain concise and immaculate in writing Python programs, I suggest you have a look at PEP 8, which is Python's official style guide.

Hope this helps!


Just reviewing brute_force.

There's no docstring.
There's no need to write comments if they just repeat what it says in the code:

sep = float('inf')  # set the initial minimum to infinity

Use comments to explain things that are hard to deduce from reading the code.
The special case for n < 2 is unnecessary. If n is less than 2, then the loop over i will be empty and no pairs will be tested.
There are some superfluous parentheses. In Python the comma operator has higher precedence than assignment, and so, instead of:

pair = (xpoints[i], xpoints[j])

you can write:

pair = xpoints[i], xpoints[j]

The expression abs(xpoints[i] - xpoints[j]) gets computed twice in some cases: this could be avoided by storing the result in a local variable.
When looping over the distinct pairs of a sequence, use itertools.combinations, like this:

from itertools import combinations

def brute_force(points):
    """Find the pair (p, q) in the sequence points with the closest
    separation. Return the tuple (separation, (p, q)).

    """
    sep = float('inf')
    pair = None, None
    for p, q in combinations(points, 2):
        pq_sep = abs(p - q)
        if pq_sep < sep:
            sep = pq_sep
            pair = p, q
    return sep, pair

This could be turned into a single expression using min and operator.itemgetter:

from itertools import combinations
from operator import itemgetter

def brute_force(points):
    """Find the pair (p, q) in the sequence points with the closest
    separation. Return the tuple (separation, (p, q)).

    """
    return min(((abs(p - q), (p, q)) for p, q in combinations(points, 2)),
               key=itemgetter(0), default=(float('inf'), (None, None)))

(This needs to be Python 3.4 or later since it uses the default keyword argument.)

Not everyone finds this style of programming readable, so it would be totally reasonable to stop with the version in §6 above and not try to squash everything into a single expression.


Parse a config-file and add to command-line-arguments using argparse in Python

You don't need a class

In your current version of the code, it is hard to see what is stored in an instance and how the data flows around the different methods. If you do write a class, I find it clearer to have an init to define the different members but in your case, you could stop writing classes.

Removing the class, you get something like :

def execute():
    pprint(parse_args(create_parser()))

def create_parser():
    parser = argparse.ArgumentParser()

    g = parser.add_argument_group('Device Targets')
    g.add_argument(
        '--config-file',
        dest='config_file',
        type=argparse.FileType(mode='r'))
    g.add_argument('--name', default=[], action='append')
    g.add_argument('--age', default=[], action='append')
    g.add_argument('--delay', type=int)
    g.add_argument('--stupid', dest='stupid', default=False, action='store_true')
    return parser

def parse_args(parser):
    args = parser.parse_args()
    if args.config_file:
        data = yaml.load(args.config_file)
        delattr(args, 'config_file')
        arg_dict = args.__dict__
        for key, value in data.items():
            if isinstance(value, list):
                for v in value:
                    arg_dict[key].append(v)
            else:
                arg_dict[key] = value
    return args

execute()

The name execute probably needs to be improved for something more meaningful.

The right tool for the job

To add all the content from value to arg_dict[key], you shouldn't use àppend but extend.

        if isinstance(value, list):
            arg_dict[key].extend(value)
        else:
            arg_dict[key] = value


I think this is one of the few "Sieves of Erosthenes" that actually implements the sieving method; congratulations! ^_^

Run rustfmt:

Spaces go around binary operators:

let mut all: Vec<u32> = (2..max + 1).collect();

vec! should always be called with square brackets:

let mut primes: Vec<u32> = vec![];

There's no comma after the curly brace of a match arm.

Run Clippy:

warning: length comparison to zero
  --> src/main.rs:13:11
   |
13 |     while all.len() > 0 {
   |           ^^^^^^^^^^^^^ help: using `is_empty` is more concise: `!all.is_empty()`
   |
   = note: #[warn(len_zero)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#len_zero

You are declaring types way more frequently than you need to. Type inference can handle most of these cases. Other times, you can let the compiler infer a part of the type, such as with collect: let foo: Vec<_> = iter.collect().
Converting a Vec to an iterator, popping one element, then converting back to a Vec is expensive. Instead, just get the first element of the input using the index operator (foo[0]).
Once you've done that, you might as well just pass in a mutable reference to the list to avoid taking ownership of the list and passing back ownership and dealing with the tuple output.
Once you've done that, there's no reason to pass in the whole prime list just to append to it and get it back. Instead, return the new prime number from the function and append it later.
Use your function comments to enhance your function names, instead of them being dead text warning about how to call them ("non empty list").
Your desire to avoid unwrap is well-founded. Your code crashes if run with 1 as the argument. To properly format a comma-separated list, check out What's an idiomatic way to print an iterator separated by spaces in Rust? and In Rust, what is the best way to print something between each value in a container. TL;DR: use Itertools::format.
Using {:} as the format specifier is very unusual — I had to think hard about what it even meant. You should use just {}.
Don't take a Vec if you are just going to iterate over it.
Don't explicitly mark () as the return type of a function, that's the default.
Instead of collecting your arguments into a vector, just grab the single argument you care about using Iterator::nth.

extern crate itertools;

use itertools::Itertools;

use std::env;

fn primes_to(max: u32) -> Vec<u32> {
    let mut all: Vec<_> = (2..max + 1).collect();
    let mut primes = vec![];

    while !all.is_empty() {
        primes.push(sieve_non_empty_list(&mut all));
    }

    primes
}

fn sieve_non_empty_list(list: &mut Vec<u32>) -> u32 {
    let head = list[0];
    list.retain(|&x| x % head != 0);
    head
}

fn prettyprint_primes(primes: &[u32]) {
    print!("{}", primes.iter().format(", "))
}

fn main() {
    let arg = env::args().nth(1);

    match arg {
        None => {
            println!("Please enter a number to receive primes.");
            println!("Usage:");
            println!("\ttoPrime x");
        }
        Some(x) => {
            match x.parse() {
                Ok(max) => {
                    let primes = primes_to(max);
                    prettyprint_primes(&primes);
                }
                _ => println!("That's not a number; please enter a number"),
            }
        }
    }
}

I'd probably implement the sieve as an iterator, however. This has the effect of removing the need to store the primes (the caller can do so if needed), allowing the caller to get the next prime back quicker, and encapsulates the state of the list so we don't need to document that you can only call functions in certain states.

struct Sieve {
    list: Vec<u32>,
}

impl Sieve {
    fn new(up_to: u32) -> Self {
        Self {
            list: (2..up_to + 1).collect(),
        }
    }
}

impl Iterator for Sieve {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        let val = self.list.get(0).cloned();

        if let Some(head) = val {
            self.list.retain(|&x| x % head != 0);
        }

        val
    }
}

And it can be printed directly as:

let primes = Sieve::new(max);
print!("{}", primes.format(", "))


I am generally impressed with the consistency of the implementations, neatness, etc.

I have a comment about the basic premise. The Shape should not be an abstract class, but an interface. It has no concrete implementations for any methods, and making it an abstract class makes it hard to inherit from other places too. Consider this instead:

public interface Shape {
    public double area();
    public double perimeter();
}

In addition to that concern, the following are also things you should consider:

The pi field on your Circle class should be private. There's no need to re-expose an already public constant in another way.
I would avoid the 'unit' default constructors. They don't help with anything. When would someone want to call new Triangle() and not want to have the dimensions?
Your classes are missing a toString() method. These are useful for many reasons, especially debugging.
You don't have a plan for out-of-bound dimensions. What will you do with negative, NaN, or infinite input?


In this case I would go the regex route. Your code is basically saying: Anything that parses as a digit is fine, just so long as everything is a digit, and at least one of them is not zero.

Express that as a regular expression:

private static final Pattern validEmployeeNumber = Pattern.compile("^[0-9]*[1-9][0-9]*$");

Then your function becomes:

private static final Pattern validEmployeeNumber = Pattern.compile("^[0-9]*[1-9][0-9]*$");

private static boolean employeeNumberCheck(String employeeNumber){
    return validEmployeeNumber.matcher(employeeNumber).matches();
}

See it running in ideone


Simple streaming parser to extract columns

You can use the Microsoft.VisualBasic.FileIO.TextFieldParser and attach the serial port to a StreamReader and use that as input for the TextFieldParser.


First off: Apologies for the shortness of this review. There's not much code, after all.

You've got a bit of inconsistent style with whitespace after your cases -- I haven't done Scala in a while, but if I'm remembering right, you're supposed to have a space after.

I'd recommend renaming i and s to i1 and s1, respectively, just to be consistent.

Your 'spec' says that "a" plus "b" should return "a and b = ab", but it actually returns "a and b". Personally, I think it should return "ab", a la string concatenation.

Using Any is not a code smell, though some error throwing may be in order if any types other than Int or String are used, so that if I call 1.0 plus "a", I don't just get nothing. It's up to you which type to use, though personally I'd use an IllegalArgumentException.

Aside from that, it looks good! Well done.


I want to know how I could make the method look prettier, and have better 'coding practices' though

avoid single letter variable if they aren't iterator variables. If you or Sam the maintainer needs to come back to this method in a few months, neither you nor Sam will grasp at first glance what the variables are about.
avoid shortening of method names. polyCheck does not tell anything about what the method tries to do. A name like IsInPolygon would be better. With a more OO approach by adding a Polygon class having a method Contains(Vector2) it would be more clear.

public class Polygon
{
    public Vector2[] Vertices { get; private set; }
    public Polygon(Vector2[] vertices)
    {
        Vertices = vertices;
    }
    public bool ContainsVector(Vector2 vector)
    {
        // do the magic
        return true;
    }
}

always use braces {} although they are optional for single lined for's. This will help you to make your code less error prone.
let your variables and operators have some space to breathe. This

c^=p[i].y>v.y^p[j].y>v.y&&v.x<(p[j].x-p[i].x)*(v.y-p[i].y)/(p[j].y-p[i].y)+p[i].x;

is just not readable.


Collecting adjacent cells in a 2D grid implemented as a 1D list

Looks good, ship it.

Certainly cols is an accurate name, but in this context sometimes people prefer to refer to it as stride.

It's close to the initial default, but still, since you know the max size you might specify a capacity: new ArrayList<>(8);

Modulo can be slightly expensive. Maybe you want to assign the result to a temp variable, or maybe you trust that JIT already did that for you.

The sequential memory references to {l&u, u, u&r} are cache friendly. The reverse sequence of addresses, {r&d, d, d&l} is perhaps backwards from what you prefer.


Passing argument to a constructor and using it only in some class methods

As far as I can see in the code example you've provided, it seems that the getStatistics and recordClickedLink methods are independent of each other. So it seems intuitive to have in this case two controllers: a StatisticsController and a something like a RecordController where the two methods recordClickedLink and canRecordClick live. In that way the StatisticsController is responsible for statisics and the RecordController for the record.

It is ok that the class contains canRecordClick, but protected means that any class extending the StatisticsController will be able to call this method too. If it will only be used in the StatisticsController, private would be better.


Need to pass cookie information to a child iFrame - Are there any security concerns?

My Answer (best guess)

Tag is correct, out of security concer i would still not pass the session id as parameter(only if there is no other way)
It makes it harder to tamper with, if it is httplony see wikipedia
Links with sessionids could be bookmarked and after the end of the session they wont work, or they could beforwarded, and sesssions could be passed/shared, ...

Btw.: i found this link https://security.stackexchange.com/questions/14093/why-is-passing-the-session-id-as-url-parameter-insecure covering more or less the same topic.

I hope it helps


Returning Early

You can remove one level of nesting, and make your code generally easier to understand by returning early:

if (headerUserAgent == null) {
    return null;
}

Now it's also more obvious what happens if the agent is null. But is returning null really what you want? It will lead to a lot of if (agent == null) in the calling code. I would suggest throwing an exception instead. Java also has a nice utility method for this:

Objects.requireNonNull(headerUserAgent, "User Agent is Null");

(This method should be used if the agent being null is not expected. If you do expect it, because it's part of your program logic, this might not be the best approach)

Bugs

Your code doesn't work for quite a lot of input:

empty string, , ua, etc as input results in a NullPointerException.
Some Firefox user agents also result in NullPointerException, eg Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0.
You can see a list of some possible IE user agents here. I tried some of them, and a lot result in exceptions, such as Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US)), which should be IE 9, Mozilla/5.0 (MSIE 7.0; Macintosh; U; SunOS; X11; gu; SV1; InfoPath.2; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648) which should be IE 7, or Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1) which should be IE 10 (or 00 in your case).

Misc

Your placement of the { is not really following Java conventions.
Some of your variable names could be more descriptive, eg x and y.
Variables should start with a lower-case character.
You have an unnecessary ;.
A JavaDoc style comment describing the exact return values might be a good idea, especially since the method name is a bit confusing (it doesn't always return the version, but 00 for compatibility mode).


Try using a SVG object on the canvas:

<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse">
            <path d="M 8 0 L 0 0 0 8" fill="none" stroke="gray" stroke-width="0.5" />
        </pattern>
        <pattern id="grid" width="80" height="80" patternUnits="userSpaceOnUse">
            <rect width="80" height="80" fill="url(#smallGrid)" />
            <path d="M 80 0 L 0 0 0 80" fill="none" stroke="gray" stroke-width="1" />
        </pattern>
    </defs>

    <rect width="100%" height="100%" fill="url(#smallGrid)" />
</svg>

produces a grid like this:

whereas changing fill="url(#smallGrid)" to fill="url(#grid)" produces the following:

Which then you can feed into the canvas like the following:

var drawGrid = function(w, h, id) {
    var canvas = document.getElementById(id);
    var ctx = canvas.getContext('2d');
    ctx.canvas.width  = w;
    ctx.canvas.height = h;

    var data = '<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"> \
        <defs> \
            <pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse"> \
                <path d="M 8 0 L 0 0 0 8" fill="none" stroke="gray" stroke-width="0.5" /> \
            </pattern> \
            <pattern id="grid" width="80" height="80" patternUnits="userSpaceOnUse"> \
                <rect width="80" height="80" fill="url(#smallGrid)" /> \
                <path d="M 80 0 L 0 0 0 80" fill="none" stroke="gray" stroke-width="1" /> \
            </pattern> \
        </defs> \
        <rect width="100%" height="100%" fill="url(#smallGrid)" /> \
    </svg>';

    var DOMURL = window.URL || window.webkitURL || window;

    var img = new Image();
    var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
    var url = DOMURL.createObjectURL(svg);

    img.onload = function () {
      ctx.drawImage(img, 0, 0);
      DOMURL.revokeObjectURL(url);
    }
    img.src = url;
}
drawGrid(800, 400, "grid");
<canvas id="grid"></canvas>

Of course, you'll need to play around with the sizes of the grid to match what you want. However you'll find that this method is much faster.


Since it looks like you don't wait for a specific length of data I assume that you have no idea how to get the length of the data up-front. Since you are willing to learn how HTTP/1.x works I recommend you to read the specifications and watch out for something like "Content-length" and "Transfer-Encoding: chunked". Once you've understood why these are important and how to correctly deal with them you can write your code so that it does not timeout.


Try something like this:

if (now.getTime() < boise.date.getTime() ) {
    banner.attr('src', imgDir+boise.img+'.jpg');
}
.....

In total,

var now = new Date();
    objs = {
        // here I change your 12 variables to a single object, so I can loop over them
        boise : { date: new Date ('May 15, 2012'), img: 'Boise' },
        central : { date: new Date ('May 21, 2012'), img: 'Central' },
        notreDame : { date: new Date ('May 27, 2012'), img: 'NotreDame' }
    },
    banner = $('#nextGameBanner'),
    imgDir = 'images/nextGame';

// making loop with objs

$.each(objs, function(key, singleObj) {
   // compare time with now and stored time in object
   if (now.getTime() < singleObj.date.getTime() ) {
     // assigning src to image when the condition satisfied
     banner.attr('src', imgDir+ singleObj.img +'.jpg');
     break; // stop the loop when match found
   }
});

read about getTime()


The thread that calls it will likely be the UI Thread.

You're invoking Task.WaitAll which waits for the processing to finish.
However you said, "... I don't want any of the callers to wait while the processing is happening (either for the processing to happen or while the processing is happening)."
Is this a contradiction?
Instead of creating short-lived tasks as a local variable inside a semaphore, perhaps it would be better to:

Create a single long-lived task (e.g. as a data member of your class)
Wake up the task when you enqueue something or fix a ProcessQueueItems problem (perhaps by setting a event which the task is waiting on)
Don't invoke Task.WaitAll until your program is shutting down
Put an exception handler inside the task so that the (single, supposedly long-lived) task can't permanently fail if one ProcessQueueItem call throws an exception

It is a custom type of mine. Has a few native types and a dictionary.

It needs to be a type like ConcurrentQueue<T> because you have one thread (the task) dequeueing from it while (presumably) other threads are enqueueing on it.


Checks size of and number of files in each subdirectory

edit: I just realized, that you're using python2. I'm very unfamiliar with that and if you'll be able to use yield from, pathlib and format string literals. If you like the solution, I think I could rewrite it to be usable for python2.

Solution for python 3.6 and up (of that, I am very confident that it will produce no error):

Instead of creating all your information within one function, you can reduce the nesting depth by pulling up some of the functionality.

from pathlib import Path

def folders_in_path(path):
    if not Path.is_dir(path):
        raise ValueError("argument is not a directory")
    yield from filter(Path.is_dir, path.iterdir())

def folders_in_depth(path, depth):
    if 0 > depth:
        raise ValueError("depth smaller 0")
    if 0 == depth:
        yield from folders_in_path(path)
    else:
        for folder in folders_in_path(path):
            yield from folders_in_depth(folder, depth-1)

def files_in_path(path):
    if not Path.is_dir(path):
        raise ValueError("argument is not a directory")
    yield from filter(Path.is_file, path.iterdir())

def sum_file_size(filepaths):
    return sum([filep.stat().st_size for filep in filepaths])

if __name__ == '__main__':
    for folder in folders_in_depth(Path.cwd(),1):
        #       vvvv quick hack to to use len(), does not perform well
        files = list(files_in_path(folder))
        total_size = sum_file_size(files)
        print(f'{folder}: filecount:{len(files)}, total size:{total_size}')

which produces:

/tmp/Parent/FolderB/subfolder3: filecount:10, total size:50
/tmp/Parent/FolderB/subfolder2: filecount:10, total size:50
/tmp/Parent/FolderB/subfolder1: filecount:10, total size:50
/tmp/Parent/FolderA/subfolder3: filecount:10, total size:50
/tmp/Parent/FolderA/subfolder2: filecount:10, total size:50
/tmp/Parent/FolderA/subfolder1: filecount:10, total size:50

if your cwd is Parent.
This will only count files in that are in a subdirectory at depth == 1 and nothing else.

There might be some neater solutions, that's just what I came up with in a few minutes.

edit2: I was curious, so I did a 2.7 version. os.walk is using depth first search. From what I gather, it could be done like this:

import os

def folders_in_depth(path, depth, walk_iter=None):
    if walk_iter is None:
        walk_iter = os.walk(path)
    if 0 > depth:
        raise ValueError("depth smaller 0")
    if 0 == depth:
        dirpath, dirnames, filenames = next(walk_iter)
        for i in range(len(dirnames)):
            dirpath, dirnames, filenames = next(walk_iter)
            yield dirpath, filenames
    else:
        dirpath, dirnames, filenames = next(walk_iter)
        for i in range(len(dirnames)):
            for result in folders_in_depth(path, depth-1, walk_iter=walk_iter):
                yield result

def sum_file_size(folder, filepaths):
    return sum([os.path.getsize(folder + '/' + filep) for filep in filepaths])

if __name__ == '__main__':
    for folder in folders_in_depth(os.getcwd(),1):
        foldername, files = folder
        print foldername,': filecount:', len(files), ', total size:', sum_file_size(foldername,files)

which results in

/tmp/Parent/FolderB/subFolderB3 : filecount: 10 , total size: 50
/tmp/Parent/FolderB/subFolderB2 : filecount: 10 , total size: 50
/tmp/Parent/FolderB/subFolderB1 : filecount: 10 , total size: 50
/tmp/Parent/FolderA/subFolderA3 : filecount: 10 , total size: 50
/tmp/Parent/FolderA/subFolderA2 : filecount: 10 , total size: 50
/tmp/Parent/FolderA/subFolderA1 : filecount: 10 , total size: 50

Not sure, where the extra spaces come from.

Here, the iterator is passed down in the recursion and has to be forwarded with next to produce the correct result.

Caveat: I think, this 2.7 solution will not work if the 'subFolder*' contain more folders on their own. Judging from how os.walk is implemented, modifying that solution might be the best option, so you don't have to worry about that. (sadly I was looking at how 3.6 implements os.walk, which is a little more complicated)

So for this to work correctly, you'd have to forward the iterator through the complete sub-tree, which is completely unneccesary.
os.walk allows to modify the returned dirname to control where it should recurse via side effects. So clearing that might lead to the wanted result, you'd need to test that.


Functions in C with no parameters should have a void parameter:

int main(void)

Variables should be declared/initialized on separate lines:

int a;
int b;
int c;
int d;
int sum3;
int sum5;
int sum15;
int total_sum;

Try to avoid single-character variable names.  They're very ambiguous and say nothing about the variable's purpose.  The only valid exception to this is loop counter variables.
Statements/blocks of different purposes should be separated to increase readability.  That would be the divisions, the sums, and the printf().
Your operands should be spread out to make the lines more readable:

sum3 = b * (3+999) / 2;

Initializations should be done as late as possible to help aid in maintenance:

sum3 = b * (3+999) / 2;

Remove int a since it's never used.


Perhaps consider building an array of path segments through your logic and then setting page with it.

app.get('/*', function (req, res) {
  var page
  var base = req.params[0]
  var baseExtension = path.parse(base).ext
  // determine path segments
  var pathSegments = [__dirname]
  if (base !== '') {
    pathSegments.push(base)
  }
  if (baseExtension === '') {
    pathSegments.push('index.html')
  }

  // set page
  // here we use spread operator
  page = path.parse(path.join(...pathSegments))
  // if not using ES6, you could alternatively use
  // page = path.parse(path.join.apply(pathSegments))

  // perhaps consider switch here instead of if-else if you are going
  // to have more than just html and css extension types
  if (page.ext === '.html') {
    /*... do html stuff ...*/
  }
  else if (page.ext === '.css') {
    /*... do css stuff ...*/
  }
  /*...*/
})

Be consistent on your usage or non-usage of semicolons to end lines of code.  It seems like you have chosen to use the no semi-colon style, so why is there one after var page;?


Remove nth node from last position in linked list

You failed to solve the "try to do this in one pass" part, as you iterate through the list once to find the total size and a second time to find the nth element from the start.

The algorithmic idea is, to use two pointers into the list:

Initialize poiner1 to head, advance n times (if n is the distance from the tail you seek)
Then, initialize pointer2 to head, advance both pointers, until pointer1 is null, i.e. reached the end of the list.
Now, pointer2 should point to the end-nth element

Removal as usual.


How to make this ASP.NET MVC ViewModel population query efficient?

It's hard to tell exactly how to write this query without knowing exactly what your datamodel look like and how you've set it up. An assumption was made you're using Linq 2 SQL, I'll adhere to that assumption unless we hear otherwise. You can eagerly fetch other tables if you tell linq to sql to do so. You use the Include method for that.
If you've set up your datamodel correctly, you should be able to create a query that resembles this:
string userName = User.Identity.Name;
List<RequestExecutionViewModel> = (from request in db.Requests.Include("Requests.ExecutionStatus").Include("Requests.Rules.Approvals");
    where  request.UserName == userName
    select new RequestExecutionViewModel(){
        Request = request,
        ExecutionStatus = request.ExecutionStatus,
        Approvals = request.Rule.Approvals
    }).ToList();

And as you can see, this query instructs Linq-to-SQL to eagerly fetch the to related tables and then uses them in the output shaping process to create your viewmodel directly..
Make sure you look at the profiler to see that this is actually resulting in one query. Linq-to-SQL can at any time decide to loop over the subresults by itself.


In your example code you have the following synchronization-related statements:

this.buySell = Collections.synchronizedList(new ArrayList<BuySell>());
synchronized (buySell) {
synchronized (this) {

As a consequence, you are synchronizing on three different things in one class.

This is very confusing, and is buggy.

You are onlu showing us part of your class, but, there is no point in making buySell a synchronizedCollection if you are going to also gate access to it using synchronized(buySell).... it is redundant, and introduces 2 levels of synchronization.

Presumably when you calculate interest you also access the buySell class, and, as a consequence you have two levels of synchronization there too.

A deadlock is a situation where two threads each have a lock, and they each attempt to get another lock where that other lock is being held by the other thread. If you have multiple lock points in your class it becomes much easier to code things where you introduce deadlock possibilities. I cannot see any in your code at the moment, but your code is incomplete, and these are bugs that can creep in as the class is maintained.

The safest way to do things is to have just a single object which you use to cate access to your class. It is often tempting to use the actual instance itself as the gate, make every method synchronized, and, if you did, your class would become:

public class RetirementAccount {

    public static final int TYPE1 = 0;
    public static final int TYPE2 = 1;

    private final int accountType;
    public final List<BuySell> buySell;

    public RetirementAccount(int accountType) {
       this.accountType = accountType;
       this.buySell = new ArrayList<BuySell>();
    }

   public synchronized void addToAccount(double amount) {
       if (amount <= 0) {
            throw new IllegalArgumentException();
       } else {
            buySell.add(new BuySell(amount));
       }
   }

   public synchronized double interestGained() {

        switch (accountType) {
                …..
   }

This would be a thread-safe class, and it has just one synchronization lock point (the class instance itself). There is no internal possibility of any deadlock, and it would be much better than what you have.

There is a better solution though....

The problem with the above solution is that you expose the locking system in the instance and make it public. Anyone can do:

synchronized(myaccount) {
    ....
}

and they essentially become a prt of your locking system, and that can result in lock-conditions that are unexpected when you created your class.

To make the class completely thread-safe, and have just a single lock point, and still keep isolated from the out-side, I recommend using a dedicated lock instance. It typically looks like this....

public class RetirementAccount {

    public static final int TYPE1 = 0;
    public static final int TYPE2 = 1;

    private final int accountType;
    public final List<BuySell> buySell;
    private final Object synclock = new Object();

    public RetirementAccount(int accountType) {
       this.accountType = accountType;
       this.buySell = new ArrayList<BuySell>();
    }

   public void addToAccount(double amount) {
       synchronized (synclock) {
            if (amount <= 0) {
                throw new IllegalArgumentException();
           } else {
                buySell.add(new BuySell(amount));
           }
       }
   }

   public double interestGained() {

       synchronized (synclock) {

            switch (accountType) {
                …..
       }
   }

Synchronization and other locking mechanisms are complicated concepts, and they are hard to write, and hard to read. There are rules which make it easier:

discipline - you have to create a system, and you have to follow it diligently
dependence - use prefabricated classes where you can (java.util.concurrent.* is your friend) .... but understand what those classes do. Just because one instance is safe, it does not mean your system is safe. They do not solve all problems.
discipline - you have to create a system, and you have to follow it diigently
use as few locks as possible - the fewer locks you have to mentally track, the better.
discipline - you have to create a system, and you have to follow it diigently
avoid places where you have double-locking - you synchonize against one class, then synchronize against another. These double-locking situations are a precursor to deadlocks (they add risk).
discipline - you have to create a system, and you have to follow it diigently
avoid synchronizing classes with synchronized methods because that leads to conditions where outside influences can affect the internal locking of your instance.
discipline - you have to create a system, and you have to follow it diigently

Did I mention that successful thread-safe implementations require discipline? You have to be diligent about implementing the synchronization correctly at each place it is needed.

Finally, there are ways you can force thread-safe operation with light versions of locking. My general advice to people is "don't try to be clever unless you really are that clever". It takes a special kind of brain to understand all the nuances of Java's memory moela nd the way the threading affects it. If you have it clear in your mind, then sure, play some tricks.... but, even those who have i clear, mess up when they try to be clever.