text:
Q: Int32.Parse vs Single.Parse - ("1,234") and ("1,2,3,4"). Why do int and floating point types parse separator chars differently? In C#:
This throws a FormatException, which seems like it shouldn't:
Int32.Parse("1,234");

This does not, which seems normal:
Single.Parse("1,234");

And surprisingly, this parses just fine:
Single.Parse("1,2,3,4"); //Returns 1234

My local culture is EN-US, so , is the default thousands separator char.
Main question: Why the inconsistency?
Also: Why does Parse("1,2,3,4") work?  It appears to just be removing all instances of the local separator char before parsing.  I know there would be extra runtime overhead in a regex check or something like that, but when would the numeric literal "1,2,3,4" not be a typo?

Related:
C# Decimal.Parse issue with commas

A: mine is es-ES
On these . is the default thousands separator char, and "," the separate character between int and double
So
any parse like "1.2.3,4" gives me "123,40" ( 123.40 on US )
If i put the "." before the "," like "123,4.3" it gives error
but, the same way the questions says, if i put "1.2.3.4" gives me "1234"
So, may be it is a functionality of the .net itself.

A: According to MSDN:

The s parameter contains a number of the form:
[ws][sign]digits[ws]

The s parameter is interpreted using the NumberStyles.Integer style. In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed.

That's it, NumberStyles.Integer disallows the Parse method to use the thousands separator, whereas Single.Parse uses by default NumberStyles.Float and NumberStyles.AllowThousands. You can change this behaviour by specifiying the second argument as NumberStyles:
Int32.Parse("1,234", NumberStyles.AllowThousands); //works

Single.Parse ignores the grouping and doesn't use culture-specific NumberGroupSizes at all, and only determines if the character is a group or decimal separator. The group sizes are used only when formatting numbers.

A: For the first case, from Microsoft Source Code Reference, by default Int32.Parse implements NumberStyles.Integer but not NumberStyles.AllowThousands
public static int Parse(String s) {
    return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

Thus any comma separator is not allowed. This:
Int32.Parse("1,234");

or
Int32.Parse("1.234");

will both be wrong. In any culture.
To fix it, NumberStyles.AllowThousands must be added to the NumberStyles which will allow "1,234" to be parsed in EN-US culture:
Int32.Parse("1,234", NumberStyles.Integer | NumberStyles.AllowThousands);

But
Int32.Parse("1.234", NumberStyles.Integer | NumberStyles.AllowThousands);

Will still throw an Exception.

For the second case, according to Microsoft Code Source Reference, the default style for Single.Parse is:
public static float Parse(String s) {
    return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}

Which allows thousands separator. And "," is recognized as thousand separator in EN-US culture, for Single.Parse and thus you get the second case parsed correctly
Single.Parse("1,234"); //OK

And obviously "1.234" will also be correct, except that "." is not recognized as thousand separators but decimal separator.

As for the third case, Internally, Single.Parse calls TryStringToNumber, and Parse.Number which would simply ignore the thousand separators. Thus you get:
Single.Parse("1,2,3,4"); //Returns 1234

Because it is equivalent as
Single.Parse("1234"); //Returns 1234


text:
Q: Grabbing variables from a URL into a MC Query So this is what i have so far, but for some reason it's not working
<?PHP
        require MCQuery . '/MinecraftQuery.class.php';

    try
    {
        $Query->Connect( '$_GET['ip'];', $_GET['port'] );

    }
    catch( MinecraftQueryException $e )
    {
        echo $e->getMessage( );
    }

        if(($Players = $Query->GetPlayers()) !== false) {
            foreach($Players as $Player) {
            echo "
                  ";
            }
        }
    ?>

Thanks in advance :)

A: How about this, You have syntax error in your code
  $Query->Connect( $_GET['ip'], $_GET['port'] );

instead of
 $Query->Connect( '$_GET['ip'];', $_GET['port'] );

A: Here is my own query to my Minecraft Server. It's working on my server and I have MinecraftQuery.class.php in the same directory so be sure to run it from there.
            <?php
                    require __DIR__ . '/MinecraftQuery.class.php';

                    $Query = new MinecraftQuery( );

                    try
                    {
                            $Query->Connect( '192.99.0.12', 25565 );
                            foreach ($Query->GetPlayers() as $arrayItem)
                            {
                            echo " " ;
                            }
                    }
                    catch( MinecraftQueryException $e )
                    {
                            echo $e->getMessage( );
                    }
            ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Call action methods within same route I'm trying to call an "action" method within the same route.
I get an error when I'm doing something like that:

Nothing handled the action 'refreshFoo'. If you did handle the action,
  this error can be caused by returning true from an action handler in a
  controller, causing the action to bubble.

Here is my code:
export default Ember.Route.extend({
   setupController: function (controller, model) {
      this._super(controller, model);
      this.send('refreshFoo');
   },

   actions: {
        refreshFoo: function () {
            alert('refreshed!');
        }
    }
});

http://emberjs.jsbin.com/rununifupono/2/edit
Any idea what is wrong? Am I using the send method properly?
Thanks

A: The error is because inside setupController the IndexRoute is not fully materialized so when you send the action it can only be handled by the ApplicationRoute
In order for it to work the way you would like, you need to wrap the call to send in an Ember.run.later
like this
Ember.run.later(this, function(){
  this.send('refreshFoo')
});

working bin: http://emberjs.jsbin.com/rununifupono/7/edit

A: define the action inside your controller. and call controller.send('action');
http://jsbin.com/porer/1/


text:
Q: How do I run a separate version of jquery in shopify for my flexslider plugin? I have a flexslider pano on my index page, to get it work properly I have to use 'jQuery' version '1.6.2-1.7.2'. If I change the version to 1.7.3 or higher, the slider has a glitchy animation.  The problem is that I have a drop down menu that only functions using versions 1.7.3 or higher in the same page.
I am trying to figure out how to make flexslider run on version 1.7.2 or lower, without affecting the rest of the site.
Here's the script for the flexslider:
<script type="text/javascript" charset="utf-8">
  $(window).load(function() {
  $('.flexslider').flexslider({
    animation: "fade",
    animationLoop: true,
    controlNav: false
  });
});
</script>

I took some suggestions on overflow but they don't seem to work on Shopify.
Such as using jQuery.noConflict();
Here's my version:
 <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type='text/javascript'>

 var $jq = jQuery.noConflict();

</script>

<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.3/jquery.min.js"></script>

<script type="text/javascript" charset="utf-8">
  $j(window).load(function() {
  $j('.flexslider').flexslider({
    animation: "fade",
    animationLoop: true,
    controlNav: false
  });
});
</script>

The website is enrou.co, I currently disabled the jQuery so you can see that the pano is glitchy when you switch between images. The only way for me to disable the animations is to run jQuery version 1.7.2 or earlier, but that disables the functionality of other plugins.


text:
Q: When one worker thread fails, how to abort remaining workers? I have a program which spawns multiple threads, each of which executes a long-running task.  The main thread then waits for all worker threads to join, collects results, and exits.
If an error occurs in one of the workers, I want the remaining workers to stop gracefully, so that the main thread can exit shortly afterwards.
My question is how best to do this, when the implementation of the long-running task is provided by a library whose code I cannot modify.
Here is a simple sketch of the system, with no error handling:
void threadFunc()
{
    // Do long-running stuff
}

void mainFunc()
{
    std::vector<std::thread> threads;

    for (int i = 0; i < 3; ++i) {
        threads.push_back(std::thread(&threadFunc));
    }

    for (auto &t : threads) {
        t.join();
    }
}

If the long-running function executes a loop and I have access to the code, then
execution can be aborted simply by checking a shared "keep on running" flag at the top of each iteration.
std::mutex mutex;
bool error;

void threadFunc()
{
    try {
        for (...) {
            {
                std::unique_lock<std::mutex> lock(mutex);
                if (error) {
                    break;
                }
            }
        }
    } catch (std::exception &) {
        std::unique_lock<std::mutex> lock(mutex);
        error = true;
    }
}

Now consider the case when the long-running operation is provided by a library:
std::mutex mutex;
bool error;

class Task
{
public:
    // Blocks until completion, error, or stop() is called
    void run();

    void stop();
};

void threadFunc(Task &task)
{
    try {
        task.run();
    } catch (std::exception &) {
        std::unique_lock<std::mutex> lock(mutex);
        error = true;
    }
}

In this case, the main thread has to handle the error, and call stop() on
the still-running tasks.  As such, it cannot simply wait for each worker to
join() as in the original implementation.
The approach I have used so far is to share the following structure between
the main thread and each worker:
struct SharedData
{
    std::mutex mutex;
    std::condition_variable condVar;
    bool error;
    int running;
}

When a worker completes successfully, it decrements the running count.  If
an exception is caught, the worker sets the error flag.  In both cases, it
then calls condVar.notify_one().
The main thread then waits on the condition variable, waking up if either
error is set or running reaches zero.  On waking up, the main thread
calls stop() on all tasks if error has been set.
This approach works, but I feel there should be a cleaner solution using some
of the higher-level primitives in the standard concurrency library.  Can
anyone suggest an improved implementation?
Here is the complete code for my current solution:
// main.cpp

#include <chrono>
#include <mutex>
#include <thread>
#include <vector>

#include "utils.h"

// Class which encapsulates long-running task, and provides a mechanism for aborting it
class Task
{
public:
    Task(int tidx, bool fail)
    :   tidx(tidx)
    ,   fail(fail)
    ,   m_run(true)
    {

    }

    void run()
    {
        static const int NUM_ITERATIONS = 10;

        for (int iter = 0; iter < NUM_ITERATIONS; ++iter) {
            {
                std::unique_lock<std::mutex> lock(m_mutex);
                if (!m_run) {
                    out() << "thread " << tidx << " aborting";
                    break;
                }
            }

            out() << "thread " << tidx << " iter " << iter;
            std::this_thread::sleep_for(std::chrono::milliseconds(100));

            if (fail) {
                throw std::exception();
            }
        }
    }

    void stop()
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_run = false;
    }

    const int tidx;
    const bool fail;

private:
    std::mutex m_mutex;
    bool m_run;
};

// Data shared between all threads
struct SharedData
{
    std::mutex mutex;
    std::condition_variable condVar;
    bool error;
    int running;

    SharedData(int count)
    :   error(false)
    ,   running(count)
    {

    }
};

void threadFunc(Task &task, SharedData &shared)
{
    try {
        out() << "thread " << task.tidx << " starting";

        task.run(); // Blocks until task completes or is aborted by main thread

        out() << "thread " << task.tidx << " ended";
    } catch (std::exception &) {
        out() << "thread " << task.tidx << " failed";

        std::unique_lock<std::mutex> lock(shared.mutex);
        shared.error = true;
    }

    {
        std::unique_lock<std::mutex> lock(shared.mutex);
        --shared.running;
    }

    shared.condVar.notify_one();
}

int main(int argc, char **argv)
{
    static const int NUM_THREADS = 3;

    std::vector<std::unique_ptr<Task>> tasks(NUM_THREADS);
    std::vector<std::thread> threads(NUM_THREADS);

    SharedData shared(NUM_THREADS);

    for (int tidx = 0; tidx < NUM_THREADS; ++tidx) {
        const bool fail = (tidx == 1);
        tasks[tidx] = std::make_unique<Task>(tidx, fail);
        threads[tidx] = std::thread(&threadFunc, std::ref(*tasks[tidx]), std::ref(shared));
    }

    {
        std::unique_lock<std::mutex> lock(shared.mutex);

        // Wake up when either all tasks have completed, or any one has failed
        shared.condVar.wait(lock, [&shared](){
            return shared.error || !shared.running;
        });

        if (shared.error) {
            out() << "error occurred - terminating remaining tasks";
            for (auto &t : tasks) {
                t->stop();
            }
        }
    }

    for (int tidx = 0; tidx < NUM_THREADS; ++tidx) {
        out() << "waiting for thread " << tidx << " to join";
        threads[tidx].join();
        out() << "thread " << tidx << " joined";
    }

    out() << "program complete";

    return 0;
}

Some utility functions are defined here:
// utils.h

#include <iostream>
#include <mutex>
#include <thread>

#ifndef UTILS_H
#define UTILS_H

#if __cplusplus <= 201103L
// Backport std::make_unique from C++14
#include <memory>
namespace std {

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(
            Args&& ...args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

} // namespace std
#endif // __cplusplus <= 201103L

// Thread-safe wrapper around std::cout
class ThreadSafeStdOut
{
public:
    ThreadSafeStdOut()
    :   m_lock(m_mutex)
    {

    }

    ~ThreadSafeStdOut()
    {
        std::cout << std::endl;
    }

    template <typename T>
    ThreadSafeStdOut &operator<<(const T &obj)
    {
        std::cout << obj;
        return *this;
    }

private:
    static std::mutex m_mutex;
    std::unique_lock<std::mutex> m_lock;
};

std::mutex ThreadSafeStdOut::m_mutex;

// Convenience function for performing thread-safe output
ThreadSafeStdOut out()
{
    return ThreadSafeStdOut();
}

#endif // UTILS_H

A: I've been thinking about your situation for sometime and this maybe of some help to you. You could probably try doing a couple of different methods to achieve you goal. There are 2-3 options that maybe of use or a combination of all three. I will at minimum show the first option for I'm still learning and trying to master the concepts of Template Specializations as well as using Lambdas.

*

*Using a Manager Class

*Using Template Specialization Encapsulation

*Using Lambdas.

Pseudo code of a Manager Class would look something like this:
class ThreadManager {
private:
    std::unique_ptr<MainThread> mainThread_;
    std::list<std::shared_ptr<WorkerThread> lWorkers_;  // List to hold finished workers
    std::queue<std::shared_ptr<WorkerThread> qWorkers_; // Queue to hold inactive and waiting threads.
    std::map<unsigned, std::shared_ptr<WorkerThread> mThreadIds_; // Map to associate a WorkerThread with an ID value.
    std::map<unsigned, bool> mFinishedThreads_; // A map to keep track of finished and unfinished threads.

    bool threadError_; // Not needed if using exception handling
public:
    explicit ThreadManager( const MainThread& main_thread );

    void shutdownThread( const unsigned& threadId );
    void shutdownAllThreads();

    void addWorker( const WorkerThread& worker_thread );
    bool isThreadDone( const unsigned& threadId );

    void spawnMainThread() const; // Method to start main thread's work.

    void spawnWorkerThread( unsigned threadId, bool& error );

    bool getThreadError( unsigned& threadID ); // Returns True If Thread Encountered An Error and passes the ID of that thread,

};

Only for demonstration purposes did I use bool value to determine if a thread failed for simplicity of the structure, and of course this can be substituted to your like if you prefer to use exceptions or invalid unsigned values, etc.
Now to use a class of this sort would be something like this: Also note that a class of this type would be considered better if it was a Singleton type object since you wouldn't want more than 1 ManagerClass since you are working with shared pointers.
SomeClass::SomeClass( ... ) {
    // This class could contain a private static smart pointer of this Manager Class
    // Initialize the smart pointer giving it new memory for the Manager Class and by passing it a pointer of the Main Thread object

   threadManager_ = new ThreadManager( main_thread ); // Wouldn't actually use raw pointers here unless if you had a need to, but just shown for simplicity
}

SomeClass::addThreads( ... ) {
    for ( unsigned u = 1, u <= threadCount; u++ ) {
         threadManager_->addWorker( some_worker_thread );
    }
}

SomeClass::someFunctionThatSpawnsThreads( ... ) {
    threadManager_->spawnMainThread();

    bool error = false;
    for ( unsigned u = 1; u <= threadCount; u++ ) {
        threadManager_->spawnWorkerThread( u, error );

        if ( error ) { // This Thread Failed To Start, Shutdown All Threads
            threadManager->shutdownAllThreads();
        }
    }

    // If all threads spawn successfully we can do a while loop here to listen if one fails.
    unsigned threadId;
    while ( threadManager_->getThreadError( threadId ) ) {
         // If the function passed to this while loop returns true and we end up here, it will pass the id value of the failed thread.
         // We can now go through a for loop and stop all active threads.
         for ( unsigned u = threadID + 1; u <= threadCount; u++ ) {
             threadManager_->shutdownThread( u );
         }

         // We have successfully shutdown all threads
         break;
    }
}

I like the design of manager class since I have used them in other projects, and they come in handy quite often especially when working with a code base that contains many and multiple resources such as a working Game Engine that has many assets such as Sprites, Textures, Audio Files, Maps, Game Items etc. Using a Manager Class helps to keep track and maintain all of the assets. This same concept can be applied to "Managing" Active, Inactive, Waiting Threads, and knows how to intuitively handle and shutdown all threads properly. I would recommend using an ExceptionHandler if your code base and libraries support exceptions as well as thread safe exception handling instead of passing and using bools for errors. Also having a Logger class is good to where it can write to a log file and or a console window to give an explicit message of what function the exception was thrown in and what caused the exception where a log message might look like this:
Exception Thrown: someFunctionNamedThis in ThisFile on Line# (x)
    threadID 021342 failed to execute.

This way you can look at the log file and find out very quickly what thread is causing the exception, instead of using passed around bool variables.

A: The implementation of the long-running task is provided by a library whose code I cannot modify.
That means you have no way to synchronize the job done by working threads
If an error occurs in one of the workers,
Let's suppose that you can really detect worker errors; some of then can be easily detected if reported by the used library others cannot i.e.

*

*the library code loops.

*the library code prematurely exit with an uncaught exception.

I want the remaining workers to stop **gracefully**
That's just not possible
The best you can do is writing a thread manager checking on worker thread status and if an error condition is detected it just (ungracefully) "kills" all the worker threads and exits.
You should also consider detecting a looped working thread (by timeout) and offer to the user the option to kill or continue waiting for the process to finish.

A: Your problem is that the long running function is not your code, and you say you cannot modify it. Consequently you cannot make it pay any attention whatsoever to any kind of external synchronisation primitive (condition variables, semaphores, mutexes, pipes, etc), unless the library developer has done that for you.
Therefore your only option is to do something that wrestles control away from any code no matter what it's doing. This is what signals do. For that, you're going to have to use pthread_kill(), or whatever the equivalent is these days.
The pattern would be that

*

*The thread that detects an error needs to communicate that error back to the main thread in some manner.

*The main thread then needs to call pthread_kill() for all the other remaining threads. Don't be confused by the name - pthread_kill() is simply a way of delivering an arbitrary signal to a thread. Note that signals like STOP, CONTINUE and TERMINATE are process-wide even if raised with pthread_kill(), not thread specific so don't use those.

*In each of those threads you'll need a signal handler. On delivery of the signal to a thread the execution path in that thread will jump to the handler no matter what the long running function was doing.

*You are now back in (limited) control, and can (probably, well, maybe) do some limited cleanup and terminate the thread.

*In the meantime the main thread will have been calling pthread_join() on all the threads it's signaled, and those will now return.

My thoughts:

*

*This is a really ugly way of doing it (and signals / pthreads are notoriously difficult to get right and I'm no expert), but I don't really see what other choice you have.

*It'll be a long way from looking 'graceful' in source code, though the end user experience will be OK.

*You will be aborting execution part way through running that library function, so if there's any clean up it would normally do (e.g. freeing up memory it has allocated) that won't get done and you'll have a memory leak. Running under something like valgrind is a way of working out if this is happening.

*The only way of getting the library function to clean up (if it needs it) will be for your signal handler to return control to the function and letting it run to completion, just what you don't want to do.

*And of course, this won't work on Windows (no pthreads, at least none worth speaking of, though there may be an equivalent mechanism).

Really the best way is going to be to re-implement (if at all possible) that library function.


text:
Q: Max line count of one file? How many max number of lines of code one .cs file should hold. Are there any industry standards/best practices?

A: I don't know how much, but there is a number which is considered a best practice.
It's all about maintainability, and there's much more to it than the number of lines in a source file. What about number of methods in a class? Cyclomatic complexity of a method? Number of classes in a project?
It's best to run a code metrics tool on your source code to find out more, like NDepend.

A: As few as possible to do the job required whilst remaining readable.
If you're spilling over into the thousands upon thousands of line you might want to ask yourself what exactly this file is doing and how can you split it up to express the activity better.
Day to day, if I find a class which is more than 1000 lines long I am always suspicious that either the class is responsible for too much, or the responsibility is expressed badly.
However as with every rule of thumb, each case should be assessed on it's own merits.


text:
Q: How can I align both boxes, one in top of the other having same size I am trying to align both of the boxes shown in the code below, using bootstrap flex and grid classes, but somehow both of them have different width.
I tried setting the width of both to width=200px; to see what happened, and flex items lose position.

                                Ingresos

                                + 4,300

                                34%

                                Gastos

                                + 4,300

                                22%

I expect to have both of the specified boxes aligned horizontally, and both having the same width.
Thank you so much,

A: try with table, table-row and table-cell display. Like:

      content1

      content2


text:
Q: Convergence in Probability and lim inf, lim sup I am currently reading a book, where the author has shown that for a sequence of random variables $(Y_n)_{n \in \mathbb{N}}$ $(Y_n \geq 0 $ for all n) and $d<\infty$, it holds.

if:    lim $sup_{n \in \mathbb{N}}  \mathbb{E}[Y_n] \geq d$  and
  lim $inf_{n \in \mathbb{N}} Y_n \leq d$
  then $Y_n$ converges in Probability to $d$

Unfortunetaly i have very little experience in proving convergence in probability.
My first guess was to use Markov inequality, but so far it didnt yield any results.


text:
Q: fread and fwrite parameters in C I am trying to adapt a matlab program to C, my problem is in the fwrite and fread function. On matlab I have:
fid = fopen ('sweep_100_3400.pcm','rb');
s = fread (fid, 'int16');

My doubt is, in C there are two more parameters in fread and fwrite function.
fread(void*, size_t, size_t, FILE*);
fwrite(const void*, size_t, size_t, FILE*);

In my C code I have:
arq = fopen("C:\\Users\\iago_\\Desktop\\MediaMovel\\sweep_100_3400.pcm", "rb");
fread(x, sizeof(double), itera, arq);
fclose(arq);

x is the vector where the data of my file will be saved.
sizeof(double) is the length of the data (I've declared all double)
arq is the pointer to the file.
The third parameter is a size_t, to adapt my matlab program, in this parameter should I use the media length or the vector size?
(I am encoding a moving average, the media length is informed by the user and the vector size is the length of my input file).
For the fwrite function I have the same doubt about the parameters.
arq=fopen("C:\\Users\\iago_\\Desktop\\MediaMovel\\saida_medial_movel_c.pcm", "wb");
fwrite(saida, sizeof(double), itera, arq);
fclose(arq);

A: fread() parameters are
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

where nmemb is multiple of size function of read. So second parameter should be sizeof your vector and third should number of vectors you want to read from file pointer. Also there is but of confusion about matlab fread call. second param in matlab fread call is int16 which is 2 bytes, but in c fread call you have passed second param as sizeof(double) which is 8 bytes.


text:
Q: Amavis / spamassassin setup, how to disable quarantine and get default spamassassin behavior back? I've set up my first mail server that uses amavis. First off, I don't really see the point in amavis if I don't care about viruses. I don't use clamav as it's a huge RAM hog. SpamAssassin has worked just fine before on its own without amavis.
Just this morning I caught some emails stuck in something called a quarantine (amavis feature). I don't know how to disable the quarantine feature entirely. I'm wondering how to get back the default SpamAssassin behavior where it does nothing more than add ***** SPAM <score> ***** to the subject line, and drops it into my inbox.
Server details: Debian 7.5, postfix 2.9.6, amavisd-new 2.7.1, spamassassin 3.3.2.

A: You should put this options on your /etc/amavis/conf.d/50-user file:
$sa_tag_level_deflt  = -999; # add spam info headers if at, or above that level
$sa_tag2_level_deflt = 6.2;  # add 'spam detected' headers at that level
$sa_kill_level_deflt = 6.9;  # triggers spam evasive actions (e.g. blocks mail)
$sa_spam_subject_tag = '**Spam**';

Configure the SPAM confidence level to the ones accordingly to your needs.
If you don't want to manage your score levels, you can set the quarantine directories to undefined ones. To do this add those lines in the same file:
$clean_quarantine_to      = undef;      # local quarantine
$virus_quarantine_to      = undef;      # traditional local quarantine
$banned_quarantine_to     = undef;      # local quarantine
$bad_header_quarantine_to = undef;      # local quarantine
$spam_quarantine_to       = undef;      # local quarantine

If you want to check the information or take a look at additional information here's the Quarantine block on the AMaViS website: http://www.amavis.org/amavisd-new-docs.html#quarantine

A: The best solution I found was simply to put this in /etc/amavis/conf.d/50-user:
$final_spam_destiny=D_PASS;
$final_virus_destiny=D_PASS;

This way bad e-mails are either marked SPAM or INFECTED, but still delivered to the users, without being rejected, blocked nor quarantined.
See AMAVIS documentation


text:
Q: XCloseDisplay hangs I'm working on a small self-written window manager, the project is at the very beginning and there are just a few lines of code communicating with the X server. The problem comes at exit: the program hangs when XCloseDisplay is called.
There is no window manager running while testing, the program just initializes some features, gets the screens and the available windows, call XSelectEvent on the default root and prints out the number of windows retrieved. Then it cleans it's internal data and tries to close the connection with the X server.
At that point it hangs until killed.

A: Solved. The problem was not with X11 but with the compilation process. Some headers were updated but the source file were not. If you have problem like this, remember to delete your object files and build the whole application again.


text:
Q: Table of contents and python dictionaries I've got data stored in an excel file, it looks like this:
Cell A1: Chapter1
Cell A2: Sub-chapter1
Cell A3: Sub-chapter2
Cell A4: Chapter2
Cell A5: Sub-chapter1

It goes on like that for several hundred rows.
Basically, I'd like to store all this in a python dictionary, with the chapters being the keys and the sub-chapters being the values. I'm looking at an efficient way to transfer this data from excel to my python IDLE.
I understand that the ending result should look like:
mydic = {"Chapter1" : [Sub-chapter1, Sub-chapter2], "Chapter2"... }

Spent some time researching this on the internet, but I've absolutely no idea on how to perform this other than manually.
Thanks for your help,


text:
Q: Add custom fields to a page template, admin side I'm adding a page template to the theme I'm currently using. Is there any way to make the admin editor to show some input text fields or other options for the template?
For example, I'd need two textareas.

A: You can do this via JavaScript rather easily. Here are the steps you need to take. I've created a sample (untested) script below as a proof-of-concept for you.
Register your meta box
add_action('add_meta_boxes', 'foo_page_template_meta_box');
function foo_page_template_meta_box(){
    add_meta_box(
        'foo_page_template_options',
        __('Foo Page Template Options'),
        'foo_page_template_options',
        'page'
    );
}

function foo_page_template_options(){
    //Your custom field form goes here
}

Add JavaScript and CSS to admin_head for post.php and post-new.php
add_action('admin_head-post.php', 'foo_page_template_script');
add_action('admin_head-post-new.php', 'foo_page_template_script');

function foo_page_template_script(){
    global $post;

    # Only use this script for pages
    if('page' !== $post->post_type)
        return;

    #Name of page template file
    $file = 'foo_page_template.php';

    $output = "
        <!-- Hide the Meta Box -->
        <style type='text/css'>
            #foo_page_template_options{display:none;}
        </style>

        <script type='text/javascript'>
            jQuery(document).ready(function($){
                var _file = '$file';
                var _meta_box = $('#foo_page_template_options');
                var _page_template = $('#page-template');

                //Show meta box on page load
                if(_file == _page_template.val())
                    _meta_box.show();

                //Sniff changes to the page template dropdown
                _page_template.change(function(){
                    if(_file == _page_template.val())
                        _meta_box.show();
                });
            });
        </script>
    ";
    echo $output;
}

The main premise of this approach is that you load the meta box on all 'page' edit screens, but only show it when the page template select value matches your page template file name.
Hope this helps!


text:
Q: Difference in sorting (Order By) for Date Fields in EntityFramework vs Oracle When the below two queries executed, there is a difference in the result sorting order for the users with exactly same CreatedTime.
Oracle Query Results
Select UserName, CreatedTime from TableA
where CreatedTime > '01-Jan-2014' order by CreatedTime;

User1   12/13/2014 12:38:58 PM
User2   12/23/2014 12:38:58 PM
User3   12/23/2014 12:38:58 PM
User4   12/23/2014 12:38:58 PM
User5   12/23/2014 12:38:58 PM

LINQ Results
 using (var dbContext = new MyDBEntities())
 {
        var users = from x in dbContext.TableA
                    where
                    x.CreatedTime > JanFirst2014
                    orderby x.CreatedTime
                    select user;
 }

User1   12/13/2014 12:38:58 PM
User3   12/23/2014 12:38:58 PM
User2   12/23/2014 12:38:58 PM
User5   12/23/2014 12:38:58 PM
User4   12/23/2014 12:38:58 PM

We can fix this issue by ordering by UserName, But what is the reason for this issue/difference?


text:
Q: Copying source files into a Visual Studio project I've created a new Visual Studio C++ project and I'd like to import copies of a number of C and header files into the project. That is, the files are currently in a folder on my desktop and I'd like to import them such that copies are placed in the newly created project folder.
How would I do this? I've tried using File | New | Project from Existing Code but that just keeps the files in their existing location. I've even tried a simple Ctrl-C and Ctrl-V and again that imported the files but they stayed in the same place on disk.

A: Copy the files to the new location in Windows Explorer, then start Visual Studio and add them as existing items to the project.

A: I think the better solution would be to create a new (empty) project and add your h and cpp files per "Add -> Existing item" in the context menu of "Headers" and "Sources"


text:
Q: SSH from Virtualbox Guest to DynDNS address I have Windows 10 as host with a Manjaro installation as Guest on Virtualbox.
I have set a Debian server on another house with ssh installed. I have setup a dyndns on Debian's network so I can access it remotely.
For example..
From address 12.34.56.78 I ssh to foo.dyndns.org:1234. This port redirects me to 192.168.1.5:22 always as this is my Debian machine and the connection is established. I am able to do this from Windows 10 as well as my android and any other device in 12.34.56.78 or by 3G.
But..
When I try to do this
$ ssh foo.dyndns.org:1234

from the Manjaro Guest in Virtualbox I get the following error:
ssh: Could not resolve hostname foo.dyndns.org:1234: Name or service not known

So I did ifconfig and I saw my inet address was 10.0.2.15. I changed virtualbox's network adapter from NAT to Bridged so I can get a lan ip and I got the host's ip, 192.168.2.4. So I gave it another try and still didn't work.
Also, if i try to connect from vm to server while I'm in the same network
$ ssh user@192.168.2.5:22

it works. In this case virtualbox's network adapter was NAT.
This command works if I try from my android (connectbot).
I can connect the same way from PuTTY from Windows.
So my questions are:

*

*Can it be done?

*If so, how? (and why?)

*Can a VBox Guest get lan ip that's not the same as the host's?
Is there any more information I should provide?
I have searched for a couple of days in  here and on google and all I found where solutions on how someone can ssh INTO a vm. No one (from what I saw) asked the opposite.

A: Checking manual page for ssh reveals the format of command-line options:
ssh [...] [-p port] [...] [user@]hostnamessh

This simply describes, that you need to change
ssh foo.dyndns.org:1234

to
ssh -p 1234 foo.dyndns.org

if the domain resolves correctly to the ip address.


text:
Q: How do you change the link color in a UITextField? Anyone know how to change the link color or the phone number color in a UITextField? It's nice that the detection option automatically changes the color of these things to blue and underlines them. But come on, fluorescent blue? Really? OK, it looks fine on a white background, I guess.
Wishful thinking ...
textField.linkColor = [UIColor notThatAwfulBlue];

A: Can I change the color of auto detected links on UITextView?
For a UITextView, but I guess the solution is still relevant.


text:
Q: Cache-control max-age meta tag not registering I've put this in my head section. It appears in the page source in the browser.
<meta http-equiv="Cache-Control" content="max-age=1209600">

However, when I look in the Chrome extension Live HTTP Headers, it says the following.
Cache-Control: max-age=0
Content-Encoding: gzip
Content-Length: 5849
Content-Type: text/html; charset=utf-8
Date: Sat, 05 Apr 2014 04:29:16 GMT
Expires: Sat, 05 Apr 2014 04:29:16 GMT
Last-Modified: Sat, 05 Apr 2014 03:33:19 GMT

The max-age isn't registering. I've emptied the browser cache but it makes no difference.
Any explanations? This is the site, incidentally.
UPDATES:
Firebug similarly records Cache-Control: max-age=0.
Google also makes clear here that max-age overrides the Expires header (which I don't set) and that you don't need both.

A: When you use tools like Live HTTP Headers, they show you the actual HTTP headers sent by the browser. What they do with meta tags used to simulate HTTP headers is a different issue. We can expect any conflict to be resolved in favor of the actual headers. (This has been normatively specified in HTML specs for Content-Type headers.)
To control cacheing, you should (at least primarily) use server configuration. See Caching Tutorial for Web Authors and Webmasters.


text:
Q: Different AWS snapshots in console vs CLI? When I use the CLI to look at my snapshots, I see many more than the ones I see in the AWS console. I also don't see ones listed on the CLI that are in the console. On the CLI, I am using:
aws ec2 describe-snapshots | sort -k 5 | grep 2014-07

Why aren't they the same?

A: As per the AWS documentation here, describe-snapshots outputs public snapshots, a.o.
I believe what you want is:
aws ec2 describe-snapshots --owner-ids self


text:
Q: How to auto scroll to the last element when screen size increase I have a list. When clicking on an element it will open a new div next to it. When it becomes greater than screen size a horizontal scroll bar added. But I want to focus on the last added element. Every time when an element is added, the screen should be scroll to it. Now I have to manually scroll to the element. But it should be automatically visible.

function childData(_id) {
     var tRow = $(".organogram li").length,
      row = parseInt(_id)+1;
     for (var i = row; i <= tRow; i++) {
         $("#dept-"+i).remove();
     }
     var data =  "
"

     +"

 "
     +"

Tusher1

Designation

"
     +"

Tusher2

Designation

"
     +"

Tusher3

Designation

"
     +"

";
     $(".organogram").append(data);
 }
 function thisNode(_this){
     var _id = $(_this).closest(".team").attr("id").match(/\d+/);

     $(_this).closest("ul").find("li").removeClass( "active" );
     $(_this).addClass( "active" );

 $(_this).closest("ul").prepend($(_this));
     childData(_id);
 }
ul{
 padding:0px;
 list-style-type: none;
 }
 .data {
    float: left;
    width: 260px;

    margin: 10px;
    border-radius: 5px;
}
 .data a{
 text-decoration: none;
 }
 .data ul{
 list-style-type: none;
 }
 .profile{
 height: 55px;
 width: 55px;
 float: left;
 margin: 0px 13px;
 border-radius: 5px;
 }
 .details{
 font-size: 13px;
 }
 li.title {
    overflow: hidden;
    padding: 5px 0;
    cursor: pointer;
    box-shadow: 1px 5px 7px #00000024;
    margin-bottom: 17px;
    border-bottom: 3px solid #7667ff;
    background: #bdcbd026;
}
 .active{
 background:#3868d2d6 !important;
 }

 .details p {
    margin: 0px;
    padding: 0px;
    font-size: 14px;
    line-height: 24px;
    vertical-align: middle;
    font-family: Arial, sans-serif;
}
li.active.title p {
    color: white;
}
.name {
    color: #2700ff;
    font-weight: 600;
    letter-spacing: 2px;
}
.designation {
    color: #09a023;
    letter-spacing: 1px;
}

ul.organogram{
    display: flex;
}

Tusher1

Designation

Tusher2

Designation

Tusher3

Designation

A: You can use document.getElementById().scrollIntoView() function to scroll to newly created element. you can call this function after inserting new elements like below.

function childData(_id) {
     var tRow = $(".organogram li").length,
      row = parseInt(_id)+1;
     for (var i = row; i <= tRow; i++) {
         $("#dept-"+i).remove();
     }
     var data =  "
"

     +"

 "
     +"

Tusher1

Designation

"
     +"

Tusher2

Designation

"
     +"

Tusher3

Designation

"
     +"

";
     $(".organogram").append(data);
      document.getElementById("dept-"+row).scrollIntoView();
 }
 function thisNode(_this){
     var _id = $(_this).closest(".team").attr("id").match(/\d+/);

     $(_this).closest("ul").find("li").removeClass( "active" );
     $(_this).addClass( "active" );

 $(_this).closest("ul").prepend($(_this));
     childData(_id);
 }
ul{
 padding:0px;
 list-style-type: none;
 }
 .data {
    float: left;
    width: 260px;

    margin: 10px;
    border-radius: 5px;
}
 .data a{
 text-decoration: none;
 }
 .data ul{
 list-style-type: none;
 }
 .profile{
 height: 55px;
 width: 55px;
 float: left;
 margin: 0px 13px;
 border-radius: 5px;
 }
 .details{
 font-size: 13px;
 }
 li.title {
    overflow: hidden;
    padding: 5px 0;
    cursor: pointer;
    box-shadow: 1px 5px 7px #00000024;
    margin-bottom: 17px;
    border-bottom: 3px solid #7667ff;
    background: #bdcbd026;
}
 .active{
 background:#3868d2d6 !important;
 }

 .details p {
    margin: 0px;
    padding: 0px;
    font-size: 14px;
    line-height: 24px;
    vertical-align: middle;
    font-family: Arial, sans-serif;
}
li.active.title p {
    color: white;
}
.name {
    color: #2700ff;
    font-weight: 600;
    letter-spacing: 2px;
}
.designation {
    color: #09a023;
    letter-spacing: 1px;
}

ul.organogram{
    display: flex;
}

Tusher1

Designation

Tusher2

Designation

Tusher3

Designation


text:
Q: In E-Invoicing what is the best way to save previous invoice hash with the new inserted invoice and handle concurrent users In E-Invoicing what is the best way to save previous invoice hash with the new inserted invoice  and handle concurrent users ?
should I use message queue ?
what is the best solution with the best performance ?
should I using lock in DB ?
Please advice


text:
Q: Linq to group by and split a datatable - VB.net I have a data table which I was to split as multiple datatables. The structure inside the datatable has three columns
Company Name. Emp Name and Phone
I want to split the whole datatable into multiple datatables each containing all the employees from one company. I hope I am making sense here with my question. I understood linq is the best way to go about doing this, but I have never used linq before and have completely no idea of how to go about doing this.
Can some one give me a lead on how to go about this? Some code example would be highly appreciated.
Thank you

A: You can get your company names and data tables as dictionary using this:
Dim dict = dataTable.AsEnumerable().GroupBy(Function(r) r.Field(Of String)("CompanyName")).ToDictionary(Function(g) g.Key, Function(g) CopyToDataTable)


text:
Q: How to get all files from a folder and his subfolders? Imagine this files paths:

*

*/root/subfolder/filename.csv

*/root/subfolder/subfolder2/filename2.csv
Can I extract data from "filename.csv" and "filename2.csv" without explicitly write their paths?
I want to do something like:
@var = EXTRACT column FROM "/root/{*}.csv" USING Extractors.Csv(skipFirstNRows:1);

Is it possible?

A: Unfortunately, this feature (a Kleene-* like recursive folder navigation) is not yet available in filesets, but is on our long term roadmap. Please file/upvote for this feature at http://aka.ms/adlfeedback.
The current work-around is to have one step wild card EXTRACTs for each level you expect to encounter and then UNION ALL them together. E.g.,
 @d1 = EXTRACT ... FROM "/fixpath/{*}" USING ... ;
 @d2 = EXTRACT ... FROM "/fixpath/{*}/{*}" USING ...;
 @d3 = EXTRACT ... FROM "/fixpath/{*}/{*}/{*}" USING ...;
 ....

 @data =
   SELECT * FROM @d1 UNION ALL SELECT * FROM @d2 UNION ALL SELECT * FROM @d3 UNION ALL ...;

A: Yes you can! The formatting is almost exactly what you thought it would be. It's done through filesets in U-SQL, and they allow you to search entire directories of folders and also extract information from the path. You define wildcard characters of your choice anywhere in the folder path, and then save that character as a virtual column in your extract statement.
DECLARE @file_set_path string = "/Samples/Data/AmbulanceData/vehicle{vid}_{date:MM}{date:dd}{date:yyyy}.csv";

@data =
EXTRACT vehicle_id int,
        entry_id long,
        event_date DateTime,
        latitude float,
        longitude float,
        speed int,
        direction string,
        trip_id int?,
        vid int,  // virtual file set column
        date DateTime // virtual file set column
FROM @file_set_path
USING Extractors.Csv();

Notice the regular wild card character in the path {vid}, and how it's saved in the extract statement as a new column with the same name (that you can then use to filter your query).  The date virtual column is a special feature of filesets that allows you to automatically bundle dates in filesets into a single DateTime object.
Filesets also work in directory paths the same way - you could have a set of subfolders divided by date and version, and use "/Samples/{date:yyyy}/{date:MM}/{date:dd}/{type}/RCV_{vid}.csv" and store the virtual columns identically as above.
Let me know if you have any more questions!


text:
Q: Javascript update for loop value after delete First, my JSFiddle
I have dynamically created content that is supposed to delete when they are clicked. I am using the variable emma to create a click function for each div that is clicked.
Every time I click on a content div, the amount of contents is reduced. As such, I want my emma count to reduce corresponding to its place in the DOM.
So if I click on Content 1, whose emma value in the loop is 1, Content 1 deletes, and in its place is Content 2. I want Content 2 to take its place and have an emma value of 1. Instead, if I click on Content 2 after deleting Content 1, then the value of emma on Content 2 is still 2.
I am ultimately using the emma variable for CRUD features.
How might I adjust to keep my emma value updated after each of my content is deleted?
function digiteditcall(){
    for (emma = 0; emma < mar; emma++){
        (function(emma){
            document.addEventListener('click', function(e){
                let tenille = "content"+emma;
                if ( (e.target && e.target.id == tenille) || (e.target && e.target.parentNode.id == tenille) ){
                    maincontainer.removeChild(document.getElementById(tenille));
                    mar--;
                    console.log(emma);
                }
            });
        })(emma);
    }
}

Again, here is my JSFiddle

A: If you can use jQuery(which is less headache), try this:
 $document.ready(function(){
 $("#maincontainer").click(function(){
 $("#maincontainer").hide();
 })
})

otherwise use ES6 let keyword for your emma which provides block-level scope.

A: I'm not sure, but it looks like you might be over complicating things.
Take a look at this and see if it does what you are expecting.
EDIT: I added the Emma value as a custom data attribute to the element. So you can see it on the DOM as data-emma="X" or with JavaScript via el.dataset.emma

(function cobrakai() {
  let bar = '';
  for (i = 0; i < 5; i++) {
    bar += "
Content " + i + "
";
  }
  maincontainer.innerHTML += bar;
})();

maincontainer.addEventListener('click', reDo);

function reDo(e) {
  if (e.target.nodeName !== 'P') return;
  e.preventDefault();
  e.stopPropagation();
  var nextElIndex = false;
  document.querySelectorAll('#maincontainer p').forEach((el, i) => {
    if(e.target.id == el.id) {
     el.remove();
      nextElIndex = i;
    }else if(nextElIndex !== false){
       el.id = 'content'+ nextElIndex;
       el.textContent = 'Content '+ nextElIndex;
       el.dataset.emma = nextElIndex;
       nextElIndex++;
    }
  });
}


text:
Q: drop,dropRight,take,takeRight vs substring? I am learning Scala from Scala for the Impatient and Chapter 01 exercise has a problem

*What do the take, drop, takeRight, and dropRight string functions
  do? What advantage or disadvantage do they have over using substring?

The only advantage I see that drop(and flavors) will not throw IndexOutOfBoundsException
For example:
scala> "Hello World!" dropRight 100
res26: String = ""

scala> "Hello World!" substring 100
java.lang.StringIndexOutOfBoundsException: String index out of range: -88
  at java.lang.String.substring(String.java:1919)
  ... 33 elided

What else? Memory efficient?

A: Seems that you are right. All these operations use StringOps.slice method, that delegates to String.substring method.
So, except for the overhead of wrapping string and performing bounds validation it's the same call to substring.

A: The main benefit is that it allows you to treat a String as a sequential collection of characters, much like any other Seq or List instance.
In fact, these methods (and other important transformational functions like map, flatMap and filter) are not implemented in String itself (which is, in fact, simply the Java String class, not a native-Scala class), but in the StringOps class (which extends StringLike -> ... -> SeqLike), and an implicit conversion ensures that a String is converted into a StringOps whenever you need access to these methods.
This means you can pass a String to a list-manipulation function and the function will receive a StringOps instance, work on it like any other SeqLike entity without needing to know it is actually a String, and hand back the results of the manipulation, which StringOps is designed to present back to you as a String.
If you know an entity is a String in a given piece of code, feel free to use the String-specific methods, but the availability of this implicit conversion means that you can also take advantage of a String's "character sequence"-like nature to treat it like any other list in situations where that may be convenient.


text:
Q: R xml encountering and dealing with html entities in an xml file Hello R's XML package users,
I am encountering a weird bug while parsing XML. It has to do with encountering HTML entities like mdash and ndash while parsing XML files.
This is the code I use:
InText = readLines(xmlFileName,n=-1)
Text = xmlValue(xmlRoot(xmlTreeParse(InText,trim=FALSE)))

I am currently eliminating these entities like mdash and ndash using the following
InText = gsub("\\&mdash"," ",InText);
InText = gsub("\\&ndash"," ",InText);

But this can really tedious, as I see the list of possible HTML.4.0 entity list.
Any ideas on how I can eliminate these while parsing the XML files
Thanks a lot for your help and ideas
Shivani

A: If you simply want to remove all named HTML entities, use a regex:
library("XML")

InText <- "<html>\
<head>\
    <title>Test & Test again</title>\
</head>\
    <body>Hello   world</body>\
</html>"

InText <- gsub("\\&[^;]+;","",InText)

Text <-  xmlValue(xmlRoot(xmlTreeParse(InText,trim=FALSE)))

A: Try readHTML in the XML package; it has robust methods that can handle quite a few of these cases. See also Scraping html tables into R data frames using the XML package .


text:
Q: basic boolean states problems I am trying to write a piece of code so that when a key is pressed it will execute something, but then the key will have to be released and then repressed again in order to retrigger the event.  So if the user just holds down the key, it wont keep doing it over and over, instead they will have to press and release repeatedly.
So far, I have:
if(keyLifted)
{
    if(Keyboard.isKeyDown(45))
    {
        keyLifted = false;
        dostuff;
    }
    else if(Keyboard.isKeyDown(46))
    {
        keyLifted = false;
        dostuff();
    }
    else
    {
        keyLifted = true;
    }
}

but this is flawed for obvious reasons (it will only reset the key to being unlifted if the key is already lifted: if the key was pressed, it wont be set to unpressed).  I have tried a couple variations, but I just cant get it to work.
Thanks in advance for any help!

A: You should use a KeyListener to capture keyboard events. Here you go:
public class KeyListenerExample extends JFrame {
    public KeyListenerExample() {
        addKeyListener(new KeyAdapter() {
            private boolean keyLifted;

            public void keyReleased(KeyEvent e) {
                keyLifted = true;
            }

            public void keyPressed(KeyEvent e) {
                keyLifted = false;
                switch (e.getKeyChar()) {
                    case 45:
                        doStuff();
                        break;

                    case 46:
                        doStuff();
                        break;
                }
            }
        });
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void doStuff() {
        System.out.println("stuff");
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new KeyListenerExample();
    }
}

I just kept the keyLifted because it is in your example. But I think for the usual keyboard stuff you don't need it.


text:
Q: RegEx function to parse a command line without using a library I would like to split up a string using a space as my delimiter, but if there are multiple words enclosed in double or single quotes, then I would like them to be returned as one item.
For example if the input string is:
CALL "C:\My File Name With Space" /P1 P1Value /P1 P2Value
The output array would be:
Array[0]=Call
Array[1]=C:\My File Name With Space
Array[2]=/P1
Array[3]=P1Value
Array[4]=/P1
Array[5]=P2Value

How do you use regular expressions to do this? I realize that there are command line parsers. I took a cursory look at a popular one, but it did not handle the situation where you can have multiple parameters with the same name. In any event, instead of learning how to use a command line parsing library (leave that for another day). I'm interested in getting exposed more to RegEx functions.
How would you use a RegEx function to parse this?

A: I wouldn't do it with Regex, for various reasons shown above.
If I did need to, this would match your simple requirements:
(".*?")|([^ ]+)

However, this doesn't include:

*

*Escaped quotes

*Single quotes

*non-ascii quotes (you don't think people will paste smart quotes from word into your file?)

*combinations of the above

And that's just off the top of my head.

A: The link in Jim Mischel's comment points out that the Win32 API provides a function for this. I'd recommend using that for consistency. Here's a sample (from PInvoke).
static string[] SplitArgs(string unsplitArgumentLine)
{
    int numberOfArgs;
    IntPtr ptrToSplitArgs;
    string[] splitArgs;

    ptrToSplitArgs = CommandLineToArgvW(unsplitArgumentLine, out numberOfArgs);
    if (ptrToSplitArgs == IntPtr.Zero)
        throw new ArgumentException("Unable to split argument.",
          new Win32Exception());
    try
    {
        splitArgs = new string[numberOfArgs];
        for (int i = 0; i < numberOfArgs; i++)
            splitArgs[i] = Marshal.PtrToStringUni(
                Marshal.ReadIntPtr(ptrToSplitArgs, i * IntPtr.Size));
        return splitArgs;
    }
    finally
    {
        LocalFree(ptrToSplitArgs);
    }
}

[DllImport("shell32.dll", SetLastError = true)]
static extern IntPtr CommandLineToArgvW(
    [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
    out int pNumArgs);

[DllImport("kernel32.dll")]
static extern IntPtr LocalFree(IntPtr hMem);

If you want a quick-and-dirty, inflexible, fragile regex solution you can do something like this:
var rex = new Regex(@"("".*?""|[^ ""]+)+");
string test = "CALL \"C:\\My File Name With Space\" /P1 P1Value /P1 P2Value";
var array = rex.Matches(test).OfType<Match>().Select(m => m.Groups[0]).ToArray();

A: @chad Henderson you forgot to include the single quotes, and this also have the problem of capturing anything that comes before a set of quotes.
here is the correction including the single quotes, but also shows the problem with the extra capture before a quote.
http://regexhero.net/tester/?id=81cebbb2-5548-4973-be19-b508f14c3348


text:
Q: finding largest number Qt How to find a largest number from a File in Qt. Could anybody explain to me in detail, as I am new to Qt.
I've already tried but i am not able to understand. Here I took a file from the folder which contains 2000 ints (numbers). I converted string to int and now I want to find the largest number among all the int's in file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QFile>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
QString ReadAll;
int i;
//int iMax = array[0];

void MainWindow::on_pushButton_pressed()
{

    QFile file("/home/path");
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"error";
    }
    QTextStream in(&file);

    while(!in.atEnd())
    {
        qDebug()<<ReadAll;
      ReadAll=in.readAll();
        qDebug()<<ReadAll;
    }
    file.close();
        qDebug()<<ReadAll;

        QStringList List=ReadAll.split(QRegExp("\n"),QString::SkipEmptyParts);
        int StrListInt[List.count()];

        i=0;

        foreach(QString Str, List)
        {
            qDebug()<<Str;

            StrListInt[i]=Str.toInt();
            qDebug()<<"spliting"<<QString::number(StrListInt[i]);
        }

    ui->textEdit->setText(ReadAll);

}

A: Your code is wrong so I would decide to completely rewrite it.
I think this would be the correct approach:

*

*read line by line.

*convert the line to Int.

*use qMax() for updating the current maximum if needed.
QFile file(QStandardPaths::locate(QStandardPaths::HomeLocation));
if (!file.open(QIODevice::ReadOnly))
    qDebug() << file.errorString();

QTextStream in(&file);

QString string;
int currentMaximum = INT_MIN;

while (!in.atEnd()) {
    string = in.readLine();
    currentMaximum = qMax(currentMaximum, string.toInt());
}

Disclaimer: I would not personally use Qt for such a simple task, just the standard library in C++.


text:
Q: Cannot connect to tomcat externally
I install the tomcat server on my openSuse port 8080, but I can connect to http://127.0.0.1:8080 only in my local machine.

A: do you have a linux firewall like iptables configured?
If it's iptables you can fix this with this statement
  iptables -I INPUT -p tcp --dport 8080 -j ACCEPT

(You change your iptables config to accept external tcp connections, please make shure that you know what you are doing if your are editing firewall ports)


text:
Q: How to align this span to the right of the div? I have the following HTML:

    Cumulative performance
    20/02/2011

with this CSS:
.title
{
    display: block;
    border-top: 4px solid #a7a59b;
    background-color: #f6e9d9;
    height: 22px;
    line-height: 22px;
    padding: 4px 6px;
    font-size: 14px;
    color: #000;
    margin-bottom: 13px;
    clear:both;
}

If you check this jsFiddle:
http://jsfiddle.net/8JwhZ/
you can see that the Name & Date are stuck together. Is there a way that I can get the date to align to the right? I've tried float: right; on the second  but it screws up the style, and pushes the date outside of the enclosing div

A: Working with floats is bit messy:

This as many other 'trivial' layout tricks  can be done with flexbox.
   div.container {
     display: flex;
     justify-content: space-between;
   }

In 2017 I think this is preferred solution (over float) if you don't have to support legacy browsers: https://caniuse.com/#feat=flexbox
Check fiddle how different float usages compares to flexbox ("may include some competing answers"): https://jsfiddle.net/b244s19k/25/. If you still need to stick with float I recommended third version of course.

A: You can do this without modifying the html.
http://jsfiddle.net/8JwhZ/1085/

Cumulative performance
20/02/2011

.title span:nth-of-type(1) { float:right }
.title span:nth-of-type(2) { float:left }

A: If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/

  Cumulative performance
  20/02/2011

.title .date { float:right }
.title .name { float:left }

A: An alternative solution to floats is to use absolute positioning:
.title {
  position: relative;
}

.title span:last-child {
  position: absolute;
  right: 6px;   /* must be equal to parent's right padding */
}

See also the fiddle.

A: The solution using flexbox without justify-content: space-between.

  Cumulative performance
  20/02/2011

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first , it takes up the entire remaining space and moves the second  to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/
Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first .

A: ul { /** works with ol too **/
    list-style: none; /** removes bullet points/numbering **/
    padding-left: 0px; /** removes actual indentation **/
}


text:
Q: Algolia vue-instantsearch : disjunction between two distincts facets Using algolia vue-instantsearch, i'm encountering a special case and i'm having an hard time finding a solution.
Refinement behaviors is that you get the results that matches all your refinement filters.
If i filter on a brand and a price, i'll get the results that matches both the brand and the price.
I need to add some specific filters that work differently. I would like to be able to say "returns me the results that matches either refinementA, or refinementB, or refinementC."
The reason is that those refinements are checking fields that are not present on all the products.
If i check a value for refinementA, i want to keep all the results that has no value for field corresponding to refinementA, but remove those that has a value for refinementA that does not match with the one i filtered one.
Im thinking about handling myself some inputs instead of ias-components, and modifying by hand each query that is send to algolia by checking the value of my own inputs when searchFunction is triggered (https://www.algolia.com/doc/api-reference/widgets/instantsearch/js/#widget-param-searchfunction).
I did not found yet how i can trigger a search from an non-vue-instantsearch input event, and i'm not sure how the above solution could affect the internal working of vue-instantsearch.
I'm looking for feedbacks about a more standard way of doing this, or for any advices !

A: I got the answer by exchanging with a vue-instantsearch maintainer.
vue-instantsearch does not provide any option to do it.
A workaround is to overwrite algoliasearch search method, that is used under the hood by vue-instant-search.
const client = algoliasearch('', '');
const originalSearch = client.search;
client.search = function search(queries) { ... }

More informations in this github issue : https://github.com/algolia/vue-instantsearch/issues/1102


text:
Q: Installing Leopard from DVD: Apple logo? I need to install Leopard OSX on my mac.
When the mac starts, I hold the alt button and I load the Leopard Installation DVD. Afterwords I can only see the Apple logo on the screen and everything seems stuck (waited for 8 minutes so far).
How much am I supposed to wait to see the first istructions when loading the Installation DVD at boot time ?
thanks

A: You most probably won't be able to install this OS X version on your iMac:

*

*10.6.4 (which is Snow Leopard, not Leopard) was released June 15th, 2010 (Wikipedia)

*iMac 12,2 was released mid 2011 (Apple Support Document)

As a general rule you can't install older OS X discs on newer hardware (missing drivers etc.).


text:
Q: TrustNotGrantedException when updating ClickOnce app installed through CD We have a ClickOnce app deployed using a CD installer and set up the Update URL (the install URL is empty)
On Windows 7 and Windows 8, the auto-update feature (we use the programmatic approach via System.Deployment) ends up with a TrustNotGrantedException and "User has refused to grant required permissions to the application"
The symptoms are very similar to Clickonce full trust app update failing with TrustNotGrantedException on Windows 8 but the provided solution does not make any difference.
When using the CD installer, the ClickOnce prompt warning shield is green as local install, is it then not possible to download updates from the web?

A: We had the same problem and ended up using the InPlaceHostingManager Class. It's made for installing or updating a ClickOnce deployment. GetManifestAsync() fires the GetManifestCompleted event, which gives you the version number. Then you can call DownloadApplicationAsync() and handle the DownloadApplicationCompleted event. So far this works and no TrustNotGrantedException is thrown.

A: We tried workarounds as well, but none resolved all of our issues. If you install your Authenticode certificate (public key only) in the "trusted publishers" certificate store you can then call ApplicationDeployment.CheckForDetailedUpdate without the TrustNotGrantedException.
This was only a problem for us when starting with CD-install, although we've seen similar issues when changing to a new UpdateLocation. Assuming you haven't changed the default trust prompt behavior, your initial CD-install should have prompted the user (at install time) to elevate the application permissions to FullTrust.

If the application is configured to check for updates from a Web or network location and a newer version is available, the original installation can receive permissions for the Internet or Intranet zone instead of full-trust permissions. To prevent users from being prompted, a System Administrator can specify a ClickOnce deployment policy that defines a specific application publisher as a trusted source.
(REF: VS2015 Securing ClickOnce Applications)

I never found adequate documentation in the Trusted Application Development Overview, but I believe that when you try to go from the MyComputer zone (CD-install) to the Internet zone, the trust manager thinks that the user must be prompted to re-confirm the FullTrust permission elevation. It seems the Trust Prompting only happens when launching the .application file and so you've missed you chance by the time your app is running.
FWIW - our other issues with the workarounds were related to Taskbar pinning on Win10 after switching from a CD-install to a Web-Install. Our behavior was similar to this but none of those solutions helped.


text:
Q: Why does the second call to RasGetEntryProperties() return an Overlapped I/O operation is in progress? There is such code:
#include <ras.h>
#include <raserror.h>
#include <stdio.h>
#include <windows.h>

int main(int argc, char** argv) {
    DWORD dwEntryInfoSize = 0;
    DWORD dwDeviceInfoSize = 0;
    DWORD dwRet = 0;
    LPRASENTRY lpRasEntry = NULL;
    LPBYTE lpDeviceInfo = NULL;

Create RAS connection. Get buffer sizing information for a default phonebook entry.
    if ((dwRet = RasGetEntryProperties(NULL, "", NULL, &dwEntryInfoSize, NULL, &dwDeviceInfoSize)) != ERROR_SUCCESS) {
        if (dwRet != ERROR_BUFFER_TOO_SMALL) {
            printf("RasGetEntryProperties error: %s\n", GetLastError());

            return EXIT_FAILURE;
        }
    }

    if (dwEntryInfoSize == 0) {
        printf("Entry info size error: %s\n", GetLastError());

        return EXIT_FAILURE;
    }

    lpRasEntry = (LPRASENTRY) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntryInfoSize);

    if (lpRasEntry == NULL) {
        printf("HeapAlloc RasEntry error: %s\n", GetLastError());

        return EXIT_FAILURE;
    }

    if (dwDeviceInfoSize) {
        lpDeviceInfo = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwDeviceInfoSize);
    }

    lpRasEntry->dwSize = sizeof(RASENTRY);

Here there is an error: Overlapped I/O operation is in progress. The error occurs in Windows XP and in Windows 10 everything works fine. I need this code to work in XP.
    if ((dwRet = RasGetEntryProperties(NULL, "", lpRasEntry, &dwEntryInfoSize, lpDeviceInfo, &dwDeviceInfoSize)) != ERROR_SUCCESS) {
        printf("RasGetEntryProperties error: %s\n", GetLastError());

        return EXIT_FAILURE;
    }

    // Validate new phonebook name "TestEntry"
    if ((dwRet = RasValidateEntryName(NULL, "TestEntry")) != ERROR_SUCCESS) {
        printf("RasValidateEntryName error: %s\n", GetLastError());

        return EXIT_FAILURE;
    }

    // Install a new phonebook entry, "TestEntry", using default properties
    if ((dwRet = RasSetEntryProperties(NULL, "TestEntry", lpRasEntry, dwEntryInfoSize, lpDeviceInfo, dwDeviceInfoSize)) != ERROR_SUCCESS) {
        printf("RasSetEntryProperties error: %s\n", GetLastError());

        return EXIT_FAILURE;
    }

    // Deallocate memory for the connection buffer
    HeapFree(GetProcessHeap(), 0, lpRasEntry);
    lpRasEntry = NULL;

    return EXIT_SUCCESS;
}

This code creates a dial-up connection. And I'm stuck on this bug.
enter image description here

A: The code showed errors...
Error #1: The Ras* functions do not set error codes for GetLastError(). Those GetLastError() does not make sense. They return error codes as DWORD. Read Routing and Remote Access Error Codes in MSDN.
Error #2: Starting with NT in the RasGetEntryProperties() function 5 and 6, the parameters are not used and should be NULL.
Error #3: The most insidious. The fact is that the size of the RASENTRY structure for some Windows operating systems is different. For example, between XP and 10. Therefore, somewhere in the header files, we should specify something like this:
#define WINVER 0x0501
#define _WIN32_WINNT 0x0501

More details can be read in MSDN. Modifying WINVER and _WIN32_WINNT. In this case, we specified the version of Windows XP. That's what I needed. And Overlapped I / O operation is in progress has nothing to do with us in this case. We just output the result of GetLastError() which probably arose somewhere in the depths of Windows when the previous functions were executed.


text:
Q: Java import problems The import statement in Java seems to be acting bizarre, I've checked with Java The Complete Reference and I can't see why something isn't working.
I have two files one in first/mysql/MySQLAccess.java and another in first/mysql/test/Main.java and an import statement in the latter for first.mysql.MySQLAccess isn't working.
package first.mysql.test;

import first.mysql.MySQLAccess;

MySQLAccess.java starts with
package first.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

public class MySQLAccess {

I can't work out why this won't work, it should work perfectly unless I've missed something. I've compiled MySQLAccess.java and it produced MySQLAccess.class
Main.java:1: error: package first.mysql does not exist
import first.mysql.MySQLAccess;
                   ^
Main.java:5: error: cannot find symbol
    MySQLAccess dao = new MySQLAccess();
    ^
symbol:   class MySQLAccess
location: class Main
Main.java:5: error: cannot find symbol
    MySQLAccess dao = new MySQLAccess();
                          ^
symbol:   class MySQLAccess
location: class Main
3 errors

I've compiled with:
john@fekete:~/devel/java/mysqlexample$ javac first/mysql/test/Main.java

Source code:
first/mysql/MySQLAccess.java: http://pastebin.com/7WkewTEf
first/mysql/test/Main.java: http://pastebin.com/aSsn34fX
I have found a clue to the weird behaviour, java does not seem like like MySQLAccess.class...
john@fekete:~/devel/java/mysqlexample$ java first/mysql/MySQLAccess.class
Error: Could not find or load main class first.mysql.MySQLAccess.class

A: Most likely reason - first.mysql.MySQLAccess.java wasn't compiled successfully to begin with, or it was compiled directly under /mysql - negating the package structure. The source may be there, but as far as first.mysql.test.Main.java is concerned, it will only look for first.mysql.MySQLAccess.class.
First, make sure you have this structure:
mysqlexample
  |--first
       |--mysql
          |--test
             |-- Main.java
       MySQLAccess.java

Then issue these commands:
john@fekete:~/devel/java/mysqlexample$ javac first/mysql/MySQLAccess.java

john@fekete:~/devel/java/mysqlexample$ javac first/mysql/test/Main.java


text:
Q: How do I save PDF files within a web browser - using a bookmarklet? I'm building a social bookmarking application for use within large companies.
It has a simple JavaScript bookmarklet which currently works fine - the bookmarklet allowes users to save a bookmark from popular browsers. It works for public web links quite well - and is fairly browser-agnostic. The closest example of such a bookmarklet is this:
http://delicious.com/help/bookmarklets
When I am viewing a PDF in my browser (let's say Chrome/Mac):
http://website.com/file.pdf
This does not work of course - since there is no way to inject HTML markup on top of a PDF being viewed in-browser.
What is the best approach to making links to non-http resources work within a bookmarklet? Do I have to create then inject some kind of invisible iframe and then grab a parent frame and it's URL to be able to save it?

A: I don't know about all browsers, but in Firefox you can inject Javascript and iFrames over PDF files and images. This is because images and PDF files are actually displayed inside special dummy HTML pages generated by Firefox. I think Chrome may be the same.
You can see this for yourself by opening a PDF or image and then opening the Web Console (must use menu, can not use CTRL+SHIFT+K in this case) to get the JS console and then type document.documentElement.outerHTML to see the actual dummy HTML where the PDF or image is embedded.
To detect situations where I can not add an iFrame or other HTML to a page, I might test if document.documentElement is defined, or possibly some other DOM element.
For any browser or file-type combination where this will not work, or if I just wanted to keep things more simple, I'd open a page on my server in a new tab or window and pass the page title and location to that page like http://mysocialsite.tld/add-bookmark?title=file.pdf&location=http://anothersite.tld/file.pdf. That page on my server would let the user complete the bookmarking process.


text:
Q: VUE - Module not found. Can´t Import Component Working with VUE/VUEX.
I want to import the Component "Popup.vue" from the file: "Tienda2.vue". But I am getting this error:
Failed to compile.

./src/layouts/Tienda2.vue?vue&type=script&lang=js (./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/layouts/Tienda2.vue?vue&type=script&lang=js)
Module not found: Error: Can't resolve '@/components/Popup.vuex' in 'D:\Cursos\VUE\0_proyecto\src\layouts'

I'm pretty sure the import path is valid, here is my folder structure:
|----src
     |----components
     |      |---------Popup.vue
     |
     |----layouts
           |---------Tienda2.vue

I have tried with @/components/Popup.vuex  and  ../components/Popup.vuex. Here is my code:
Tienda2.vue
<template>

Tienda2 {{id}}

**<Popup />**

      <div @click="$router.push({name:'TipoArticulo', params: {id:`${tipo.nombre}`}})">{{tipo.nombre}}

  <router-view></router-view>
</template>

```

  [1]: https://i.stack.imgur.com/lJZlE.png
  [2]: https://i.stack.imgur.com/5Hx7H.png

A: It should be '.vue', not 'vuex'.

import Popup from '../components/Popup.vue'


text:
Q: Prove: If L is regular then ContainsABBA(L) is regular ContainsABBA(L) is the set of all strings which are both 1) in L and 2) contain the substring abba.
We can say a language is regular if we are able to come up with a DFA or Regular expression or regular grammar. But I'm unable to figure out how to prove the connection with L and ContainsABBA(L).


text:
Q: Limiting list returned by xpath I am trying to use xpath in WebHarvest and I am able to receive a large list of data, however I only need the first 5 strings returned.
<var-def name="googleProducts">
    <html-to-xml>
        <http url="http://google.com/shopping?q=fila skele-toes&hl=en"/>
    </html-to-xml>
</var-def>
<var-def name="googlePrices">
    <xpath expression="//div[@id='center_col']//div[@class='psliprice']/div[1]/text()">
        <var name="googleProducts"></var>
    </xpath>
</var-def>

I have tried using *[position()<6]
but i get the error the value of attribute "expression" associated with an element type "null" must not contain the '<' character

A: This expression is valid, and should accomplish your goal:
<xpath expression="//div[@id='center_col']//div[@class='psliprice' and position()<=5]/div[1]/text() ">

Fiddle Example


text:
Q: Qt: hide widget with ToolTip flag when window is not visible I'm creating a video player, below is an MRE implementation of the VideoWidget and a widget to display the video controls, called ControlBar:
import os
from PySide6 import QtMultimedia as qtm
from PySide6 import QtMultimediaWidgets as qtmw
from PySide6 import QtWidgets as qtw
from PySide6 import QtCore as qtc
from PySide6 import QtGui as qtg

class VideoWidget(qtmw.QVideoWidget):
    load_finished_signal = qtc.Signal()

    _playback_state_changed_signal = qtc.Signal()

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.setFocusPolicy(qtc.Qt.FocusPolicy.NoFocus)
        self.setMouseTracking(True)
        # In Qt6, a private internal class is used for rendering the video, so
        # add `vw.children()[0].setMouseTracking(True)`
        self.children()[0].setMouseTracking(True)

        self._seeking = False

        self._audio_output = qtm.QAudioOutput(qtm.QMediaDevices.defaultAudioOutput())
        self._media_player = qtm.QMediaPlayer(self)
        self._control_bar = ControlBar(self)
        self._hide_control_bar_timer = qtc.QTimer()

        self._media_player.setVideoOutput(self)
        self._media_player.setAudioOutput(self._audio_output)
        self._media_player.mediaStatusChanged.connect(self._video_loaded)
        self._media_player.durationChanged.connect(
            self._control_bar.update_total_duration
        )
        self._media_player.positionChanged.connect(self._control_bar.update_progress)
        self.videoSink().videoFrameChanged.connect(self._seeked)

        self._control_bar.seek_requested_signal.connect(self._seek)
        self._control_bar.pause_play_requested_signal.connect(self._change_playback_state)
        self._playback_state_changed_signal.connect(self._control_bar.playback_state_changed)
        self._hide_control_bar_timer.setSingleShot(True)
        self._hide_control_bar_timer.setInterval(1000)
        self._hide_control_bar_timer.timeout.connect(self._hide_control_bar)

    def _hide_control_bar(self) -> None:
        if not self._control_bar.underMouse():
            self._control_bar.setVisible(False)
            cursor = self.cursor()
            cursor.setShape(qtc.Qt.CursorShape.BlankCursor)
            self.setCursor(cursor)

    def load(self, location: str) -> None:
        self._media_player.setSource(qtc.QUrl.fromLocalFile(location))

    def _video_loaded(self, location: str) -> None:
        self._control_bar.set_filename(
            os.path.basename(self._media_player.source().toString())
        )
        if self._media_player.source():
            self._media_player.play()
            self.load_finished_signal.emit()

    def close_item(self) -> None:
        self._media_player.stop()
        self._media_player.setSource(qtc.QUrl())

    def _screenshot(self, video_frame: qtm.QVideoFrame):
        image = video_frame.toImage()
        image.save(filename)

    def _update_conrol_bar_position(self) -> None:
        geometry = self.geometry()
        top_left_global = geometry.topLeft()
        self._control_bar.update_geometry_to_width(self.width())
        self._control_bar.move(
            top_left_global.x(),
            top_left_global.y() + geometry.height() - self._control_bar.height(),
        )

    def _change_playback_state(self) -> None:
        if (
            self._media_player.playbackState()
            == qtm.QMediaPlayer.PlaybackState.PlayingState
        ):
            self._media_player.pause()
        elif (
            self._media_player.playbackState()
            == qtm.QMediaPlayer.PlaybackState.PausedState
            or self._media_player.playbackState()
            == qtm.QMediaPlayer.PlaybackState.StoppedState
        ):
            self._media_player.play()

        self._playback_state_changed_signal.emit()

    def mouseMoveEvent(self, event: qtg.QMouseEvent) -> None:
        if not self.cursor().shape() & qtc.Qt.CursorShape.ArrowCursor:
            cursor = self.cursor()
            cursor.setShape(qtc.Qt.CursorShape.ArrowCursor)
            self.setCursor(cursor)
        if (
            not self.width() == self._control_bar.width()
            or not self.geometry().contains(self._control_bar.geometry())
        ):
            self._update_conrol_bar_position()
        if not self._control_bar.isVisible():
            self._control_bar.setVisible(True)
        self._hide_control_bar_timer.start()

    def mousePressEvent(self, event: qtg.QMouseEvent) -> None:
        self._change_playback_state()
        event.accept()
        return

    def mouseDoubleClickEvent(self, event: qtg.QMouseEvent) -> None:
        F_event = qtg.QKeyEvent(
            qtc.QEvent.KeyPress,
            qtc.Qt.Key.Key_F,
            qtc.Qt.KeyboardModifier.NoModifier,
            "F",
        )
        qtc.QCoreApplication.sendEvent(self, F_event)
        super().mouseDoubleClickEvent(event)

    def resizeEvent(self, event: qtg.QResizeEvent) -> None:
        super().resizeEvent(event)
        self._update_conrol_bar_position()

    def contextMenuEvent(self, event: qtg.QContextMenuEvent):
        """"""

    def keyPressEvent(self, event: qtg.QKeyEvent) -> None:
        key = event.key()

        if (
            key == qtc.Qt.Key.Key_Left
            or key == qtc.Qt.Key.Key_Right
            or key == qtc.Qt.Key.Key_Less
            or key == qtc.Qt.Key.Key_Greater
        ):
            factor = (
                1
                if event.modifiers() == qtc.Qt.KeyboardModifier.ShiftModifier
                else 60
                if event.modifiers() == qtc.Qt.KeyboardModifier.ControlModifier
                else 5
            )
            if key == qtc.Qt.Key.Key_Left:
                self._seek(max(self._media_player.position() - (1000 * factor), 0))
            elif key == qtc.Qt.Key.Key_Right:
                self._seek(
                    min(
                        self._media_player.position() + (1000 * factor),
                        self._media_player.duration(),
                    )
                )

        elif key == qtc.Qt.Key.Key_F5:
            self._screenshot(self.videoSink().videoFrame())

        elif key == qtc.Qt.Key.Key_Space:
            self._change_playback_state()

        elif key == qtc.Qt.Key.Key_Down:
            self._media_player.audioOutput().setVolume(
                max(self._media_player.audioOutput().volume() - 0.1, 0)
            )
        elif key == qtc.Qt.Key.Key_Up:
            self._media_player.audioOutput().setVolume(
                min(self._media_player.audioOutput().volume() + 0.1, 1)
            )
        elif key == qtc.Qt.Key.Key_M:
            self._media_player.audioOutput().setMuted(
                not self._media_player.audioOutput().isMuted()
            )

        else:
            super().keyPressEvent(event)
            return None
        event.accept()
        return None
        """
        - next in directory
        - previous in directory
        """

    def _seek(self, position: int) -> None:
        if self._seeking:
            return
        self._seeking = True
        if self._media_player.isSeekable():
            self._media_player.setPosition(position)
        else:
            self._seeked()

    def _seeked(self):
        self._seeking = False

    def wheelEvent(self, event: qtg.QWheelEvent) -> None:
        "volume"

class ControlBar(qtw.QWidget):
    seek_requested_signal = qtc.Signal(int)
    pause_play_requested_signal = qtc.Signal()

    _WRT_HEIGHT = 100
    _MAX_FONT_POINT_F = 20
    _WRT_WIDTH = 1920 / 2
    # Height should be _WRT_HEIGHT if width is _WRT_WIDTH.
    _CONTROL_BAR_WIDTH_TO_HEIGHT_RATIO = _WRT_HEIGHT / _WRT_WIDTH
    _FONT_POINT_F_RATIO = _MAX_FONT_POINT_F / _WRT_HEIGHT

    _WIDGETS_SIZE_RATIOS = {
        "filename": (_WRT_WIDTH / _WRT_WIDTH, 40 / _WRT_HEIGHT),
        "pause_play": (30 / _WRT_WIDTH, 35 / _WRT_HEIGHT),
        "pause": (10 / _WRT_WIDTH, 35 / _WRT_HEIGHT),
        "play": (25 / _WRT_WIDTH, 35 / _WRT_HEIGHT),
        "left_duration": (0 / _WRT_WIDTH, 40 / _WRT_HEIGHT),
        "right_duration": (0 / _WRT_WIDTH, 40 / _WRT_HEIGHT),
        "total_progress_bar": (578 / _WRT_WIDTH, 40 / _WRT_HEIGHT),
        "completed_progress_bar": (0 / _WRT_WIDTH, 40 / _WRT_HEIGHT),
    }
    _PADDINGS_RATIOS = {"v_pad": 5 / _WRT_HEIGHT, "h_pad": 10 / _WRT_WIDTH}

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.setWindowFlag(qtc.Qt.WindowType.ToolTip)

        self._total_duration_ms = 0
        self._completed_duration_ms = 0
        self._widget_shapes = {
            "filename_rect": qtc.QRect(),
            "pause_play_button_rect": qtc.QRect(),
            "pause_path": qtg.QPainterPath(),
            "play_triangle": qtg.QPolygon(),
            "left_duration_rect": qtc.QRect(),
            "progress_bar_rect": qtc.QRect(),
            "right_duration_rect": qtc.QRect(),
        }
        self._show_milliseconds = False
        self._filename = ""
        self._paused = False

    def playback_state_changed(self) -> None:
        self._paused = not self._paused

    def paintEvent(self, event: qtg.QPaintEvent) -> None:
        painter = qtg.QPainter(self)
        painter.setRenderHint(qtg.QPainter.RenderHint.Antialiasing)

        painter.fillRect(0, 0, self.width(), self.height(), qtc.Qt.GlobalColor.black)

        pen = qtg.QPen()
        pen.setColor(qtc.Qt.GlobalColor.white)
        painter.setPen(pen)
        painter.setFont(self._get_font())

        painter.drawText(
            self._widget_shapes["filename_rect"],
            qtc.Qt.AlignmentFlag.AlignLeft,
            self._filename,
        )

        if self._paused:
            path = qtg.QPainterPath()
            path.addPolygon(self._widget_shapes["play_triangle"])
            painter.fillPath(path, qtc.Qt.GlobalColor.white)
        else:
            painter.fillPath(self._widget_shapes["pause_path"], qtc.Qt.GlobalColor.white)

        painter.drawText(
            self._widget_shapes["left_duration_rect"],
            qtc.Qt.AlignmentFlag.AlignCenter,
            _format_milliseconds(self._completed_duration_ms, self._show_milliseconds),
        )

        painter.fillRect(
            self._widget_shapes["progress_bar_rect"], qtc.Qt.GlobalColor.gray
        )
        painter.fillRect(
            self._get_completed_progress_bar_rect(), qtc.Qt.GlobalColor.white
        )
        painter.drawText(
            self._widget_shapes["right_duration_rect"],
            qtc.Qt.AlignmentFlag.AlignCenter,
            _format_milliseconds(self._total_duration_ms, self._show_milliseconds),
        )

    def set_filename(self, filename: str) -> None:
        self._filename = filename

    def update_total_duration(self, duration: int) -> None:
        self._total_duration_ms = duration
        self.update()

    def update_progress(self, progress: int) -> None:
        self._completed_duration_ms = progress
        self.update()

    def update_geometry_to_width(self, width: int) -> None:
        new_control_bar_height = int(self._CONTROL_BAR_WIDTH_TO_HEIGHT_RATIO * width)
        self.setFixedSize(width, min(new_control_bar_height, self._WRT_HEIGHT))
        self._update_widgets_geometry()

    def _update_widgets_geometry(self) -> None:
        total_height = 0
        row_1_total_width = 0
        row_2_total_width = 0

        total_height += self.height() * self._PADDINGS_RATIOS["v_pad"]
        row_1_total_width += self.width() * self._PADDINGS_RATIOS["h_pad"]
        row_2_total_width += self.width() * self._PADDINGS_RATIOS["h_pad"]

        font_metric = qtg.QFontMetrics(self._get_font())
        horizontal_advance = font_metric.horizontalAdvance("A")

        self._widget_shapes["filename_rect"].setX(row_1_total_width)
        self._widget_shapes["filename_rect"].setY(total_height)
        self._widget_shapes["filename_rect"].setWidth(
            horizontal_advance * len(self._filename)
        )
        self._widget_shapes["filename_rect"].setHeight(
            self.height() * self._WIDGETS_SIZE_RATIOS["filename"][1]
        )
        total_height += self._widget_shapes["filename_rect"].height()
        row_1_total_width += self._widget_shapes["filename_rect"].width()

        total_height += self.height() * self._PADDINGS_RATIOS["v_pad"]
        row_1_total_width += self.width() * self._PADDINGS_RATIOS["h_pad"]

        self._widget_shapes["pause_play_button_rect"].setX(row_2_total_width)
        self._widget_shapes["pause_play_button_rect"].setY(total_height)
        self._widget_shapes["pause_play_button_rect"].setWidth(
            min(30, self.width() * self._WIDGETS_SIZE_RATIOS["pause_play"][0])
        )
        self._widget_shapes["pause_play_button_rect"].setHeight(
            self.height() * self._WIDGETS_SIZE_RATIOS["pause_play"][1]
        )

        self._widget_shapes["pause_path"] = qtg.QPainterPath()
        pause_1 = qtc.QRect(
            self._widget_shapes["pause_play_button_rect"].x(),
            self._widget_shapes["pause_play_button_rect"].y(),
            min(10, self.width() * self._WIDGETS_SIZE_RATIOS["pause"][0]),
            self.height() * self._WIDGETS_SIZE_RATIOS["pause"][1],
        )
        self._widget_shapes["pause_path"].addRect(pause_1)

        pause_2 = qtc.QRect(
            self._widget_shapes["pause_play_button_rect"].topRight().x(),
            self._widget_shapes["pause_play_button_rect"].y(),
            -min(10, self.width() * self._WIDGETS_SIZE_RATIOS["pause"][0]),
            self.height() * self._WIDGETS_SIZE_RATIOS["pause"][1],
        )
        self._widget_shapes["pause_path"].addRect(pause_2)

        self._widget_shapes["play_triangle"] = qtg.QPolygon()
        right = self._widget_shapes["pause_play_button_rect"].center()
        right.setX(self._widget_shapes["pause_play_button_rect"].right())
        self._widget_shapes["play_triangle"].append(
            [
                self._widget_shapes["pause_play_button_rect"].topLeft(),
                self._widget_shapes["pause_play_button_rect"].bottomLeft(),
                right,
            ]
        )
        row_2_total_width += self._widget_shapes["pause_play_button_rect"].width()

        row_2_total_width += self.width() * self._PADDINGS_RATIOS["h_pad"]

        self._widget_shapes["left_duration_rect"].setX(row_2_total_width)
        self._widget_shapes["left_duration_rect"].setY(total_height)
        self._widget_shapes["left_duration_rect"].setWidth(
            horizontal_advance
            * len(
                _format_milliseconds(
                    self._completed_duration_ms, self._show_milliseconds
                )
            )
        )
        self._widget_shapes["left_duration_rect"].setHeight(
            self.height() * self._WIDGETS_SIZE_RATIOS["left_duration"][1]
        )
        row_2_total_width += self._widget_shapes["left_duration_rect"].width()

        row_2_total_width += self.width() * self._PADDINGS_RATIOS["h_pad"]

        self._widget_shapes["progress_bar_rect"].setX(row_2_total_width)
        self._widget_shapes["progress_bar_rect"].setY(total_height)
        self._widget_shapes["progress_bar_rect"].setWidth(
            self.width() * self._WIDGETS_SIZE_RATIOS["total_progress_bar"][0]
        )
        self._widget_shapes["progress_bar_rect"].setHeight(
            self.height() * self._WIDGETS_SIZE_RATIOS["total_progress_bar"][1]
        )
        row_2_total_width += self._widget_shapes["progress_bar_rect"].width()
        row_2_total_width += self.width() * self._PADDINGS_RATIOS["h_pad"]

        # To adjust the size of the progress bar according to the remaining width
        # left after adding all remaining widget's widths.
        theoritical_width = row_2_total_width
        theoritical_width += horizontal_advance * len(
            _format_milliseconds(self._total_duration_ms, self._show_milliseconds)
        )
        theoritical_width += self.width() * self._PADDINGS_RATIOS["h_pad"]

        remaining_width = self.width() - theoritical_width

        self._widget_shapes["progress_bar_rect"].setWidth(
            self._widget_shapes["progress_bar_rect"].width() + remaining_width
        )
        row_2_total_width += remaining_width

        self._widget_shapes["right_duration_rect"].setX(row_2_total_width)
        self._widget_shapes["right_duration_rect"].setY(total_height)
        self._widget_shapes["right_duration_rect"].setWidth(
            horizontal_advance
            * len(
                _format_milliseconds(self._total_duration_ms, self._show_milliseconds)
            )
        )
        self._widget_shapes["right_duration_rect"].setHeight(
            self.height() * self._WIDGETS_SIZE_RATIOS["right_duration"][1]
        )
        row_2_total_width += self._widget_shapes["right_duration_rect"].width()
        row_2_total_width += self.width() * self._PADDINGS_RATIOS["h_pad"]

    def _get_font(self) -> qtg.QFont:
        font = qtg.QFont()
        font.setPointSizeF(self.height() * self._FONT_POINT_F_RATIO)
        return font

    def _get_completed_progress_bar_rect(self) -> qtc.QRect:
        completed_width = int(
            (self._completed_duration_ms / (self._total_duration_ms or 1))
            * self._widget_shapes["progress_bar_rect"].width()
        )
        completed_rect = qtc.QRect(self._widget_shapes["progress_bar_rect"])
        completed_rect.setWidth(completed_width)
        return completed_rect

    def _get_time_from_mouse_press(self, point: qtc.QPoint) -> None:
        return int(
            (point.x() / self._widget_shapes["progress_bar_rect"].width())
            * self._total_duration_ms
        )

    def mousePressEvent(self, event: qtg.QMouseEvent) -> None:
        point = event.pos()
        if self._widget_shapes["left_duration_rect"].contains(point):
            self._show_milliseconds = not self._show_milliseconds
            self._update_widgets_geometry()

        elif self._widget_shapes["progress_bar_rect"].contains(point):
            self.seek_requested_signal.emit(
                self._get_time_from_mouse_press(
                    point - self._widget_shapes["progress_bar_rect"].topLeft()
                )
            )

        elif self._widget_shapes["pause_play_button_rect"].contains(point):
            self.pause_play_requested_signal.emit()

        self.update()
        event.accept()
        return

    def mouseMoveEvent(self, event: qtg.QMouseEvent) -> None:
        if self._widget_shapes["progress_bar_rect"].contains(event.pos()):
            self.seek_requested_signal.emit(
                self._get_time_from_mouse_press(
                    event.pos() - self._widget_shapes["progress_bar_rect"].topLeft()
                )
            )
        event.accept()
        return

def _format_milliseconds(milliseconds: int, show_milliseconds: bool = False) -> str:
    seconds, milliseconds = divmod(milliseconds, 1000)
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return f"{hours:02}:{minutes:02}:{seconds:02}" + (
        f".{milliseconds:03}" if show_milliseconds else ""
    )

app = qtw.QApplication()
vw = VideoWidget()
vw.show()
vw.load("video_file")
app.exec()

While this works as expected for the most part, if I alt-tab into another window (effectively hiding the program) with the ControlBar displayed, the bar is visible on top of the other window as well. I'm guessing such is the nature of the Qt.ToolTip window flag. How do I have it "show" or "hide" with the main program?
Also, the _update_widgets_geometry() function's implementation is rather tedious, is there a better way to do this? "This" being the way I layout (set the QRects for) the shapes in the ControlBar.
EDIT:
The code should work "out of the box", just pass a valid video file path to the vw.load() at the end of the code. A screenshot.