Best practice for factory pattern in c++?

I’ll start by answering the questions.
Questions

Is the usage of factory pattern here justified ?

Going just by what’s visible in the code and your commentary, I don’t see any purpose to writing the code this way. I don’t see any purpose to the RosBagDataReader or CameraDataReader classes. They don’t actually do anything unique; you could just implement get_next_frameset() in the base class, and forget the whole hierarchy.
In fact, the only difference at all between the classes is not what they do, but rather how their data is set up. I suppose you could sorta-kinda justify having different classes to handle the different types of initialization… but then, you should put the initialization in the classes—that is, in the constructors. However, you could just as easily use two constructors for DataReader, and again, forget the rest of the hierarchy.
But the thing that really makes me scratch my head about why you’d want to use the factory pattern is the fact that you don’t even really have a single factory. You have two factories that you’ve just shoehorned into one by saying “go one way if there’s a path, the other way if not”. That shouldn’t be a single function; that’s poor design. That should be two functions, one taking a path, one not. And once you’ve done it that way, it kinda reveals that the factory pattern doesn’t really make sense here.
Frankly, run-time polymorphism should always be the last tool you reach for in modern C++:

It relies on reference semantics, and C++ is a value semantic language.
It usually means you need to use dynamic allocation, which is slow, cumbersome, and error-prone (though smart pointers help).
It doesn’t really work well with compile-time stuff like type-checking and constexpr… which, again, are C++’s strengths.
It’s often less efficient because of the extra memory used, and extra indirection.
And there are all kinds of nasty gotchas just waiting to bite your ass (like, slicing if you aren’t VERY careful writing copy ops, swap ops, and so on).

HOWEVER….
Of course, there are situations where the factory pattern using run-time polymorphism is the perfect solution. One that springs to mind is the case where you’re writing a library: you’d only give DataReader and the factory function as the entire library interface, and client code can use the library without knowing any details about possible concrete readers, so you could swap them out without having to recompile the client. You could even add readers as plugins.
If you were doing that kind of thing, then sure, the factory pattern makes sense. But… if you’re just writing a program—not a library, let alone an extensible library—then I don’t see the point of it.

Is my implementation of factory pattern correct ? Or are there any pitfalls in the code ?

Eh, it’s mostly okay. It’s not outright wrong, but… there are a few problems with doing things the way you’re doing them.
The first issue is that you don’t seem to know whether you’re writing an interface hierarchy, or an implementation hierarchy. Those are two very different things, and they need to be handled in different ways. If you are trying to build from an interface—in this case, the single function get_next_frameset()—then your base class should be a pure abstract class… what other languages like Java specifically call an interface: no data, only pure virtual functions. If you are building up an implementation, then you’d do things very differently.
I can’t tell you which one you’re really doing here, because, frankly, you don’t have much of an interface or implementation hierarchy, and none of the commentary explains any of the reasoning for even wanting the factory pattern in the first place. As I noted earlier, there doesn’t really seem to be much justification for a hierarchy at all.
I’m also not keen on using shared pointers as the default. It seems completely pointless, especially because you can’t even take advantage of std::make_shared() (because the constructors aren’t public). You should probably return a std::unique_ptr instead. If someone wants a shared pointer, they can always make one out of the unique pointer… but you can’t really do the opposite.

For example, I used friend function to access the protected constructors in all the classes, is this appropriate or there are better ways to do this?

I actually think pretty much all of your uses of protected are bad. But let’s set that aside for now.
If the constructors are non-public, then yeah, you have to use a friend somehow. There’s really no choice.

Another example, protected constructor is used so that the users may not directly construct the readers, but only through the factory function. Is this done correctly?

I honestly don’t see the sense of making any of the constructors protected.
Let’s start with the base class constructor. The only reason you need it protected is because you want initialize the protected data members. Now, I think the protected data members are also a bad idea, but one thing at a time. If you are going to have data members in the base class—which, again, is generally unwise—then, okay, it makes sense to have a protected constructor.
As for the constructors of the other two classes, unlike the base class these are concrete classes. What is the reasoning for hiding those constructors? If you want people to use the factory function, fine, but why make that the only option? Why don’t you want users to directly construct the readers?
By hiding those constructors, you prevent the use of std::make_shared(), which is an optimization opportunity lost. What’s the logic of that?
Also, even if you wanted to hide those constructors, what’s the sense in making them protected, and not private? That seems to imply you expect the classes to be derived from… but that’s a terrible idea: non-leaf classes should be abstract. (Again, assuming you’re doing interface inheritance. If you’re doing implementation inheritance, then there’s a whole other set of rules.)
Code review
Because the code is not presented as it would be in the actual project, and is instead all packed into a single block as some kind of code soup, with no includes and no explanation of what some of the key types are, this isn’t going to be a very comprehensive code review. I’ll do what I can with what I’ve got, but as the saying goes, GIGO.
typedef std::shared_ptr<DataReader> datareader_ptr;

There’s no indication of why shared_ptr is used here, and not unique_ptr, and in fact the rest of the code is written in a way that hamstrings the use of shared_ptr.
virtual void finalize() {
  pipe_.stop();
}
virtual ~DataReader() {
  std::cout << "dtor for DataReader called." << std::endl;
  finalize();
}

NEVER call virtual functions from constructors or destructors. It doesn’t do what you’d think, and only creates confusion for less experienced programmers.
In this case it “works” only because… well, I mean, the whole hierarchy is actually pointless. If the hierarchy were actually doing something that justified its existence, then this would almost certainly not work.
There is no visible purpose to finalize(). Just put pipe_.stop() in the destructor.
DataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile)
    :cfg_(cfg),pipe_(pipe),pipeline_profile_(pipeline_profile) {}

This is not a good way to write this constructor. (Or maybe it is? Who knows? Not enough information, forced to make guesses.)
If you are going to take the arguments by value—which is the right thing to do, because they are sink arguments—then you should move them into their final place… not copy. The copy is unnecessary, and possibly wasteful. And, if the move ops for all those types is noexcept (which it should always be), then that would mean you could make the constructor noexcept too.
The other issue is that you’ve mixed up the order of construction; it’s not the same as the order of declaration:
// order of declaration:
rs2::config           cfg_;
rs2::pipeline_profile pipeline_profile_;
rs2::pipeline         pipe_;

// order of construction:
cfg_(cfg),
pipe_(pipe),
pipeline_profile_(pipeline_profile)

I’m surprised this compiled without warning. You do have all warnings turned on, don’t you?
By the way, all the above is true of all the constructors, because they’re all identical. Which… again… is another issue.
class RosBagDataReader : public DataReader {
  // ... [snip] ...

  virtual bool get_next_frameset(rs2::frameset& frames) {

Prefer one of virtual, override, final, or none of the above. In this case, the one you want is NOT virtual, it’s override.
virtual ~RosBagDataReader() {}

You don’t need this. Don’t write code you don’t need; it just becomes a maintenance burden, noise obscuring important code, and confusion for future coders who wonder why it was put there if it wasn’t necessary.
// in base class:
virtual bool get_next_frameset(rs2::frameset& frames)=0;
rs2::pipeline pipe_;

// in derived class 1:
bool get_next_frameset(rs2::frameset& frames) override {
  frames = pipe_.wait_for_frames();
  return true;
}

// in derived class 2
bool get_next_frameset(rs2::frameset& frames) override {
  frames = pipe_.wait_for_frames();
  return true;
}

Why?
Why not:
// in base class:
virtual bool get_next_frameset(rs2::frameset& frames) {
  frames = pipe_.wait_for_frames();
  return true;
}
rs2::pipeline pipe_;

// in derived class 1:
// nothing needed

// in derived class 2:
// nothing needed

This entire class hierarchy serves no purpose. If I were to reorganize it into something logical, it might look more like this:
// truly abstract base class
class DataReader
{
public:
    virtual ~DataReader() /* = default; */
    {
        std::cout << "dtor for DataReader called." << std::endl;
    }

    virtual bool get_next_frameset(rs2::frameset& frames) = 0;
};

// concrete implementation 1
class RosBagDataReader : public DataReader
{
    // all data is private, as it should be
    rs2::config cfg_;
    rs2::pipeline_profile pipeline_profile_;
    rs2::pipeline pipe_;

public:
    RosBagDataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :
        cfg_(std::move(cfg)),
        pipeline_profile_(std::move(pipeline_profile)),
        pipe_(std::move(pipe))
    {}

    ~RosBagDataReader()
    {
        pipe_.stop();
    }

    bool get_next_frameset(rs2::frameset& frames) override
    {
        frames = pipe_.wait_for_frames();
        return true;
    }
};

// concrete implementation 2... same as 1... which, yeah
class CameraDataReader : public DataReader
{
    rs2::config cfg_;
    rs2::pipeline_profile pipeline_profile_;
    rs2::pipeline pipe_;

public:
    CameraDataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :
        cfg_(std::move(cfg)),
        pipeline_profile_(std::move(pipeline_profile)),
        pipe_(std::move(pipe))
    {}

    ~CameraDataReader()
    {
        pipe_.stop();
    }

    bool get_next_frameset(rs2::frameset& frames) override
    {
        frames = pipe_.wait_for_frames();
        return true;
    }
};

Or:
// no longer abstract, or even designed for inheritance at all:
class DataReader
{
    // all data is private, as it should be
    rs2::config cfg_;
    rs2::pipeline_profile pipeline_profile_;
    rs2::pipeline pipe_;

public:
    DataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :
        cfg_(std::move(cfg)),
        pipeline_profile_(std::move(pipeline_profile)),
        pipe_(std::move(pipe))
    {}

    ~DataReader()
    {
        std::cout << "dtor for DataReader called." << std::endl;
        pipe_.stop();
    }

    bool get_next_frameset(rs2::frameset& frames)
    {
        frames = pipe_.wait_for_frames();
        return true;
    }
};

// now pointless: class RosBagDataReader
// now pointless: class CameraDataReader

Honestly, I don’t even know if the suggestions I’m making make any sense whatsoever, because without the definitions of rs2::config et cetera, I have no clue whether these classes are copyable, movable, or whatever. But I don’t know what else to say: you hide code from reviewers, you get shitty reviews.
datareader_ptr make_data_reader(const std::string& ros_bag_path)

My biggest peeve with this factory function is that the argument list is bullshit. If I want to construct a data reader for a camera, I have to create a completely spurious path. That’s a waste of time for me on every level: it’s a waste of time for me to write the code to create a path I neither want nor need, and it’s a waste of resources within the program to create this useless path only to make a pointless check that it’s empty and then discard it.
If I were actually going to use this code, the very first thing I’d do is write my own wrapper functions:
auto make_camera_reader() { return make_data_reader({}); }

auto make_ros_bag_reader(std::string const& path) { return make_data_reader(path); }

And then I’d use those instead of direct calls to the factory functions.
Why? Because if I saw this in code:
auto reader = make_data_reader({}); // or make_data_reader("") or whatever

I’d immediately be forced to wonder… what is the {}? What does it mean? What am I constructing there at the call site? Will it be expensive? Does it have some semantics I should be aware of?
I like reading mystery stories; I don’t like mystery code. Code shouldn’t challenge me to wonder what’s going on, or force me to go read the docs. It should be crystal clear about what’s going on, and what it’s doing.
On the other hand, if I were to see:
auto reader = make_camera_reader();

That tells me pretty much everything I need to know. No mysteries.
This is not a problem with factory functions in general. Factory functions can still be very clear about what they’re doing. For example:
auto renderer = make_renderer("opengl"); // or make_renderer("vulkan") or whatever

// Here, make_renderer returns unique_ptr<renderer>, and renderer is an
// abstract base class, and the factory function returns concrete renderer
// implementations... but none of that matters! Just from the call above, I
// understand generally what's going on.

Compare that to:
auto reader = make_data_reader("");

// or even:
auto reader = make_data_reader("/path/to/file");

What is really going on there? “Data reader”? Well that’s damn vague. In the first case: the hell is that string supposed to mean? Make a data reader for… nothing? Emptiness? Perhaps the {} refers to wanting only default options? In the second case: okay, we’re making a data reader for some path, probably a file. That’s still pretty damned vague. Are we making a data reader for the file? If so, what kind of data? Are we making a data reader from the file?
If I were going to improve the design of your factory function, I might refactor it as follows:
auto make_data_reader(std::string_view name, std::string_view args)
{
    rs2::config cfg;
    rs2::pipeline pipe;

    if (name == "camera")
    {
        // args is unused

        rs2::pipeline_profile profile = pipe.start();
        return datareader_ptr(new CameraDataReader(cfg, pipe, profile));
    }
    else if (name == "video file")
    {
        // args is the path to the video file

        cfg.enable_device_from_file(args, false);

        rs2::pipeline_profile profile = pipe.start(cfg);

        rs2::playback play(profile.get_device());
        play.set_real_time(false);

        return datareader_ptr(new RosBagDataReader(cfg, pipe, profile));
    }
    /* future expansion:
        else if (name == "url")
        {
            // args is the url

            // ... implementation...
        }
    */
    else
    {
        throw std::logic_error{std::string{"unknown data reader type: "} + name};
    }

    // this should never happen, so it could also be an assert
    throw std::logic_error{std::string{"data reader type "} + std::string{name} + " failed to return reader"};
}

inline auto make_data_reader(std::string_view name)
{
    return make_data_reader(name, {});
}

And the usage is:
// I want to read frames from a camera:
auto reader = make_data_reader("camera");

// I want to read frames from a file:
auto reader = make_data_reader("video file", "/path/to/file");

// Hypothetical extension: I want to read frames from a web service:
auto reader = make_data_reader("url", "https://domain.com/path/to/service");

Let’s keep following the train of thought I started with my wrapper functions. What if they were more than mere wrappers?
auto make_camera_reader()
{
    rs2::config cfg;
    rs2::pipeline pipe;
    rs2::pipeline_profile profile = pipe.start();

    // Note: using make_shared because I assume constructors are public.
    return std::make_shared<CameraDataReader>(std::move(cfg), std::move(pipe), std::move(profile));
}

// Note: taking a proper path rather than a random string. You should always
// prefer proper, semantic types.
auto make_ros_bag_reader(std::filesystem::path const& path)
{
    rs2::config cfg;
    cfg.enable_device_from_file(ros_bag_path.string(), false);

    rs2::pipeline pipe;

    rs2::pipeline_profile profile = pipe.start(cfg);

    rs2::playback play(profile.get_device());
    play.set_real_time(false);

    return std::make_shared<RosBagDataReader>(std::move(cfg), std::move(pipe), std::move(profile));
}

Now there doesn’t seem to be any point to returning pointers, rather than objects directly.
In fact, let’s go one step further:
class image_sequence_reader // a better name than DataReader
{
    rs2::config cfg_;
    rs2::pipeline pipe_;
    rs2::pipeline_profile pipeline_profile_;

public:
    static auto make_for_camera() -> image_sequence_reader
    {
        rs2::config cfg;
        rs2::pipeline pipe;
        rs2::pipeline_profile profile = pipe.start();

        return {std::move(cfg), std::move(pipe), std::move(profile)};
    }

    static auto make_for_video_file(std::filesystem::path const& path) -> image_sequence_reader
    {
        rs2::config cfg;
        cfg.enable_device_from_file(ros_bag_path.string(), false);

        rs2::pipeline pipe;

        rs2::pipeline_profile profile = pipe.start(cfg);

        rs2::playback play(profile.get_device());
        play.set_real_time(false);

        return {std::move(cfg), std::move(pipe), std::move(profile)};
    }

    ~DataReader()
    {
        pipe_.stop();
    }

    auto get_next_frameset(rs2::frameset& frames) -> bool
    {
        frames = pipe_.wait_for_frames();
        return true;
    }

private:
    DataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :
        cfg_(std::move(cfg)),
        pipe_(std::move(pipe)),
        pipeline_profile_(std::move(pipeline_profile))
    {}
};

Usage:
// I want to read frames from a camera:
auto reader = image_sequence_reader::make_for_camera();

// I want to read frames from a file:
auto reader = image_sequence_reader::make_for_video_file("/path/to/file");

Want to extend the capabilities to read from some other source? No problem. Just add a new static member function:
    static auto make_for_nondefault_camera(camera_id const& id) -> image_sequence_reader;
    static auto make_for_device(std::filesystem::path const& device_path) -> image_sequence_reader;
    static auto make_for_web_service(url const& location) -> image_sequence_reader;
    static auto make_for_retina_brain_interface(person const& name) -> image_sequence_reader;
    // and so on...

That’s much less work than adding a whole new derived class, and then monkeying with the factory function to be able to select it.
It’s also clearer—both in the class and at the call site—safer, and, frankly, just easier to use.
Okay, but what if you really, REALLY want to use the factory pattern, because this is going to be in a library, and you want to be able to extend the library without client code having to be recompiled.
With some minor tweaks, you can even still enjoy all the other benefits of the factory pattern too:
////////////////////////////////////////////////////////////////////////
// in header used by client code:

// pure interface:
class image_sequence_reader_interface
{
public:
    virtual ~image_sequence_reader_interface() = default;

    virtual auto get_next_frameset(rs2::frameset&) -> bool = 0;

    // run-time polymorphic classes should generally not be copyable.
    // usually you'd implement a clone() function. i'll skip all that here.
};

// concrete implementation: the only thing client code really needs to care
// about.
class image_sequence_reader final : public image_sequence_reader_interface
{
    // if necessary, you can use a custom deleter to make sure the library
    // deletes its own memory, and not the application.
    std::unique_ptr<image_sequence_reader_interface> _p_impl;

public:
    static auto make_for(std::string_view name, std::string_view args) -> image_sequence_reader;

    static auto make_for(std::string_view name) -> image_sequence_reader
    {
        return make_for(name, {});
    }

    ~image_sequence_reader() = default;

    auto get_next_frameset(rs2::frameset& frames) -> bool override
    {
        return _p_impl->get_next_frames(frames);
    }

    image_sequence_reader(image_sequence_reader&&) noexcept = default;
    auto operator=(image_sequence_reader&&) noexcept -> image_sequence_reader& = default;

private:
    explicit image_sequence_reader(std::unique_ptr<impl>) noexcept;
};

////////////////////////////////////////////////////////////////////////
// in implementation file (cpp file, or module, or library source code, depending):

class camera_image_sequence_reader : public image_sequence_reader_interface
{
    rs2::config cfg_;
    rs2::pipeline pipe_;
    rs2::pipeline_profile pipeline_profile_;

public:
    camera_image_sequence_reader() :
        camera_image_sequence_reader(_construct())
    {}

    ~camera_image_sequence_reader()
    {
        pipe_.stop();
    }

    auto get_next_frameset(rs2::frameset& frames) -> bool override
    {
        frames = pipe_.wait_for_frames();
        return true;
    }

    camera_image_sequence_reader(camera_image_sequence_reader&&) noexcept = default;
    auto operator=(camera_image_sequence_reader&&) noexcept -> camera_image_sequence_reader& = default;

private:
    // All this _construct() stuff *MIGHT BE* needed because the data
    // members all seem to need to be constructed in a specific order, and
    // with references to each other. Or none of it might be necessary;
    // there's no way to know because I don't know what the data types are.

    static auto _construct() -> std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile>
    {
        rs2::config cfg;
        rs2::pipeline pipe;
        rs2::pipeline_profile profile = pipe.start();

        return {std::move(cfg), std::move(pipe), std::move(profile)};
    }

    camera_image_sequence_reader(std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile> t) :
        cfg_(std::move(t.cfg)),
        pipe_(std::move(t.pipe)),
        pipeline_profile_(std::move(t.profile))
    {}
};

class video_file_image_sequence_reader : public image_sequence_reader_interface
{
    rs2::config cfg_;
    rs2::pipeline pipe_;
    rs2::pipeline_profile pipeline_profile_;

public:
    video_file_image_sequence_reader() :
        video_file_image_sequence_reader(_construct())
    {}

    ~video_file_image_sequence_reader()
    {
        pipe_.stop();
    }

    auto get_next_frameset(rs2::frameset& frames) -> bool override
    {
        frames = pipe_.wait_for_frames();
        return true;
    }

    video_file_image_sequence_reader(video_file_image_sequence_reader&&) noexcept = default;
    auto operator=(video_file_image_sequence_reader&&) noexcept -> video_file_image_sequence_reader& = default;

private:
    static auto _construct() -> std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile>
    {
        rs2::config cfg;
        cfg.enable_device_from_file(ros_bag_path.string(), false);

        rs2::pipeline pipe;

        rs2::pipeline_profile profile = pipe.start(cfg);

        rs2::playback play(profile.get_device());
        play.set_real_time(false);

        return {std::move(cfg), std::move(pipe), std::move(profile)};
    }

    video_file_image_sequence_reader(std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile> t) :
        cfg_(std::move(t.cfg)),
        pipe_(std::move(t.pipe)),
        pipeline_profile_(std::move(t.profile))
    {}
};

// add or include any other implementations

auto image_sequence_reader::make_for(std::string_view name, std::string_view args) -> image_sequence_reader
{
    auto p = std::unique_ptr<impl>{};

    if (name == "camera")
    {
        p.reset(new camera_image_sequence_reader{});
    }
    else if (name == "video file")
    {
        p.reset(new video_file_image_sequence_reader{args});
    }

    // add any other options ...

    else
    {
        throw std::logic_error{std::string{"unknown image sequence reader type: "} + name};
    }

    // assert(p);

    return image_sequence_reader{std::move(p)};
}

And the usage is the same as before:
// I want to read frames from a camera:
auto reader = image_sequence_reader::make_for("camera");

// I want to read frames from a file:
auto reader = image_sequence_reader::make_for("video file", "/path/to/file");

And not only that, but with very little extra work you could even allow clients to register their own extension implementations. Alls you need is a register function in image_sequence_reader that takes a name and a create function (which returns a unique pointer with an appropriate deleter), and then a map that maps names to create functions, and then in image_sequence_reader::make_for(), just query the map for the name, then use the create function.
Is this a better design than what you have?  Impossible to say with the information I have.


Avoid Async.RunSynchronously until absolutely necessary. It is very inefficient by design. Looks like you need:

async { let! xs = SqlCmd.xxxHits query
        return List.ofSeq xs }

Which you should probably abstract into a function.

Once you remove the blocking (RunSynchronously), the ref use also becomes invalid - you are querying the ref potentially before the async changes it - race condition. Try returning it (return) in the main async instead.

If you really want the subqueries to execute in parallel, consider a helper combinator like Async.Parallel rather than starting multiple sub-computations manually.

Your function should return Async<string> instead of string. If the caller of your code wants a string and cannot possibly use Async, they'll call Async.RunSynchronously - make it their problem.

Concerning choosing to quit based on the result of first two asyncs, not sure what you need exactly. Cancellation is an optimization - it may be tricky to get right but may make the code better performing. It's your decision based on the problem domain whether it is worth it or not.


Defining application flow in ASP.NET MVC5

First off I think its a mistake to call your controller Methods after the view they return. I think this is creating a conceptual link which doesn't really exist.

Secondly, presumably the actions which the user takes at the end of each view are either the same regardless of the next view, or depend on what the next view is. I could have step 1: submit customer address -> 2: submit customer phone OR 2: submit customer name -- but the action from 1 is always 'submit address'

OR

you might have 1: request Phone Detail Form / 1: request name form

If it's the former then the submit address action should contain the workflow logic, and there is no need to decorate the view model, read the settings from config.

If the the later then the view model should include options for the different buttons which may or may not be enabled

If you do put the logic in the action, then yes, I think splitting it into a different workflow class is probably a good idea, even though it's probably going to be tightly coupled, it will give you the option to change it later and make it easy to see where changes just affect the workflow rather than the individual actions.


SPOJ problem - The last digit of a number to a power

As you have probably noticed, this is not efficient because you have a loop running exponent times (which could be over 2 billion). The way to make this more efficient is not to make your code faster, but to choose a better algorithm.

I'm not going to tell you outright what the answer is, but do the following. Add some output to your loop:

        for(i=1;i<=exponent;i++)
        {
            digit=(base*digit)%10;
            printf("digit = %d\n", digit);
        }

and then run your program for some (small) sample inputs. You should notice a pattern. The key is to identify the pattern and use it to avoid running the loop a billion times.


Assigning properties based on string parameters

Making the assumption you can't just use team1.Driver = team2.Codriver because you don't know the name of the properties first hand, I would build an even more generic function where it can be used with any type.

Also, I wouldn't name it Move because there is no move involved since the source still retains its values,

That said, my approach would be:

public void CopyProperty<T>(T source, string sourcePropertyName, T target, string targetPropertyName)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    if (target == null)
    {
        throw new ArgumentNullException(nameof(target));
    }

    if (string.IsNullOrWhiteSpace(sourcePropertyName))
    {
        ThrowInvalidParameterNameException(nameof(sourcePropertyName));
    }

    if (targetPropertyName == null)
    {
        ThrowInvalidParameterNameException(nameof(targetPropertyName));
    }

    Type elementType = typeof(T);
    PropertyInfo sourceProperty = elementType.GetProperty(sourcePropertyName);
    if (sourceProperty == null)
    {
        ThrowPropertyDoesNotExistException(sourcePropertyName, nameof(sourcePropertyName), elementType.Name);
    }

    if (!sourceProperty.CanRead)
    {
        ThrowPropertyAccessException(sourcePropertyName, PropertyAccessType.Read);
    }

    PropertyInfo targetProperty = elementType.GetProperty(targetPropertyName);
    if (targetProperty == null)
    {
        ThrowPropertyDoesNotExistException(targetPropertyName, nameof(targetPropertyName), elementType.Name);
    }

    if (!targetProperty.CanWrite)
    {
        ThrowPropertyAccessException(targetPropertyName, PropertyAccessType.Write);
    }

    if (sourceProperty.PropertyType != targetProperty.PropertyType)
    {
        throw new Exception(string.Concat("Property ", sourcePropertyName, " is not the same type as Property ", targetPropertyName));
    }

    targetProperty.SetValue(target, sourceProperty.GetValue(source, Type.EmptyTypes), Type.EmptyTypes);
}

private void ThrowInvalidParameterNameException(string parameterName)
{
    throw new ArgumentException("Invalid parameter name ", parameterName);
}

private void ThrowPropertyDoesNotExistException(string propertyParameter, string propertyParameterName, string typeName)
{
    throw new ArgumentException(string.Concat("Property ", propertyParameter, " does not exist in type ", typeName, " "), propertyParameterName);
}

private enum PropertyAccessType
{
    Read,
    Write
}

private void ThrowPropertyAccessException(string propertyParameter, PropertyAccessType accessType)
{
    throw new AccessViolationException(string.Concat("Property: ", propertyParameter, ", Access type: ", accessType));
}

With this you would get a safe and generic method to copy properties where you can use with any type and don't know which property is going to be copied (does not account for indexed properties).

You can use it calling:

CopyProperty(team1, "Driver", team2, "Codriver");

There is no collections to query for (unless you are searching for the right property) so I don't see how you can use linq.

This however has more if's than your first attempt.


Find non duplicateTriangle Triplets from a list of given numbers

Not an O(N^2) algorithm

You create a vector that contains every (i,j) pair.  This vector contains O(N^2) elements.

For each pair, you loop across the original vector of N elements.

Outer loop = O(N^2)
Inner loop = O(N)
Total = O(N^3)
By the way, unless you allow printing ranges of answers, there is no O(N^2) solution to this problem because there can be O(N^3) triplets that need to be printed.


new List<int>(input).ForEach(x => Console.Write(x + ","));

I see absolutely no reason to do this. In general, List.ForEach() is considered bad form by some and you should use normal foreach instead.

/// <summary>
/// sample input: 5 7 3 9 2
/// same output: 2 3 5 7 9
/// </summary>
/// <param name="numbers"></param>

This is not a very good documentation comment. The comment should describe in words what your code does. Example input and output might help to clarify that further, but I think that's not necessary for sorting.

Also, you should either describe your parameters using <param>, or don't use it (if you think the meaning of the parameters is clear). But empty <param> is not useful.

var lowerThanPivot = new List<int>();
var higherThanPivot = new List<int>();

You don't need these two lists. QuickSort can be implemented as an in-place algorithm. That means you don't need any additional collections to use it.

The way this is done is that you iterate the array from the start and at the same time from the end, switching elements between the two positions if the left one is larger than the pivot and the right one is smaller.

This will make your code somewhat more complicated, but it also potentially saves a lot memory.

int newLeftPivot = startIndex;

int newRightPivot = lowerThanPivot.Count + 1;

This is not a very good choice for a pivot. If the array is already sorted (or mostly sorted, with often isn't that uncommon), then your code will run in O(n^2) time, which will make it very slow on large inputs. You should consider a better way to choose the pivot.


ZBarSDK is the only place I've ever seen NSFastEnumeration.  I don't know a whole lot about it, nor do I know exactly why ZBarSDK was designed to be used in this way.

NSFastEnumeration isn't any faster than using a forin loop.  It is faster than a regular for or while (or do-while) loop, but not faster than a forin.

In a forin loop, we're using regular Objective-C collections, and NSArray has a firstObject and lastObject.

But if the real question is (and should be) how do I improve this code (more than just specifically grabbing a single object out of an NSFastEnumeration), then the answer is to use AVCaptureMetadataOutput (official documentation), which was introduced in iOS7.

ZBarSDK has an iOS7 memory leak.  Also, I don't know about compiled on-device size, but when I removed it from my project, it saved about 1.4mb from the project size.

Meanwhile, AVCaptureMetadataOutput has many advantages over ZBarSDK.

It's slightly easier to use... and it's simple to use if you're already familiar with video capture in iOS.
It leaves a smaller footprint in terms of storage space your app takes up on a device.
Even without ZBarSDK's memory leak, AVCaptureMetadataOutput has a smaller memory footprint.
AVCaptureMetadataOutput seems to scan barcodes faster and a farther distances than what I could manage with ZBarSDK.
ZBarSDK doesn't support 64-bit processors at all.  AVCaptureMetadataOutput however does.


Computing the profit or loss from a list of trades

This is too sketchy to be able to do a proper review. But just based on what you've written in the post:

None of this code updates the attributes of a Trade. So you could use a collections.namedtuple which avoids some duplication:

Trade = namedtuple('Trade', 'id trade_date type quantity price currency_id '
                   'company_id account_id')

In some languages (especially Java) everything has to be a member of a class. But this isn't the case in Python: you can just write a function if you want, without having to make a class whose only role is to act as a container for your function.

So here there's no need for the TradePnlCalculator class — you could just define a function compute_pnl. And there's no need for the TradeImporter class — you could just define a function load_trades.
In compute_pnl, you're not gaining anything from using NumPy — it costs more to build the NumPy arrays than you gain in faster operations. It would be simpler and faster to write:

-sum(t.type.value * t.quantity * t.price for t in trades)

The need for the negation of the result of this computation suggests that you have the values for Buy and Sell the wrong way round.
The code in compute_pnl doesn't consult the currency_id so it would go wrong if given a list of trades in a mixture of currencies.


First thing first, make config a named tuple. This would seriously improve readability, and obviate the (really unclear) comment.
Factored out the repeated code into a function, e.g.:

def wraparound(coord, matching, twist):
    if 0 < self.location[coord] < self.dimension[coord]:
        return
    if twist:
        self.location[1 - coord] *= -1
    if matching:
        self.location = self.location[::-1]
        self.direction = self.direction[::-1]


early pruning
This is very nice:
        // delete any that are over our budget

Doing it before sorting can slightly speed the sorting operation.
I say slightly because "items over budget" is determined by the input,
and it will be some fraction f of an input item category,
so the savings is O(f * n * log n).
early discard
This is a bigger deal.
        // sort the list & delete anything over budget

For k keyboards and d drives, the sort does O(k * d * log k * d) work.
Discarding within this loop would be an even bigger win.
consistent idiom
It was a little odd that you used
        combinedTotals.RemoveAll(n => n > budget);

and
        array.Where(n => n < budget).ToArray();

to accomplish the same thing.
There's no speed difference but consider phrasing the same thing in the same way.
reversing
If you pass into Sort something that implements the IComparer interface,
you can change the comparison order and thus skip the Reverse step entirely.
arithmetic
Arbitrarily choose one of the categories as the driving category, perhaps keyboard.
Sort the drive prices, while leaving the keyboards in arbitrary order.
Note the min drive price, and use that along with budget for immediately pruning infeasible keyboards.
Loop over all surviving keyboards.
Target price is budget - kb_price.
Do binary search over drives for the target,
finding largest feasible drive,
and use that to update "best combo so far".
No need to sort them, you need only retain the "best" one.


Find all permutations of a string in C++

You may need to remove duplicates. Consider what your output will be if, for example, your input string is "aaa".

Code like this is unusual:

// nextList contains an array of empty strings
nextList[i*string.length+j] += SubString(prevList[i],0,j);

IMO this would be more usual:

// nextList is empty
// calculate new string
string nextString = SubString(prevList[i],0,j)
    + string[0]
    + SubString(prevList[i],j,string.length-1);
nextList.Add(nextString);

Returning by value is sometimes necessary but can be inefficient. Your algorithm creates many temporary List objects. A better API might be ...

void Permute(const String& inputString, List& outputList) { ... }

... where one empty List is allocated by the caller, and you add to it.

This statement may be incorrect ...

List prevList = Permute(SubString(string,1,string.length));

... I don't know how returns the string 'string[i...j)' is defined but perhaps this statement should be ...

List prevList = Permute(SubString(string,1,string.length - 1));

You may run out of memory very quickly. For a string of length n there are n! ('n factorial') permutations. "what's up doc?" has 14 characters => 87178291200 (or 0x144C3B2800) i.e. bigger than 232 combinations.


Using bind instead of promises or stacked callbacks

I've realized there's no need for all these prototype functions and binds.
When using node.js, in a file, the normal named functions are private to the file, so it can be used as methods.

var self = {
  parallelLimit: 10
}

function generateLocFieldForDocs(docs) {
  log('list obtained')
  async.eachLimit(docs, self.parallelLimit, generateLocFieldForDoc, generateLocFieldForDocsDone)
}

function generateLocFieldForDoc(doc, done) {
  self.collection.update({_id: doc._id},
  {$set: {
    loc: {...}
  }}, function(err, result) {
    errorHandler(err)
    done()
  })
}

function generateLocFieldForDocsDone(err) {
  errorHandler(err)
  generateLocFieldNextSection()
}

Using module.export.myFunction = makes it public


Better way to add fields to superclass in Java

Short answer: no, there's no better way.

There's also nothing wrong with this way of working. You're adding a field that every instance of this class needs to have for your program to work correctly. That's a good reason to enforce initialising it in the constructor. Your compiler (or even better, your IDE) will tell you where else you need to update your code.

In case you're developing a package that other people use where they need to have some time to adjust to the new version you need to be more careful when making API changes (like adding parameters to a public constructor).

In that case you make the current constructor @deprecated and provide a new one next to it. You can also provide a default value for the new field so that the original constructor still "works". For example:

public class Person {
    private String lastName;
    private String firstName;

    @deprecated
    public Person(String lastName) {
        this("", lastName);
    }

    public Person(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    ...

This way, their IDE will still tell them they're using an outdated constructor, but at least they'll still be able to run their current code without changing all the calls from the start.

Alternatively you could look into other options besides adding the fields to that class. For example, you could have a lookup class that, given a certain employee, looks up his salary in a table for example. This greatly depends on what your program is supposed to do. With the little information you've given us here it's hard to propose concrete solutions like this.


You will have less code if you use a regex because you need the word boundary detection that is built into regex.  I'd suggest putting it in a utility function to make it cleaner and more readable:

function replaceClass(el, oldClass, newClass) {
    el.className = el.className.replace(new RegExp("\\b" + oldClass + "\\b"), newClass);
}

function fn_page_change(event) {
    event.preventDefault();
    var activePage = $(".ui-active");
    var newPage = $(event.target.getAttribute("href"));
    replaceClass(activePage, "ui-active", "ui-inactive");
    replaceClass(newPage, "ui-inactive", "ui-active");
}

If you wanted a version of replaceClass() that would handle either of the types of return values you get out of your selector function (single DOM object or array of DOM objects), then you could use this:

function replaceClass(el, oldClass, newClass) {
    var re = new RegExp("\\b" + oldClass + "\\b");
    if (el.nodeType) {
        el.className = el.className.replace(re, newClass);
    } else {
        for (var i = 0; i < el.length; i++) {
            el[i].className = el[i].className.replace(re, newClass);
        }
    }
}


Don't write long lines.

The reason Loki Astari didn't comment on

bool allUpper = std::all_of(s.begin() , s.end() , [](char ch){ if(std::isupper(ch) || !std::isalpha(ch)) return true; else return false; });

is that it is too long. Written properly as

bool allUpper = std::all_of(s.begin() , s.end() ,
    [](char ch){
        if(std::isupper(ch) || !std::isalpha(ch))
            return true;
        else
            return false;
    });

it'd prompt for another advice:

    if (condition)
        return true;
    else
        return false;

is a standard anti-pattern: it is equivalent to short and clean

    return condition;


Constructing a lexicon and frequency array from a long string

For each word in the lexicon you are searching through each email: (11,314 emails) * (60 words/email) * (211441 word lexicon) = lots of comparisons.

Flip it around.  Use collections.Counter.  Get the unique words in each email (use a set()) and then and update the counter.

from collections import Counter

counts = Counter()

for email in x_train:
    words = set(email.split())   # <= or whatever you use to parse the words
    counts.update(words)

This will give you a dict mapping words in the emails to the number of emails they are in.  (11,314 emails) * (60 words/email) = a lot fewer loops.
This probably also recreated the lexicon (e.g.
counter.keys() should be the lexicon.

On my computer, it takes 7 seconds to generate 115000 random 60-word emails and collect the counts.


I have observed a few things that may help you improve your code.

Use consistent formatting

The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.

Check return values for errors

The call to scanf can fail.  You can check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources.  Rigorous error handling is the difference between mostly working versus bug-free software.  You should strive for the latter.

Don't use Hungarian notation

Prefixing every variable with an abbreviation of its type is usually called "Hungarian notation" and it was once popular.  Even then it was a bad idea.  Don't clutter up your source code with that; instead, concentrate on defining meaningful names for each variable and choose types appropriately.  I'd suggest secretNumber and userGuess in this case.

Use a better random number generator

You are currently using

iRandomNum = (rand() % 10);

There are a number of problems with this approach. The most significant problem is that the range this returns (0 through 9 inclusive) does not match what the user is asked to guess ("a number between 1 and 10")  Second, this will generate lower numbers more often than higher ones -- it's not a uniform distribution.  Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result.  On my machine, there's a slight but measurable bias toward 0 with that.  See this answer for details, but I'd recommend changing that to

secretNumber = rand() / (RAND_MAX / 10) + 1;

Think of the user

When someone asks me to "Guess a number between 1 and 10", I usually say \$e\$.  (Yes, I'm afraid I'm that kind of person.)  It seems clear from the context of your program that what you really mean is to guess an integer, and it seems likely that, technically speaking, you don't want numbers solely between 1 and 10 but that you mean to include 1 and 10 among the possible choices.  To more clearly convey that, I'd suggest asking the user to "guess a whole number from 1 to 10 inclusive" but I'm probably too used to being around engineers and scientists.

Check your logic

If I input "e" as my guess, the scanf call will fail and the variable may be uninitialized.


The algorithm is not working quite as you may expect:

   if (result[str[i]] === undefined && str[i] !== " ") {
        result[str[i].toLowerCase()] = 1;
    } else {
        if (str[i] !== " ") {
            // add one to value at current key
            result[str[i]]++;
        }
    }

If you enter "Hello, World! - Hi!" the two upper case 'H' are only counted as one, because they both evaluate to true in the first if-statement - because you test for an upper case 'H' but save a lower case 'h'.

In the same place you filter spaces out both in true and false, so you could do that as the first thing to do in the loop.

All in all that could be like:

  for (; i < stringLen; i++) {
    let ch = str[i].toLowerCase();
    if (ch !== " ") {
      if (result[ch] === undefined) {
        result[ch] = 1;
      } else {
        result[ch]++;
      }
    }
  }

Use comments to explain why you do what you do (if not obvious), and not what you do - the code shows that.

The whole ting could also be done like this:

function characterCounter(str) {
  if (!str) {
    return "String input required";
  }

  if (typeof str !== "string") {
    str = str.toString();
    if (typeof str !== "string")
      return "Invalid input";
  }

  const result = {};

  for (var i in str) {
    var ch = str[i].toLowerCase();
    if (ch !== " ") {
      if (result[ch] === undefined) {
        result[ch] = 1;
      } else {
        result[ch]++;
      }
    }
  }
  return result;
}


Checking if CLI arguments are valid files/directories in Python

You can address some of this by subclassing ArgumentParser.  This will allow you hide the lambda calls that may turn off some and leave you scratching your head if you come back to that file later.

Your Script

if __name__ == "__main__":
    # Process the arguments
    #import argparse
    import arghelper
    parser = arghelper.FileArgumentParser(
        description='Process the data.')
    parser.add_argument_with_check(
        'config_file',
        help='CSV configuration file.',
        metavar='FILE')
    parser.add_argument_with_check(
        'input_dir',
        help='Directory containing the input files.',
        metavar='DIR')
    parser.add_argument_with_check(
        'output_dir',
        help='Directory where the output files should be saved.',
        metavar='DIR')
    args = parser.parse_args()
    print args

New ArgHelper

import argparse
import os

class FileArgumentParser(argparse.ArgumentParser):
    def __is_valid_file(self, parser, arg):
        if not os.path.isfile(arg):
            parser.error('The file {} does not exist!'.format(arg))
        else:
            # File exists so return the filename
            return arg

    def __is_valid_directory(self, parser, arg):
        if not os.path.isdir(arg):
            parser.error('The directory {} does not exist!'.format(arg))
        else:
            # File exists so return the directory
            return arg

    def add_argument_with_check(self, *args, **kwargs):
        # Look for your FILE or DIR settings
        if 'metavar' in kwargs and 'type' not in kwargs:
            if kwargs['metavar'] is 'FILE':
                type=lambda x: self.__is_valid_file(self, x)
                kwargs['type'] = type
            elif kwargs['metavar'] is 'DIR':
                type=lambda x: self.__is_valid_directory(self, x)
                kwargs['type'] = type
        self.add_argument(*args, **kwargs)


Remove specific consecutive element in array

You can have the same output with regex , using Arrays.toString(char[]):

System.out.println("000300300030303330000".replaceAll("[0]+", "0"));

or, with a parameter :

char charToRemove = '0' ;
System.out.println("000300300030303330000".replaceAll("[" + charToRemove + "]{1,}", charToRemove + ""));

or change charToRemove  + "" in  Character.toString(charToRemove) more academic.


Unless you use a very old compiler, I suggest you to declare (and initialize) variables as late as possible and limit their scope. This prevents potential mistakes like

return current; /* whoops, meant counter! */

in countCyclesHelper.

Next, unless you got invalid input, only array[first] may be -1, otherwise one of your nodes in your (implicit) graph has two incoming edges and the original file didn't contain a valid permutation.

If we take both suggestions into account, we end up with the following countCyclesHelper:

int countCyclesHelper(int* array, int N) {
  int total_cycles = 0;

  for (int i = 0; i < N; i++) {
    const int first = i;
    int current = first;

    if (array[current] == -1) {
      /* already counted this cycle */
      continue;
    }

    while (1) {
      const int temp = array[current] - 1;
      array[current] = -1;
      current = temp;
      if (current == first) {
        counter++;
        break;
      }
    }
  }
  return total_cycles;
}

While I kept first, it's possible to replace it with i.

As you can see, I've added const at various places. If we don't intend to change a value it's usually a good idea to prevent it with const. This holds for example for your name in countCycles. We don't want to accidentally change the file name:

int countCycles(const char *name, int N)

Next, fread(buffer, sizeof(buffer), …) is—unfortunately—wrong, since buffer is a pointer. You end up with fread(buffer, sizeof(char*), …). Therefore, your program contained undefined behaviour, unless N <= sizeof(char*).

That being said, countCycles is an overkill, since you handle only single digit permutation indices. For any  N >= 10the content ofarraywon't be a permutation. With this in mind, we can simplifycountCycles` a lot:

enum { MAXIMUM_DIGITS = 9 };

int countCycles(const char *name, int N) {
  if(N <= 0 || N > MAXIMUM_DIGITS) {
    return -1;
  }

  char buffer[MAXIMUM_DIGITS];

  FILE *fp = fopen(name, "rb");
  if(fread(buffer, N, 1, fp) != N) {
    fclose(fp);
    return -1;
  }
  fclose(fp);

  int array[MAXIMUM_DIGITS];

  for (int i = 0; i < N; i++) {
    array[i] = buffer[i] - '0';
  }
  return countCyclesHelper(array, N);
}

If MAXIMUM_DIGITS gets larger at some point, you probably need to switch to malloc again, but simple arrays with a static size work well enough for your use case.


Converting a range in excel to a single column with excel vba

4-5 hours is ridiculous

4-5 hours with ScreenUpdating, Events, & Calculation disabled is even more so.

What you've discovered here is that Excel is very slow at inserting/deleting columns/rows when you have large amounts of data in a Worksheet.

and you're doing it up to 235,000 times.

Delete everything in a single operation

What we're going to do here is loop through Ranges and, as we go, add all the Ranges-to-be-deleted to one master Range using the Union() function.

Then, at the end, delete the entire master range in one go:

Dim rowsToBeDeleted As Range '/ our master delete range

For row = Z To 1 Step -1

    If Cells(row, 1) = 0 Then

        If rowsToBeDeleted is Nothing Then '/ check if any ranges have been added yet
            Set rowsToBeDeleted = Range("A" & row) '/ add the first range
        Else
            Set rowsToBeDeleted = Union(rowsToBeDeleted, Range("A" & row)) '/ add the new range to the existing ones
        End If

    End If

Next row

If Not rowsToBeDeleted Is Nothing Then '/ check that we found anything to delete
    rowsToBeDeleted.EntireRow.Delete
End If

I suspect that this change alone will take your runtime from hours to minutes.

(Just as an aside, worth noting that a Range object can only have up to 1,048,576 range areas. So if you ever get up to more than 1,024^2, you'll have to check against it.)


Dynamically adding and removing HTML classes

A common question,

@elclanrs is right that you probably want a common class for your home anchor tags unless you truly want to style them all differently.

Then you could simply turn off the current active anchor with

$('.homeAnchor.subActive').removeClass("subActive");

Otherwise, you could try and see if this works for you:

$('.subActive').removeClass("subActive");

That assumes that on the whole page you use subActive only for your home anchors of course.


C++ implementation of the Command Pattern

Virtual Destructor

If a class has virtual methods it should also have a virtual destructor. Now this is only important if you destroy a class from a pointer to the base class. Since your code leaks all the objects it will not hurt you (Note: I am being facetious). Both leaking and incorrectly destroying objects is a big deal. This is after all not C and thus we like to actually write working programs.

class Command {
public:
    virtual ~Command() {}      // Declare a virtual destuctor in
                               // the base class. All derived types
                               // will inherit a virtual destructor.
    virtual void execute() = 0;
};

Override Specifier

In C++11 we added the override specifier. You are supposed to use this to make virtual functions you are overriding. It provides a nice safety blanket, if somebody in the future changes the virtual function definition then the override specifier in your class will cause an error if you have not changed the definition in your class to match.

class CowCommand : public Command {
    Cow cow;
public:
    CowCommand(Cow cow) : cow(cow) {}

    void execute() override {   // Add override here.
        cow.moo();
    }
};

Don't pass by value (Pass by const ref as a first default).

If you pass by value you are causing a copy of the object. This may be unnecessarily expensive. Pass by const reference. If you need to then you can make a copy before using.

Alternatively you can pass by R-Value reference and move the object in the methods.

    Cow cow;
public:
    // You make two copies of cow here.
    CowCommand(Cow cow)       // A copy is made to pass it to the method.
        : cow(cow)            // A second copy is made passing while
                              // creating the local `cow` object.
    {}

    // I would have done this:
    CowCommand(Cow const& cow)   // Pass a normal reference
        : cow(cow)               // Now make a copy (only 1 copy)
    {}
    CowCommand(Cow&& cow)        // Pass an r-value reference
        : cow(std::move(cow))    // Move the object into cow.
    {}

Don't pass pointers

A pointer has no concept of ownership. Ownership decides who is supposed to delete the object. If I don't know who is supposed to delete I may accidentally delete something that is not dynamic or if I don't delete something I am supposed to then I leak an object.

The idea is that public interfaces should pass things around in a way that ownership of the object is clear (private and internal methods can use pointers for efficiency).

This public function passes a pointer.

void setCommand(Command* ptr_cmd) {
    ptr_command = ptr_cmd;
}

Internally you store it as a pointer. But you don't take ownership (i.e. you don't call delete on the pointer in the destructor). So this object can easily be used incorrectly.

{
    PlatoSays  plato;
    plato.setCommand(new LokiCommand);
}

Here I have created a dynamic object and passed in it setCommand() (which has the only copy of this pointer. At the end of scope the LokiCommand object is leaked.

If you are not going to take ownership then pass by reference. This indicates to the method you can have a link to my object but I will delete it (not you).

void setCommand(Command& ptr_cmd) {
    ptr_command = &ptr_cmd;   // Its OK to store a pointer to the object
                              // Just mean Plato has to be created first
                              // and destroyed last.
}

Note: If you do want to pass ownership. Then wrap your pointer in a smart pointer. This will take care of the ownership.

class PlatoSays {
    std::unique_ptr<Command> ptr_command;
public:
    void setCommand(std::unique_ptr<Command>&& ptr_cmd) {
        ptr_command = std::move(ptr_cmd);
    }

    // Notice the usage of a unique_ptr is exactly the same as the
    // usage for a normal pointer. The only difference is that it
    // Correctly initializes itself (so you don't need a constructor)
    // And when updating it you need to use `std::move()`
    void invokeCommand() {
        if (ptr_command) {
            std::cout << "Plato says: ";
            ptr_command->execute();
        }
        else {
            std::cout << "Plato has nothing to say!" << std::endl;
        }
    }
};

Leaks in your program.

And here we see the exact problem with pointers.

plato.setCommand(new CowCommand(Cow()));
plato.invokeCommand();

plato.setCommand(new DogCommand(Dog("Lucky")));
plato.invokeCommand();

plato.setCommand(new CarCommand(Car()));
plato.invokeCommand();

All three of these objects are leaked.

Use when ownership is not transferred:

PlatoSays plato;
CowCommand   cow(Cow());
DogCommand   dog(Dog("Lucky");
CarCommand   car(Car());

plato.setCommand(cow);
plato.invokeCommand();

plato.setCommand(dog);
plato.invokeCommand();

plato.setCommand(car);
plato.invokeCommand();

Use when ownership is transferred:

PlatoSays plato;
plato.setCommand(std::unique_ptr<Command>(new CowCommand(Cow()));
plato.invokeCommand();

plato.setCommand(std::unique_ptr<Command>(new DogCommand(Dog("Lucky"))));
plato.invokeCommand();

plato.setCommand(std::unique_ptr<Command>(new CarCommand(Car())));
plato.invokeCommand();

Prefer "\n" over std::endl

The only difference is that std::endl flushes the stream. Manual programmer flushing is the usually non optimal and the cause of most slow downs when comparing C++ code to C code speed.


A Countdown Timer with reset functionality in pure Javascript

From a short review;

You use 9 twice, this should be assigned to a nicely named global constant
You hard code both 9 and 00:10, this is not flexible. I would expect to be able to change 9 to 99 and to have the timer start at 01:40
Similarly, 00:0${startingTime--} does not allow for much flexibility in the script
The browser tries to honor the 1000, but it cannot be trusted. You are supposed to keep track of the original start and deduct that from current time to determine how much time has passed. Otherwise the timer is not reliable.
Placing the timer in a h1 element is probably not a good idea semantically
Your entire code should be in a well named (self executing) function
I am not sure why you return anything in startStopTimer? If you are never using the returned value, then just drop the return keyword
since clearInterval returns undefined and because it makes sense, I would go for startTimer = clearInterval(startTimer);
Why console.clear()? Production code should avoid console


Find all pairs in an array whose absolute difference equals x

I don't have the rep to comment, and I know you said without sorting first, but if you are already at worst case performance of O(n^2), and sorting in theory is O(nlogn), why not then sort if it wont hurt your big-o performance?

i.e.

A.sortAscending() // however done in java. in theory is O(nlogn)

int j = 0;
for (int i = j; i < A.len; i++) {
    while (j < A.len && (abs(A[i] - A[j++]) < x))
        ; // do nothing

    // so now we are guarenteed absdiff(arr[i], arr[j]) <= x.
    // as soon as it != x we can move on because as the array is sorted
    // the difference will only increase, thus not equaling x again
    while (j < A.len && (abs(A[i] - A[j++]) == x))
        resultArray.add((arr[i], arr[j])
}


How can I make this code more readable and efficient?

This would become instantly more understandable if you gave a description (a comment at the start of the function) of what it was supposed to do.  You could also give the structure celula, which I'm assuming is at least:

struct celula
{
    int no;        // number of something?
    int peso;      // weight, perhaps?
};

Also you use i for line (linhas) and j for column (colunas). But l and c would be more logical and readable (but l looks like 1, so in English I'd use r for "row").  I'm generally ok with short variable names, but in such a long function i and j don't work for me.  In English I would probably use row and col.

As your function has nested loops with the outer loop doing nothing but enclosing the inner loop, I would if possible extract the whole inner loop to a separate function. But I can see that this might not be easy if those badly named variables a, b, c, loop accumulate across rows.  It is difficult to tell whether they do from a short look - I might take a longer look later...

Later...

Returning to variables a, b, c:  they are never reset once set.
Is that correct?  These variables names are meaningless and need changing.  And what does node mean - again the name needs improving.

A bigger observation is that everything below the first else contains the term aux[i][j].peso == 0.  I think these can all be factored out (so that the condition is tested at the top of the loop.

for(i = 0; i < linhas; i++){
    for(j = 0; j < colunas; j++){
        if((i == 0) && (j == 0)){
            aux[i][j].no = node;
        }
        else if(aux[i][j].peso == 0) {  // moved to here
            if((i == 0) && (j != 0)){

And also the i != 0 and j != 0 in the following lines are unnecessary, as they have been handled further up:

else if(aux[i-1][j].peso == 0 && i != 0){                     // here
    aux[i][j].no = aux[i-1][j].no;
}
else if(aux[i][j-1].peso == 0 && j != 0){                     //here
    aux[i][j].no = aux[i][j-1].no;
}
else{
    for(k = j; aux[i][k].peso == 0 && k < colunas; k++){
        if(i != 0){                                           // here


Sorry for the ridiculously long answer. I've added an alternative (better) way of doing this at the very bottom.
Here are a few things you could improve:
class TicTacToe
There's no need for this class. You can get (probably) rid of it.
Spaces
Overall, your code is well-formatted, but there a few instances like these, where you missed spaces:
if(turnNumber%2 == 0)    |>   if (turnNumber % 2 == 0)
pattern=>{               |>   pattern => {
def startGame: Unit ={   |>   def startGame(): Unit = {

Type aliases
I don't know about you, but I like using type aliases because they help me remember what each type represents. It's also handy when you have to refactor your code, e.g., if you want to represent moves using tuples representing the row and column ((Int, Int)) or you want to make a Board class instead of just using an array of characters, you don't have to change your method signatures - they can still return and accept objects of type Player and Board.
type Player = Char
type Board = Array[Player]

Unnecessary braces and the main method
Instead of
def main(args: Array[String]): Unit = {
    startGame
}

you could make it a one-liner
def main(args: Array[String]) = startGame

However, it'd be much more helpful to announce instructions before starting the game (I know those instructions don't match your own game, but bear with me).
def main(args: Array[String]): Unit = {
    println("Welcome to Tic Tac Toe!")
    println("To play, enter the row and column of the cell where you want to move when prompted")
    println("Both the row and column must be numbers from 1 to 3")

    runGame()
}

startGame
Rather than startGame, I feel like you should name it runGame, but that's entirely subjective, and you should pick whatever feels more intuitive to you.
More importantly, I think the startGame should be a nilary method rather than a nullary method, i.e., it should have an empty parameter list so that it looks like a proper method call rather than a property access. Currently, it looks very confusing when you just have startGame to run the entire game, since it looks like an unused expression.

Storing the board
Using a 1-D array of characters to represent a board is fine for now, although not very good functional programming style. There are a lot of other issues here, though.
board.update
You can use board(atPosition) = nextPlayer(board) instead of board.update(atPosition, nextPlayer(board)), since the update method is one of Scala's special methods that let you use syntactic sugar.
Adding the current board to the game
Currently, you use List(board) ++ game, which creates a new list and then concatenates game to it. A better approach would be board :: game, which is more idiomatic and simpler.
Why using a List[Array[Char]] is bad
First of all, there is absolutely no reason to maintain a list of all the past boards. You don't use the game variable everywhere. You can just have a single Array[Char] to keep track of the current board. Even if you do need to be able to go back to a previous move, you can just maintain a List[Move] and use it to reconstruct the board at a specific time.
Second, every single board you store in game refers to the exact same object! You're not copying board anywhere, so when you write the below code, you're getting the head of game, updating it, and then prepending that same board back onto game.
val board: Array[Char] = game.head
board.update(atPosition, nextPlayer(board))

A better solution would be to use tuples or a case class of your making. I'm going to just use tuples for now, because case classes would bloat the code.
type Row = (Player, Player, Player)
type Board = (Row, Row, Row)

Now that the board's 2-D, let's also make our moves 2-D, actually. They'll represent the row and column of each move. I made them 1-indexed in my code because I also make the user pick a number from 1 to 3 instead of 0 to 2 because I feel it'd be easier. By also internally using 1 instead of 0, we'll reduce off-by-one errors.
type Move = (Int, Int)

Variables
At the top of your object, you have a ton of variables, of which you need only one - patterns (which I'm going to rename to winCases, because that is more descriptive to me). There's no need to make separate public variables for l1, l2, etc. You can just do it like this (I used Set because the order doesn't matter):
val winCases = Set(
    Set((1, 1), (1, 2), (1, 3)),
    Set((2, 1), (2, 2), (2, 3)),
    Set((3, 1), (3, 2), (3, 3)),
    Set((1, 1), (2, 1), (3, 1)),
    Set((1, 2), (2, 2), (3, 2)),
    Set((1, 3), (2, 3), (3, 3)),
    Set((1, 1), (2, 2), (3, 3)),
    Set((1, 3), (2, 2), (3, 1)),
  )

startBoard can just be a local variable in runGame and doesn't have to be accessible by everyone.
winConditions we won't need because the whole isWon method can be refactored. There's absolutely no need to make a new string for each element of patterns/winCases.

Finding the winner
I don't like the fact that your isWon method prints the winner instead of only returning whether or not someone has won the game. A better way to do it would be to return a player and let the calling method decide what to display to the user. For that, I made this method:
def findWinner(board: Board): Either[Unit, Option[Player]] =
    if (isWinner(player1, board)) Right(Some(player1))
    else if (isWinner(player2, board)) Right(Some(player2))
    else if (isTie(board)) Right(None)
    else Left(())

Having an Either[Unit, Option[Player]] lets us encode multiple things into that single value. If it's a Left, we know the game will continue. If it's a Right, the game's ended. If it's the latter, containing a Some, there's a winner, and if it's a None, there's a tie.

Back to startGame/runGame
Among other things, I've renamed the playGameAt function to playRound. I also changed the signature. It takes the current board and player, and outputs the winner of the game. If there's a winner, it's a Some. If there's a tie, it's a None.
def playRound(board: Board, curr: Player): Option[Player]

Here's how the new function looks:
@tailrec
def playRound(board: Board, curr: Player): Option[Player] = {
  printBoard(board)
  println(s"Player $curr's move")
  val move = nextMove(board)
  val newBoard = moveTo(curr, move, board)
  findWinner(newBoard) match {
    case Right(possWinner) => possWinner
    case Left(_)           => playRound(newBoard, nextPlayer(curr))
  }
}

I've put the call to printBoard at the very top, because even though all tic-tac-toe boards are the same (unless you're playing a special variant), I personally would like to see the board I'm going to be moving on before I actually select a move. It's totally subjective, but I prefer it this way.
The print statement lets you know which player is supposed to move. The way you have it now, the users have to scroll up to see whose move it is currently, and this seems more helpful.
After that, it gets the next move with the nextMove function (which I'll put in later), creates a new board using that move, and tries to find the winner (see above for how the findWinner method works). If the game's ended, it returns the winner (or None if it's a tie). If not, it plays another round using a new board and the other player.
nextPlayer is implemented like this, by the way:
def nextPlayer(curr: Player): Player =
    if (curr == player1) player2
    else player1

The entire runGame function looks like this:
def runGame() = {
    @tailrec
    def playRound(board: Board, curr: Player): Option[Player] = ...

  val startBoard = (
    (default, default, default),
    (default, default, default),
    (default, default, default)
  )

  val winner = playRound(startBoard, player1)
  winner match {
    case Some(player) => println(s"Player $player won!")
    case None         => println("Tie")
  }
}

Here, startBoard is just a local variable, because I don't think there's any reason for anybody outside this method to know about it. default is a Char that represents a cell where no one's moved. player1 and player2 are used to mark where Player 1 and Player 2 moved, respectively.
val default = ' '
val player1 = 'x'
val player2 = 'o'

I also moved the print statement from isWon to here, so that there could be a customized message. Otherwise, if there was a tie, nothing would happen.

User input
It doesn't make sense to me that you're using a JOptionPane and displaying everything in the terminal. Why not make the user input also come from the console? We can write our nextMove method like this:
@tailrec
def nextMove(board: Board): Move = {
  val move = (nextRowOrCol("Row"), nextRowOrCol("Column"))

  if (isValid(move, board)) {
    move
  } else {
    println("That move is already taken. Please enter a different move.")
    nextMove(board)
  }
}

The above code reads a row and column using the helper function nextRowOrCol, then checks if it's a valid move, i.e., no one's moved there already. If it is, it just returns it, and if not, it gets the user to re-enter a move. I'll add the isValid function a little below.
nextRowOrCol is implemented like this (prompt can be either "Row" or "Column"). It uses regex to ensure that the input is a number between 1 and 3. Like the nextMove function, if the row or column inputted is valid, it returns it directly, otherwise, it prompts the user(s) again.
private def nextRowOrCol(prompt: String): Int = {
  val input = readLine(s"$prompt: ")

  if (input.matches("[1-3]")) {
    input.toInt
  } else {
    println("Please enter a number from 1 to 3")
    nextRowOrCol(prompt)
  }
}

The entire code
As the heading says, here's the entire code. You'll notice that it's wayyy longer than what you have currently, mostly because I used tuples, which complicated everything, but also because your original solution didn't have a lot of functionality.
I'm sure you can find a way to make it shorter, especially if you use your own case classes to represent everything. I've made almost every function that deals with tiny details like destructuring tuples private, but the public functions shouldn't need to be changed much even if you do decide to make a case class Board or something like that.
import scala.io.StdIn.readLine
import scala.annotation.tailrec

object TicTacToe {

  type Player = Char
  type Move = (Int, Int)
  type Row = (Player, Player, Player)
  type Board = (Row, Row, Row)

  val winCases = Set(
    Set((1, 1), (1, 2), (1, 3)),
    Set((2, 1), (2, 2), (2, 3)),
    Set((3, 1), (3, 2), (3, 3)),
    Set((1, 1), (2, 1), (3, 1)),
    Set((1, 2), (2, 2), (3, 2)),
    Set((1, 3), (2, 3), (3, 3)),
    Set((1, 1), (2, 2), (3, 3)),
    Set((1, 3), (2, 2), (3, 1)),
  )

  val default = ' '
  val player1 = 'x'
  val player2 = 'o'

  def main(args: Array[String]) = {
    println("Welcome to TicTacToe!")
    println("To play, enter the row and column of the cell where you want to move when prompted")
    println("Both the row and column must be numbers from 1 to 3")

    runGame()
  }

  def runGame() = {
    @tailrec
    def playRound(board: Board, curr: Player): Option[Player] = {
      printBoard(board)
      println(s"Player $curr's move")
      val move = nextMove(board)
      val newBoard = moveTo(curr, move, board)
      findWinner(newBoard) match {
        case Right(possWinner) => possWinner
        case Left(_)           => playRound(newBoard, nextPlayer(curr))
      }
    }

    val startBoard = (
      (default, default, default),
      (default, default, default),
      (default, default, default)
    )

    val winner = playRound(startBoard, player1)
    winner match {
      case Some(player) => println(s"Player $player won!")
      case None         => println("Tie")
    }
  }

  def findWinner(board: Board): Either[Unit, Option[Player]] =
    if (isWinner(player1, board)) Right(Some(player1))
    else if (isWinner(player2, board)) Right(Some(player2))
    else if (isTie(board)) Right(None)
    else Left(())

  def moveTo(player: Player, move: Move, board: Board): Board = {
    val (row0, row1, row2) = board
    val (r, c) = move

    def updateTuple[T](tup: (T, T, T), ind: Int)(f: T => T): (T, T, T) =
      ind match {
        case 1 => tup.copy(_1 = f(tup._1))
        case 2 => tup.copy(_2 = f(tup._2))
        case 3 => tup.copy(_3 = f(tup._3))
      }

    updateTuple(board, r) {
      row => updateTuple(row, c)(_ => player)
    }
  }

  def isWinner(player: Player, board: Board): Boolean =
    winCases.exists(winCase =>
      winCase.forall(move => playerAt(move, board) == player)
    )

  def isTie(board: Board): Boolean = !board.productIterator.exists {
    row => row.asInstanceOf[Row].productIterator.contains(default)
  }

  def playerAt(move: Move, board: Board): Player = {
    val (r, c) = move
    elementAt(elementAt(board, r), c)
  }

  private def elementAt[T](tup: (T, T, T), ind: Int): T =
    ind match {
      case 1 => tup._1
      case 2 => tup._2
      case 3 => tup._3
    }

  @tailrec
  def nextMove(board: Board): Move = {
    val move = (nextRowOrCol("Row"), nextRowOrCol("Column"))

    if (isValid(move, board)) {
      move
    } else {
      println("That move is already taken. Please enter a different move.")
      nextMove(board)
    }
  }

  private def nextRowOrCol(prompt: String): Int = {
    val input = readLine(s"$prompt: ")

    if (input.matches("[1-3]")) {
      input.toInt
    } else {
      println("Please enter a number from 1 to 3")
      nextRowOrCol(prompt)
    }
  }

  def isValid(move: Move, board: Board): Boolean =
    playerAt(move, board) == default

  def nextPlayer(curr: Player): Player =
    if (curr == player1) player2
    else player1

  def printBoard(board: Board): Unit =
    print(
      "__________________\n" +
      tup2String(
        mapTuple(board) {row => tup2String(row, "|")},
        "------\n"
      )
    )

  private def tup2String[T](tup: (T, T, T), sep: String): String =
    s"${tup._1}$sep${tup._2}$sep${tup._3}\n"

  private def mapTuple[T, R](tup: (T, T, T))(f: T => R): (R, R, R) =
    (f(tup._1), f(tup._2), f(tup._3))
}

An alternative way of storing the board
Working with tuples is really annoying, and even with case classes, you'd have to define your own methods and stuff. A nicer way to store the board would be to just maintain a list of all the moves anyone's ever made. Every move should contain where that move was made and the player who made that move, so let's makes these two types. By the way, the Move from before is more like Coord here.
type Coord = (Int, Int)
type Move = (Coord, Player)

Now everywhere we use board: Board, we just replace that with moves: List[Move].
playRound doesn't change all that much. The variable move now has to include the current player because of how we defined Move above, and the newMoves variable (analogous to newBoard) is constructed by prepending moves to the pre-existing list of moves, which is a lot easier than creating a moveTo function that does all sorts of crazy stuff inside. Everywhere else, just remember that board has been replaced with moves.
@tailrec
def playRound(moves: List[Move], curr: Player): Option[Player] = {
  println(s"Player $curr's move")
  val move = (nextMove(moves), curr)
  val newMoves = move :: moves
  printBoard(newMoves)
  findWinner(newMoves) match {
    case Right(possWinner) => possWinner
    case Left(_)           => playRound(newMoves, nextPlayer(curr))
  }
}

runGame only has 1 change: instead of manually creating a variable called startBoard filled with the default character (' '), you can use List.empty (or Nil):
val winner = playRound(List.empty, player1)

playerAt is a lot simpler now. It tries to find a move with the given coordinates, and if no move with those coordinates is found in our List[Move], then default is chosen.
def playerAt(coord: Coord, moves: List[Move]): Player =
    moves.find(move => move._1 == coord).map(_._2).getOrElse(default)

isTie is also a lot simpler - just check if 9 moves have been made!
def isTie(moves: List[Move]): Boolean = moves.size == 9

printBoard is the only one with big-ish changes (the good kind). You can just use map and mkString now that we're not using tuples.
def printBoard(moves: List[Move]): Unit =
    print(
      1 to 3 map { r =>
          1 to 3 map { c =>
            playerAt((r, c), moves)
          } mkString "|"
      } mkString ("__________\n", "\n------\n", "\n")
    )

The entire code:
import scala.io.StdIn.readLine
import scala.annotation.tailrec

object TicTacToe2 {

  type Player = Char
  type Coord = (Int, Int)
  type Move = (Coord, Player)

  val winCases: Set[Set[Coord]] = Set(
    Set((1, 1), (1, 2), (1, 3)),
    Set((2, 1), (2, 2), (2, 3)),
    Set((3, 1), (3, 2), (3, 3)),
    Set((1, 1), (2, 1), (3, 1)),
    Set((1, 2), (2, 2), (3, 2)),
    Set((1, 3), (2, 3), (3, 3)),
    Set((1, 1), (2, 2), (3, 3)),
    Set((1, 3), (2, 2), (3, 1))
  )

  val default = ' '
  val player1 = 'x'
  val player2 = 'o'

  def main(args: Array[String]) = {
    println("Welcome to TicTacToe!")
    println(
      "To play, enter the row and column of the cell where you want to move when prompted"
    )
    println("Both the row and column must be numbers from 1 to 3")
    printBoard(List.empty)

    runGame()
  }

  def runGame() = {
    @tailrec
    def playRound(moves: List[Move], curr: Player): Option[Player] = {
      println(s"Player $curr's move")
      val move = (nextMove(moves), curr)
      val newMoves = move :: moves
      printBoard(newMoves)
      findWinner(newMoves) match {
        case Right(possWinner) => possWinner
        case Left(_)           => playRound(newMoves, nextPlayer(curr))
      }
    }

    val winner = playRound(List.empty, player1)
    winner match {
      case Some(player) => println(s"Player $player won!")
      case None         => println("Tie")
    }
  }

  def findWinner(moves: List[Move]): Either[Unit, Option[Player]] =
    if (isWinner(player1, moves)) Right(Some(player1))
    else if (isWinner(player2, moves)) Right(Some(player2))
    else if (isTie(moves)) Right(None)
    else Left(())

  def isWinner(player: Player, moves: List[Move]): Boolean =
    winCases.exists { winCase =>
      winCase.forall(move => playerAt(move, moves) == player)
    }

  def isTie(moves: List[Move]): Boolean = moves.size == 9

  def playerAt(coord: Coord, moves: List[Move]): Player =
    moves.find(move => move._1 == coord).map(_._2).getOrElse(default)

  @tailrec
  def nextMove(moves: List[Move]): Coord = {
    val coord = (nextRowOrCol("Row"), nextRowOrCol("Column"))

    if (isValid(coord, moves)) {
      coord
    } else {
      println("That move is already taken. Please enter a different move.")
      nextMove(moves)
    }
  }

  private def nextRowOrCol(prompt: String): Int = {
    val input = readLine(s"$prompt: ")

    if (input.matches("[1-3]")) {
      input.toInt
    } else {
      println("Please enter a number from 1 to 3")
      nextRowOrCol(prompt)
    }
  }

  def isValid(coord: Coord, moves: List[Move]): Boolean =
    playerAt(coord, moves) == default

  def nextPlayer(curr: Player): Player =
    if (curr == player1) player2
    else player1

  def printBoard(moves: List[Move]): Unit =
    print(
      1 to 3 map { r =>
          1 to 3 map { c =>
            playerAt((r, c), moves)
          } mkString "|"
      } mkString ("__________\n", "\n------\n", "\n")
    )
}

By the way, here's a small change you can make concerning the isValid method. Instead of returning a boolean, return an Option with which you can do getOrElse. If you write a validate function like this:
def validate(coord: Coord, moves: List[Move]): Option[Coord] =
    Option.when(playerAt(coord, moves) == default)(coord)

you can use it in nextMove like this, which looks much more idiomatic. The only thing is that you'll have to drop the tailrec annotation.
def nextMove(moves: List[Move]): Coord = {
  val coord = (nextRowOrCol("Row"), nextRowOrCol("Column"))

  validate(coord, moves).getOrElse {
    println("That move is already taken. Please enter a different move.")
    nextMove(moves)
  }
}

Let me know if there's anything I did wrong or can improve.


Block_breaker clone in pygame with simple edge detection

First off, according to this online tool, you have ~119 PEP8 violations. So, for my first tip, I'm going to reccomend reading Python's official style guide, PEP8. The style guide essentially tells you how to format your code, so I'm not going to give you any tips on that in this answer.
Secondly, your pool class seems weird, partially because it seems like you don't necessarily need it, like it's just a static class with variables, and functions that modify those variables. In that case, I'd recommend abandoning the pool class completely, and just having global variables, with functions that modify those variables.
On your pool class again, you've misspelled __init__ and put _init_ instead.
Sorry if this sounds rude, but some of the names that you've given your variables and functions are awful. I mean, I have no idea what the variable pigger, or thung does just by looking at it. You also shouldn't abbreviate already short variable names. For example, block, does not need to become blk.
Avoid importing multiple files on one line. This helps weed out certain errors if one of the imported files isn't working correctly. You should import modules like this.

import pygame
import sys
import time
import random

Your play function could be separated into multiple functions, like a create_blocks function, or check_for_quit.
You should define SCREEN_WIDTH and SCREEN_HEIGHT variables. This gets rid of "magic numbers", and helps with overall readability.
Finally any variables with values that don't change should be constant. For example, gameover should be GAME_OVER_IMAGE.

Anyways, I hope this helped!


res = [];
for i in range(1, target+1):
  if target % i == 0:
    res.append(i)

This has a couple notable things. First, Python doesn't use semi-colons in the vast majority of cases. They aren't necessary. Also, whenever you have a loop whose only purpose is to create a list, you'll likely want a list comprehension instead:

res = [i for i in range(1, target + 1) if target % i == 0]

Whatever is on the left end (i in this case) gets appended to a new list. It can also be "guarded" using an if on the right end. Once you get used to seeing this syntax, it tends to read really nicely.

I also wouldn't write target+1 without any spaces. PEP8 recommends one space on each side of a binary operator unless you have a good reason to omit them.

result = 1
for x in compare_sets:
     result = result * x
return result

The line in the loop could make use of a compound-assignment operator to be more terse:

result *= x

This loop though is just carrying out a transformation of an "accumulator" (result). This is the ideal case for reduce:

from operator import mul
from functools import reduce

result = reduce(mul, compare_sets)

reduce is a function from Functional Programming. It and map are the standard ways of working with lists at a low level in FP. Python decided to tuck it away in functools, but it's a very useful function. And mul is just:

def mul(a, b):
    "Same as a * b."
    return a * b

operator contains many similar "first order" versions of operators for cases like this.

I wouldn't have top-level code like you do here. If you try to load this file by importing it or opening it in a REPL, the whole thing is forced to run, even if you just wanted to use or test a single function. Everything that isn't a function or constant definition should ideally be tucked away inside a main. That way you can control when the code is executed. I'd also be hesitant to call quit here. That also makes code harder to work with. Again, if you have this open in a REPL, quit will kill the REPL. I'd just change those quits to returns once this is inside a main.

And your naming isn't too bad. I would use much more descriptive names than i and k though unless those are straight from the equations involved (and even then description always helps).


Change lines like this:

    for word in line1.split(" "):

To lines like:

    for word in (w.strip() for w in line1.split(" ")):

UPDATE:

Here are two ways you could tighten up your function:

1:

    def compute_word_importance(fpath1,fpath2):

        count = collections.Counter()
        with open(fpath1, 'rt', encoding='UTF-8') as fp:
            for line in f:
                count.update([w.strip() for word in line.split()])
        with open(fpath2, 'rt', encoding='UTF-8') as fp:
            for line in fp:
                count.subtract([w.strip() for word in line.split()])

        return len(counter) and counter or none

2:

    def compute_word_importance(fpath1,fpath2):

        def get_words(path):
            words = []
            with open(path, 'rt', encoding='UTF-8') as fp:
                for line1 in f:
                    words.extend([w.strip() for word in line.split()])

        counter = collections.Counter(get_words(fpath1))
        counter.subtract(get_words(fpath2))

        return len(counter) and counter or none


Truncate text to some number of words when clicked

A few thoughts:

/\s/ is probably not the best thing to be searching for.  I would consider using /\b/ to look for all word boundaries, not just spaces.
It seems the $elem here would be a jQuery collection, however you are treating it is a single element without using things such a $.each() to be able to apply to multiple elements.  Your function fails if more than one element is passed in $elem.  This is a bad way to think about writing code against jQuery.  You should be thinking about working against collections, not single elements.
Since you are using jQuery, I would strongly suggest writing this as a jQuery plug-in such that you can better attach the behavior to a collection of elements (i.e. $('.some_class').truncatable({count: ...});.
Is word count really meaningful as a way to determine how you are truncating? I would think better logic would be to look for first word boundary at a location less than X number of characters in string as your truncation point.  That way you get more consistent size of truncated text, not subject to vary greatly based on overly long or overly short words in the content.
In the second example, it seems odd to hard-code nested <p>, .read_more, etc. into the function. Why would $elem not already be whatever element you want to work with (the <p> in this case)?  What if in the future you wanted to apply this to a <div> that does not have a <p> nested inside of it? Your code will break. You are limiting the usefulness of your code in doing this.
You should get in the habit of using strict comparisons (===, !==) by default instead of loose comparisons (==, !=).  This will make your code less fragile to unexpected truthy/falsey behavior, and this easier to maintain/debug.  I would say the loose comparisons should only be used when you have a very specific use case for doing so and would ideally include a comment in such cases explaining why such loose comparison is appropriate for that case.
I question the approach of storing the full/truncated texts in an alternate DOM elements.  I would think that perhaps when this truncation behavior is applied to an element, that you might want to store the full text (and perhaps the truncated text as well, if you want to avoid recalculation) in a data attribute.  If you take this approach, I would suggest using $.text() or native javascript textContent as means to make this change on click vs. $.html() or innerHTML for performance reasons.  You definitely don't want to be inserting nodes in DOM using $.before() here.
I know this is code review and we are reviewers should focus on the code presented, but I would suggest that you think about whether you are re-inventing the wheel here.  There are several plug-ins for jQuery that do this already - https://plugins.jquery.com/tag/truncate/


Good job for a first experience in Python! You can improve your code a little by looking at these recommendations:

To choose a random integer, you could simply use random.randrange(0,11)
You should probably not import at the function level either, try writing your import statements at the top of your file.
The game() function is called recursively; you shouldn't do that. You could have an infinite loop that fires game() back when exited.
Personally, I wouldn't use lists with "yes" and "no" values, try something like

if "y" in choice.lower():
    return True
else:
    return False

Last but not least, you should check if the number entered is an integer. If it is not, ask the user to enter a valid integer until they do so.


The game2048 function is short, which is good. It could be more clear to the casual reader.
The 2nd grid assignment uses zip(*grid), which is fine, but it would benefit by being broken out as a named helper function, which the third grid assignment could also use. Helper names often do a better documentation job than comments do.

The merge function uses the identifier transposed, where perhaps row would have sufficed, without confusingly calling to mind the 90-degree aspect of matrix transpose.

The magic number 4 is distracting - please assign a board size constant and use that.

The code lacks comments, which is not necessarily a problem, especially since it tries hard to use meaningful identifiers. Its clarity would benefit from unit tests (or docstring tests) showing before / after effects on a grid or row. The "output should be" narrative is helpful; I'm suggesting writing it as a TestCase. In the course of doing that, you may find it useful for coverage or didactic purposes to break out the occasional helper function.


Euclid's algorithm GCD finder and fraction simplifier

First thing: let's make the getGcd static:

public static int gcd(int a, int b){
    if(a % b == 0)
        return b;
    else
        return gcd(b, a % b);
}

This makes things faster if you want to stick with recursion since random instances are not made on every recursive step (otherwise, the while loop tends to win).

In order to handle the signs, I would implement the following (to make later code more readable):

public static boolean isNeg(int a){
    return a < 0;
}

and add a condition to your constructor (this would make this.nume the only possible negative value, beautifying printing and making later code easier):

public Rational(int n, int d){
    if(isNeg(n) == isNeg(d)){
         this.nume = Math.abs(n);
    }else{
         this.nume = -1*Math.abs(n);
    }
    this.deno = Math.abs(d);
}

Then, reduce would be the following:

public Rational reduce(){
    int tNume = Math.abs(this.nume);
    //Math.max and Math.min get maximal and minimal values. This is great to
    //reduce the amount of code.
    int gcd = gcd(Math.max(tNume, this.deno), Math.min(tNume, this.deno));
    return new Rational(this.nume / gcd, this.deno / gcd);
}

I would actually probably always reduce for efficient comparison and ease of use (especially for math).

Also: consider throwing an error if this.deno is ever 0 in the constructor.


How parse nicely a string into three (or more) pieces?

You can say:

>>> import re
>>> re.split('[:;]', 'NAME:0001;some text')
['NAME', '0001', 'some text']


Get list of files in directory with exclude option

A few things I noticed:

If the exclude array is empty you return an empty list instead of every file.
reversing your logic would allow you to check everything in one statement.
Since you're returning an IEnumerable<string> already, using the yield operator would make sense here.
Accepting an IEnumerable<string> instead of an string[] for the exclude parameter, gives the user more options.  Also this allows you to leverage the LINQ extensions better.

Your code could look something like this:

public static IEnumerable<string> GetFiles(string path, IEnumerable<string> exclude, SearchOption searchOption = SearchOption.AllDirectories)
{
    IEnumerable<FileInfo> files = new DirectoryInfo(path).EnumerateFiles("*.*", searchOption);
    foreach (var filename in files)
    {

        if (!exclude.Any(x => x == filename.Name || (x.StartsWith("*") && x.Contains(filename.Extension))))
        {
            yield return filename.Name;
        }

    }
}


Aiming at your questions, your naming conventions are good. However, in your test you tend to switch between camelCase and words_separated_by_underscores. I would suggest sticking to one or the other (we tend to use underscores). Your algorithm looks good and taking ANeves suggestions will make it look more "Ruby"ish.

However, I am going to suggest a much more efficient way of generating your prime numbers and none prime numbers in your Test. Instead of typing each prime number between 1 and 100 by hand into an Array, you could use the Array#Select method. It takes in an Enumerator, runs a given block against each item passed in, and returns an Array of only the items that return true.

prime_numbers = (1..100).select {|num| num.prime?}

This will given you the same Array you got by typing it all in manually. You can do the same for the none prime numbers.

non_prime_numbers = (1..100).select {|num| num unless num.prime?}

This'll return num only if it is not prime.

It'll save you a lot of typing and it will look more "Ruby"ish.