Programs & Examples On #Destructor

A special method in object-oriented programming which is invoked when an object is destroyed

How to force deletion of a python object?

Perhaps you are looking for a context manager?

>>> class Foo(object):
...   def __init__(self):
...     self.bar = None
...   def __enter__(self):
...     if self.bar != 'open':
...       print 'opening the bar'
...       self.bar = 'open'
...   def __exit__(self, type_, value, traceback):
...     if self.bar != 'closed':
...       print 'closing the bar', type_, value, traceback
...       self.bar = 'close'
... 
>>> 
>>> with Foo() as f:
...     # oh no something crashes the program
...     sys.exit(0)
... 
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>

How to destroy an object?

A handy post explaining several mis-understandings about this:

Don't Call The Destructor explicitly

This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.

When is a C++ destructor called?

To give a detailed answer to question 3: yes, there are (rare) occasions when you might call the destructor explicitly, in particular as the counterpart to a placement new, as dasblinkenlight observes.

To give a concrete example of this:

#include <iostream>
#include <new>

struct Foo
{
    Foo(int i_) : i(i_) {}
    int i;
};

int main()
{
    // Allocate a chunk of memory large enough to hold 5 Foo objects.
    int n = 5;
    char *chunk = static_cast<char*>(::operator new(sizeof(Foo) * n));

    // Use placement new to construct Foo instances at the right places in the chunk.
    for(int i=0; i<n; ++i)
    {
        new (chunk + i*sizeof(Foo)) Foo(i);
    }

    // Output the contents of each Foo instance and use an explicit destructor call to destroy it.
    for(int i=0; i<n; ++i)
    {
        Foo *foo = reinterpret_cast<Foo*>(chunk + i*sizeof(Foo));
        std::cout << foo->i << '\n';
        foo->~Foo();
    }

    // Deallocate the original chunk of memory.
    ::operator delete(chunk);

    return 0;
}

The purpose of this kind of thing is to decouple memory allocation from object construction.

Dynamically allocating an array of objects

I'd recommend using std::vector: something like

typedef std::vector<int> A;
typedef std::vector<A> AS;

There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.

When should I create a destructor?

It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.

It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.

In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.

A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.

throwing exceptions out of a destructor

Your destructor might be executing inside a chain of other destructors. Throwing an exception that is not caught by your immediate caller can leave multiple objects in an inconsistent state, thus causing even more problems then ignoring the error in the cleanup operation.

How do I correctly clean up a Python object?

atexit.register is the standard way as has already been mentioned in ostrakach's answer.

However, it must be noted that the order in which objects might get deleted cannot be relied upon as shown in example below.

import atexit

class A(object):

    def __init__(self, val):
        self.val = val
        atexit.register(self.hello)

    def hello(self):
        print(self.val)


def hello2():
    a = A(10)

hello2()    
a = A(20)

Here, order seems legitimate in terms of reverse of the order in which objects were created as program gives output as :

20
10

However when, in a larger program, python's garbage collection kicks in object which is out of it's lifetime would get destructed first.

Is calling destructor manually always a sign of bad design?

No, you shouldn't call it explicitly because it would be called twice. Once for the manual call and another time when the scope in which the object is declared ends.

Eg.

{
  Class c;
  c.~Class();
}

If you really need to perform the same operations you should have a separate method.

There is a specific situation in which you may want to call a destructor on a dynamically allocated object with a placement new but it doesn't sound something you will ever need.

Do I need to explicitly call the base virtual destructor?

No, you never call the base class destructor, it is always called automatically like others have pointed out but here is proof of concept with results:

class base {
public:
    base()  { cout << __FUNCTION__ << endl; }
    ~base() { cout << __FUNCTION__ << endl; }
};

class derived : public base {
public:
    derived() { cout << __FUNCTION__ << endl; }
    ~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor
};


int main()
{
    cout << "case 1, declared as local variable on stack" << endl << endl;
    {
        derived d1;
    }

    cout << endl << endl;

    cout << "case 2, created using new, assigned to derive class" << endl << endl;
    derived * d2 = new derived;
    delete d2;

    cout << endl << endl;

    cout << "case 3, created with new, assigned to base class" << endl << endl;
    base * d3 = new derived;
    delete d3;

    cout << endl;

    return 0;
}

The output is:

case 1, declared as local variable on stack

base::base
derived::derived
derived::~derived
base::~base


case 2, created using new, assigned to derive class

base::base
derived::derived
derived::~derived
base::~base


case 3, created with new, assigned to base class

base::base
derived::derived
base::~base

Press any key to continue . . .

If you set the base class destructor as virtual which one should, then case 3 results would be same as case 1 & 2.

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

Is there a destructor for Java?

I fully agree to other answers, saying not to rely on the execution of finalize.

In addition to try-catch-finally blocks, you may use Runtime#addShutdownHook (introduced in Java 1.3) to perform final cleanups in your program.

That isn't the same as destructors are, but one may implement a shutdown hook having listener objects registered on which cleanup methods (close persistent database connections, remove file locks, and so on) can be invoked - things that would normally be done in destructors. Again - this is not a replacement for destructors but in some cases, you can approach the wanted functionality with this.

The advantage of this is having deconstruction behavior loosely coupled from the rest of your program.

Does delete on a pointer to a subclass call the base class destructor?

I was wondering why my class' destructor was not called. The reason was that I had forgot to include definition of that class (#include "class.h"). I only had a declaration like "class A;" and the compiler was happy with it and let me call "delete".

How do I check if a string is a number (float)?

I was working on a problem that led me to this thread, namely how to convert a collection of data to strings and numbers in the most intuitive way. I realized after reading the original code that what I needed was different in two ways:

1 - I wanted an integer result if the string represented an integer

2 - I wanted a number or a string result to stick into a data structure

so I adapted the original code to produce this derivative:

def string_or_number(s):
    try:
        z = int(s)
        return z
    except ValueError:
        try:
            z = float(s)
            return z
        except ValueError:
            return s

ImportError: No module named pip

I know this thread is old, but I just solved the problem for myself on OS X differently than described here.

Basically I reinstalled Python 2.7 through brew, and it comes with pip.

Install Xcode if not already:

xcode-select –install

Install Brew as described here:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then install Python through Brew:

brew install python

And you're done. In my case I just needed to install pyserial.

pip install pyserial

Where can I find error log files?

This is a preferable answer in most use cases, because it allows you to decouple execution of the software from direct knowledge of the server platform, which keeps your code much more portable. If you are doing a lot of cron/cgi, this may not help directly, but it can be set into a config at web runtime that the cron/cgi scripts pull from to keep the log location consistent in that case.


You can get the current log file assigned natively to php on any platform at runtime by using:

ini_get('error_log');

This returns the value distributed directly to the php binary by the webserver, which is what you want in 90% of use cases (with the glaring exception being cgi). Cgi will often log to this same location as the http webserver client, but not always.

You will also want to check that it is writeable before committing anything to it to avoid errors. The conf file that defines it's location (typically either apache.conf globally or vhosts.conf on a per-domain basis), but the conf does not ensure that file permissions allow write access at runtime.

How to split a string with any whitespace chars as delimiters

String string = "Ram is going to school";
String[] arrayOfString = string.split("\\s+");

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

Only variable references should be returned by reference - Codeigniter

this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

set PATH=c:\Program Files\Java\jdk1.6.0_45\bin;%PATH%

this will work if you are working on command prompt

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

INSERT INTO KeyedTable(KeyField, Otherfield)
SELECT n.* FROM 
    (SELECT 'PossibleDupeLiteral' AS KeyField, 'OtherfieldValue' AS Otherfield
     UNION ALL
     SELECT 'PossibleDupeLiteral', 'OtherfieldValue2'
    )
LEFT JOIN KeyedTable k
    ON k.KeyField=n.KeyField
WHERE k.KeyField IS NULL

This tells the Server to look for the same data (hopefully the same speedy way it does to check for duplicate keys) and insert nothing if it finds it.

I like the IGNORE_DUP_KEY solution too, but then anyone who relies on errors to catch problems will be mystified when the server silently ignores their dupe-key errors.

The reason I choose this over Philip Kelley's solution is that you can provide several rows of data and only have the missing ones actually get in:

Counting repeated elements in an integer array

public class DuplicationNoInArray {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) throws Exception {
        int[] arr = { 1, 2, 3, 4, 5, 1, 2, 8 };
        int[] result = new int[10];
        int counter = 0, count = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean isDistinct = false;
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    isDistinct = true;
                    break;
                }
            }
            if (!isDistinct) {
                result[counter++] = arr[i];
            }
        }
        for (int i = 0; i < counter; i++) {
            count = 0;
            for (int j = 0; j < arr.length; j++) {
                if (result[i] == arr[j]) {
                    count++;
                }

            }
            System.out.println(result[i] + " = " + count);

        }
    }
}

What is /dev/null 2>&1?

>> /dev/null redirects standard output (stdout) to /dev/null, which discards it.

(The >> seems sort of superfluous, since >> means append while > means truncate and write, and either appending to or writing to /dev/null has the same net effect. I usually just use > for that reason.)

2>&1 redirects standard error (2) to standard output (1), which then discards it as well since standard output has already been redirected.

Java 8 forEach with index

It works with params if you capture an array with one element, that holds the current index.

int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));

The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.

If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:

int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));

Google maps Places API V3 autocomplete - select first option on enter

It seems there is a much better and clean solution: To use google.maps.places.SearchBox instead of google.maps.places.Autocomplete. A code is almost the same, just getting the first from multiple places. On pressing the Enter the the correct list is returned - so it runs out of the box and there is no need for hacks.

See the example HTML page:

http://rawgithub.com/klokan/8408394/raw/5ab795fb36c67ad73c215269f61c7648633ae53e/places-enter-first-item.html

The relevant code snippet is:

var searchBox = new google.maps.places.SearchBox(document.getElementById('searchinput'));

google.maps.event.addListener(searchBox, 'places_changed', function() {
  var place = searchBox.getPlaces()[0];

  if (!place.geometry) return;

  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
  } else {
    map.setCenter(place.geometry.location);
    map.setZoom(16);
  }
});

The complete source code of the example is at: https://gist.github.com/klokan/8408394

How do SO_REUSEADDR and SO_REUSEPORT differ?

Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.

There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:

{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}

Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.

The protocol of a socket is set when a socket is created with the socket() function. The source address and port are set with the bind() function. The destination address and port are set with the connect() function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.

If you explicitly bind a socket, it is possible to bind it to port 0, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0 in case of IPv4 and :: in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.

By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA to ipA:portA and socketB to ipB:portB is always possible if ipA != ipB holds true, even when portA == portB. E.g. socketA belongs to a FTP server program and is bound to 192.168.0.1:21 and socketB belongs to another FTP server program and is bound to 10.0.0.1:21, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21, regardless which specific IP address it tries to bind to, as 0.0.0.0 conflicts with all existing local IP addresses.

Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.

BSD

SO_REUSEADDR

If SO_REUSEADDR is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.

Without SO_REUSEADDR, binding socketA to 0.0.0.0:21 and then binding socketB to 192.168.0.1:21 will fail (with error EADDRINUSE), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1, too. With SO_REUSEADDR it will succeed, since 0.0.0.0 and 192.168.0.1 are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA and socketB are bound; without SO_REUSEADDR it will always fail, with SO_REUSEADDR it will always succeed.

To give you a better overview, let's make a table here and list all possible combinations:

SO_REUSEADDR       socketA        socketB       Result
---------------------------------------------------------------------
  ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
  ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
  ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
   OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
   OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
   ON              0.0.0.0:21   192.168.1.0:21    OK
   ON          192.168.1.0:21       0.0.0.0:21    OK
  ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)

The table above assumes that socketA has already been successfully bound to the address given for socketA, then socketB is created, either gets SO_REUSEADDR set or not, and finally is bound to the address given for socketB. Result is the result of the bind operation for socketB. If the first column says ON/OFF, the value of SO_REUSEADDR is irrelevant to the result.

Okay, SO_REUSEADDR has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.

A socket has a send buffer and if a call to the send() function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send() call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.

At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit() (pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.

The question is, how does the system treat a socket in state TIME_WAIT? If SO_REUSEADDR is not set, a socket in state TIME_WAIT is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.

There is one final thing you should know about SO_REUSEADDR. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR flag of the socket fed into the bind() call, for all other sockets inspected, this flag is not even looked at.

SO_REUSEPORT

SO_REUSEPORT is what most people would expect SO_REUSEADDR to be. Basically, SO_REUSEPORT allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR the code handling SO_REUSEPORT will not only verify that the currently bound socket has SO_REUSEPORT set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT set when it was bound.

SO_REUSEPORT does not imply SO_REUSEADDR. This means if a socket did not have SO_REUSEPORT set when it was bound and another socket has SO_REUSEPORT set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT state requires either SO_REUSEADDR to be set on that socket or SO_REUSEPORT must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT and SO_REUSEADDR, on a socket.

There is not much more to say about SO_REUSEPORT other than that it was added later than SO_REUSEADDR, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.

Connect() Returning EADDRINUSE?

Most people know that bind() may fail with the error EADDRINUSE, however, when you start playing around with address reuse, you may run into the strange situation that connect() fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?

As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.

So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect() will actually fail with the error EADDRINUSE for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.

Multicast Addresses

Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.

The meaning of SO_REUSEADDR changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR behaves exactly as SO_REUSEPORT for unicast addresses. Actually, the code treats SO_REUSEADDR and SO_REUSEPORT identically for multicast addresses, that means you could say that SO_REUSEADDR implies SO_REUSEPORT for all multicast addresses and the other way round.


FreeBSD/OpenBSD/NetBSD

All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.


macOS (MacOS X)

At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.

iOS / watchOS / tvOS

iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.


Linux

Linux < 3.9

Prior to Linux 3.9, only the option SO_REUSEADDR existed. This option behaves generally the same as in BSD with two important exceptions:

  1. As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.

  2. The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT prior to 3.9, the behavior of SO_REUSEADDR was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.

Linux >= 3.9

Linux 3.9 added the option SO_REUSEPORT to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.

Yet, there are still two differences to SO_REUSEPORT on other systems:

  1. To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND/SO_EXCLUSIVEADDRUSE flags.

  2. Additionally the kernel performs some "special magic" for SO_REUSEPORT sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT to get a very inexpensive load balancing.


Android

Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.


Windows

Windows only knows the SO_REUSEADDR option, there is no SO_REUSEPORT. Setting SO_REUSEADDR on a socket in Windows behaves like setting SO_REUSEPORT and SO_REUSEADDR on a socket in BSD, with one exception:

Prior to Windows 2003, a socket with SO_REUSEADDR could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!

Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE. Setting SO_EXCLUSIVEADDRUSE on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR set.

This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind() calls are made by the same user, and the third one when the bind() calls are made by different users.


Solaris

Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR, there is no SO_REUSEPORT. The SO_REUSEADDR behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.

Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND. If this option is set on a socket prior to binding it, setting SO_REUSEADDR on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA is bound to a wildcard address and socketB has SO_REUSEADDR enabled and is bound to a non-wildcard address and the same port as socketA, this bind will normally succeed, unless socketA had SO_EXCLBIND enabled, in which case it will fail regardless the SO_REUSEADDR flag of socketB.


Other Systems

In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.

All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h and stdbool.h; e.g. gcc supported both long before offering full C99 support).

All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".

It tests all possible combinations you can think of:

  • TCP and UDP protocol
  • Normal sockets, listen (server) sockets, multicast sockets
  • SO_REUSEADDR set on socket1, socket2, or both sockets
  • SO_REUSEPORT set on socket1, socket2, or both sockets
  • All address combinations you can make out of 0.0.0.0 (wildcard), 127.0.0.1 (specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3 in all tests)

and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT, in which case this option is simply not tested.

What the program cannot easily test is how SO_REUSEADDR acts on sockets in TIME_WAIT state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.

Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.

Yochai, if you ever read this, please see the note at the end.


For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Error

LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library

Meaning

one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked

while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking

How to resolve

  • Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.

  • Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.

  • [...] trawl through all your libraries and ensure they have the correct link settings

In the latter, as it in mentioned in the original post, two common problems can arise :

  • You have a third party library which is linked differently to your application.

  • You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.

For those cases, ensure you understand the problem and decide among the solutions.


Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry

How to use a ViewBag to create a dropdownlist?

@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })

How to declare variable and use it in the same Oracle SQL script?

In Toad I use this works:

declare 
    num number;
begin 
    ---- use 'select into' works 
    --select 123 into num from dual;

    ---- also can use :=
    num := 123;
    dbms_output.Put_line(num);
end;

Then the value will be print to DBMS Output Window.

Reference to here and here2.

Rmi connection refused with localhost

You need to have a rmiregistry running before attempting to connect (register) a RMI service with it.

The LocateRegistry.createRegistry(2020) method call creates and exports a registry on the specified port number.

See the documentation for LocateRegistry

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

_x000D_
_x000D_
// TypeError: functionOne is not a function_x000D_
functionOne();_x000D_
_x000D_
var functionOne = function() {_x000D_
  console.log("Hello!");_x000D_
};
_x000D_
_x000D_
_x000D_

And, a function declaration:

_x000D_
_x000D_
// Outputs: "Hello!"_x000D_
functionTwo();_x000D_
_x000D_
function functionTwo() {_x000D_
  console.log("Hello!");_x000D_
}
_x000D_
_x000D_
_x000D_

Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.

_x000D_
_x000D_
'use strict';    _x000D_
{ // note this block!_x000D_
  function functionThree() {_x000D_
    console.log("Hello!");_x000D_
  }_x000D_
}_x000D_
functionThree(); // ReferenceError
_x000D_
_x000D_
_x000D_

Running MSBuild fails to read SDKToolsPath

I had the same issue on a brand new Windows 10 machine. My setup:

  • Windows 10
  • Visual Studio 2015 Installed
  • Windows 10 SDK

But I couldn't build .NET 4.0 projects:

Die Aufgabe konnte "AL.exe" mit dem SdkToolsPath-Wert "" oder dem Registrierungsschlüssel "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools-x86

Solution: After trying (and failing) to install the Windows 7 SDK (because thats also includes the .NET 4.0 SDK) I needed to install the Windows 8 SDK and make sure the ".NET Framework 4.5 SDK" is installed.

It's crazy... but worked.

how to get docker-compose to use the latest image from repository

I spent half a day with this problem. The reason was that be sure to check where the volume was recorded.

volumes: - api-data:/src/patterns

But the fact is that in this place was the code that we changed. But when updating the docker, the code did not change.

Therefore, if you are checking someone else's code and for some reason you are not updating, check this.

And so in general this approach works:

docker-compose down

docker-compose build

docker-compose up -d

Overriding fields or properties in subclasses

option 2 is a bad idea. It will result in something called shadowing; Basically you have two different "MyInt" members, one in the mother, and the other in the daughter. The problem with this, is that methods that are implemented in the mother will reference the mother's "MyInt" while methods implemented in the daughter will reference the daughter's "MyInt". this can cause some serious readability issues, and confusion later down the line.

Personally, I think the best option is 3; because it provides a clear centralized value, and can be referenced internally by children without the hassle of defining their own fields -- which is the problem with option 1.

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).

Benefits

  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How to change the background color on a Java panel?

I think what he is trying to say is to use the getContentPane().setBackground(Color.the_Color_you_want_here)

but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)

Eg:

jPanel.setbackground(Color.BLUE)

JSON library for C#

Have a look at the system.web.script.serialization namespace (i think you will need .Net 3.5)

There is an error in XML document (1, 41)

I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.

Recover SVN password from local cache

Your SVN passwords in Ubuntu (12.04) are in:

~/.subversion/auth/svn.simple/

However in newer versions they are encrypted, as earlier someone mentioned. To find gnome-keyring passwords, I suggest You to use 'gkeyring' program.

To install it on Ubuntu – add repository :

sudo add-apt-repository ppa:kampka/ppa
sudo apt-get update

Install it:

sudo apt-get install gkeyring

And run as following:

gkeyring --id 15 --output=name,secret

Try different key ids to find pair matching what you are looking for. Thanks to kampka for the soft.

EditText onClickListener in Android

Default working of EditText: On first click it focuses and on second click it handles onClickListener so you need to disable focus. Then on first click the onClickListener will handle.

To do that you need to add this android:focusableInTouchMode="false" attribute to your EditText. That's it!

Something like this:

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusableInTouchMode="false"
        android:inputType="text" />

how to access downloads folder in android?

If you're using a shell, the filepath to the Download (no "s") folder is

/storage/emulated/0/Download

Alter table to modify default value of column

Your belief about what will happen is not correct. Setting a default value for a column will not affect the existing data in the table.

I create a table with a column col2 that has no default value

SQL> create table foo(
  2    col1 number primary key,
  3    col2 varchar2(10)
  4  );

Table created.

SQL> insert into foo( col1 ) values (1);

1 row created.

SQL> insert into foo( col1 ) values (2);

1 row created.

SQL> insert into foo( col1 ) values (3);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3

If I then alter the table to set a default value, nothing about the existing rows will change

SQL> alter table foo
  2    modify( col2 varchar2(10) default 'foo' );

Table altered.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3

SQL> insert into foo( col1 ) values (4);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo

Even if I subsequently change the default again, there will still be no change to the existing rows

SQL> alter table foo
  2    modify( col2 varchar2(10) default 'bar' );

Table altered.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo

SQL> insert into foo( col1 ) values (5);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo
         5 bar

Discard all and get clean copy of latest revision?

hg up -C

This will remove all the changes and update to the latest head in the current branch.

And you can turn on purge extension to be able to remove all unversioned files too.

JavaFX Panel inside Panel auto resizing

After hours of searching and testing finally got it just after posting the question!

You can use the "AnchorPane.topAnchor, AnchorPane.bottomAnchor, AnchorPane.leftAnchor, AnchorPane.rightAnchor" fxml commands with the value "0.0" to fit/stretch/align the child elements inside a AnchorPane. So, these commands tell to child element to follow its parent while resizing.

My updated code Main.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="anchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
    <!--<StackPane fx:id="stackPane" ></StackPane>--> <!-- replace with the following -->
    <StackPane fx:id="stackPane" AnchorPane.topAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" ></StackPane>
</AnchorPane>

Here is the result:

enter image description here

For api documentation: http://docs.oracle.com/javafx/2/api/javafx/scene/layout/AnchorPane.html

Programmatically select a row in JTable

It is an old post, but I came across this recently

Selecting a specific interval

As @aleroot already mentioned, by using

table.setRowSelectionInterval(index0, index1);

You can specify an interval, which should be selected.

Adding an interval to the existing selection

You can also keep the current selection, and simply add additional rows by using this here

table.getSelectionModel().addSelectionInterval(index0, index1);

This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.

Difference between __getattr__ vs __getattribute__

  • getattribute: Is used to retrieve an attribute from an instance. It captures every attempt to access an instance attribute by using dot notation or getattr() built-in function.
  • getattr: Is executed as the last resource when attribute is not found in an object. You can choose to return a default value or to raise AttributeError.

Going back to the __getattribute__ function; if the default implementation was not overridden; the following checks are done when executing the method:

  • Check if there is a descriptor with the same name (attribute name) defined in any class in the MRO chain (method object resolution)
  • Then looks into the instance’s namespace
  • Then looks into the class namespace
  • Then into each base’s namespace and so on.
  • Finally, if not found, the default implementation calls the fallback getattr() method of the instance and it raises an AttributeError exception as default implementation.

This is the actual implementation of the object.__getattribute__ method:

.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's :attr:~object.dict (if present). As outlined in :ref:descriptors, data descriptors take preference over instance attributes, while non-data descriptors don't. Otherwise, an :exc:AttributeError is raised.

Set up git to pull and push all branches

If you are moving all branches to a new repo from an old one then in your local repo you need to set up tracking of each branch to existing origin branches, before pushing to the new repo, otherwise all your origin branches won’t appear in the new origin. Do this manually by tracking or checking out each branch, or use the one liner:

for remote in `git branch -r | grep -v '\->' | grep -v master`; do git branch --track `echo $remote|sed 's=origin/=='` `echo $remote`; done

This one line command is based on versions of it in other answers on this page, but is arguably better because:

  1. it correctly sets up the branch tracking, unlike some older variants of this command on this page which only supply one parameter to --track and thus each branch ends up tracking master - not good
  2. names the local branches without the prefix “origin/” which I personally don’t want - and is consistent with what happens when you checkout a branch normally.
  3. skips tracking master since that is already happening
  4. doesn’t actually checkout anything thus is fast
  5. avoids stumbling over the -> in the output of git branch -r

Next, if you are switching origins, replace the link to the old origin and point to a new remote. Ensure you create the new remote first, using bitbucket/github GUI, but don’t add any files to it or there will be a merge problem. E.g.

git remote set-url origin [email protected]:YOUR/SOMEREPO.git

Now push. Note the second command is needed to push the tags as well:

git push -u --all origin
git push --tags origin

Class constructor type in typescript?

How can I declare a class type, so that I ensure the object is a constructor of a general class?

A Constructor type could be defined as:

 type AConstructorTypeOf<T> = new (...args:any[]) => T;

 class A { ... }

 function factory(Ctor: AConstructorTypeOf<A>){
   return new Ctor();
 }

const aInstance = factory(A);

gnuplot plotting multiple line graphs

andyras is completely correct. One minor addition, try this (for example)

plot 'ls.dat' using 4:xtic(1)

This will keep your datafile in the correct order, but also preserve your version tic labels on the x-axis.

Instance member cannot be used on type

You just have syntax error when saying = {return self.someValue}. The = isn't needed.

Use :

var numPages: Int {
    get{
        return categoriesPerPage.count
    }

}

if you want get only you can write

var numPages: Int {
     return categoriesPerPage.count
}

with the first way you can also add observers as set willSet & didSet

var numPages: Int {
    get{
        return categoriesPerPage.count
    }
    set(v){
       self.categoriesPerPage = v
    }
}

allowing to use = operator as a setter

myObject.numPages = 5

MySQL remove all whitespaces from the entire column

Just use the following sql, you are done:

SELECT replace(CustomerName,' ', '') FROM Customers;

you can test this sample over here: W3School

port 8080 is already in use and no process using 8080 has been listed

In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.

What does <> mean?

Yes, it's "not equal".

Null check in an enhanced for loop

I have modified the above answer, so you don't need to cast from Object

public static <T> List<T> safeClient( List<T> other ) {
            return other == null ? Collections.EMPTY_LIST : other;
}

and then simply call the List by

for (MyOwnObject ownObject : safeClient(someList)) {
    // do whatever
}

Explaination: MyOwnObject: If List<Integer> then MyOwnObject will be Integer in this case.

How can I check if PostgreSQL is installed or not via Linux script?

Go to bin directory of postgres db such as /opt/postgresql/bin & run below command :

[...bin]# ./psql --version

psql (PostgreSQL) 9.0.4

Here you go . .

Resizing SVG in html?

you can resize it by displaying svg in image tag and size image tag i.e.

<img width="200px" src="lion.svg"></img>

Android new Bottom Navigation bar or BottomNavigationView

As Sanf0rd mentioned, Google launched the BottomNavigationView as part of the Design Support Library version 25.0.0. The limitations he mentioned are mostly true, except that you CAN change the background color of the view and even the text color and icon tint color. It also has an animation when you add more than 4 items (sadly it cannot be enabled or disabled manually).

I wrote a detailed tutorial about it with examples and an accompanying repository, which you can read here: https://blog.autsoft.hu/now-you-can-use-the-bottom-navigation-view-in-the-design-support-library/


The gist of it

You have to add these in your app level build.gradle:

compile 'com.android.support:appcompat-v7:25.0.0'  
compile 'com.android.support:design:25.0.0'

You can include it in your layout like this:

<android.support.design.widget.BottomNavigationView  
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemBackground="@color/darkGrey"
        app:itemIconTint="@color/bottom_navigation_item_background_colors"
        app:itemTextColor="@color/bottom_navigation_item_background_colors"
        app:menu="@menu/menu_bottom_navigation" />

You can specify the items via a menu resource like this:

<?xml version="1.0" encoding="utf-8"?>  
<menu  
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_one"
        android:icon="@android:drawable/ic_dialog_map"
        android:title="One"/>
    <item
        android:id="@+id/action_two"
        android:icon="@android:drawable/ic_dialog_info"
        android:title="Two"/>
    <item
        android:id="@+id/action_three"
        android:icon="@android:drawable/ic_dialog_email"
        android:title="Three"/>
    <item
        android:id="@+id/action_four"
        android:icon="@android:drawable/ic_popup_reminder"
        android:title="Four"/>
</menu>

And you can set the tint and text color as a color list, so the currently selected item is highlighted:

<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:color="@color/colorAccent"
        android:state_checked="false"/>
    <item
        android:color="@android:color/white"
        android:state_checked="true"/>

</selector>

Finally, you can handle the selection of the items with an OnNavigationItemSelectedListener:

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {  
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;
        switch (item.getItemId()) {
            case R.id.action_one:
                // Switch to page one
                break;
            case R.id.action_two:
                // Switch to page two
                break;
            case R.id.action_three:
                // Switch to page three
                break;
        }
        return true;
    }
});

toBe(true) vs toBeTruthy() vs toBeTrue()

In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.

Examples.

true == true; // (true) true
1 == true; // (true) truthy
"hello" == true;  // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy

This can make things simpler if you want to check if a string is set or an array has any values.

var users = [];

if(users) {
  // this array is populated. do something with the array
}

var name = "";

if(!name) {
  // you forgot to enter your name!
}

And as stated. expect(something).toBe(true) and expect(something).toBeTrue() is the same. But expect(something).toBeTruthy() is not the same as either of those.

ASP.NET MVC Razor pass model to layout

Maybe it isnt technically the proper way to handle it, but the simplest and most reasonable solution for me is to just make a class and instantiate it in the layout. It is a one time exception to the otherwise correct way of doing it. If this is done more than in the layout then you need to seriously rethink what your doing and maybe read a few more tutorials before progressing further in your project.

public class MyLayoutModel {
    public User CurrentUser {
        get {
            .. get the current user ..
        }
    }
}

then in the view

@{
    // Or get if from your DI container
    var myLayoutModel = new MyLayoutModel();
}

in .net core you can even skip that and use dependency injection.

@inject My.Namespace.IMyLayoutModel myLayoutModel

It is one of those areas that is kind of shady. But given the extremely over complicated alternatives I am seeing here, I think it is more than an ok exception to make in the name of practicality. Especially if you make sure to keep it simple and make sure any heavy logic (I would argue that there really shouldnt be any, but requirements differ) is in another class/layer where it belongs. It is certainly better than polluting ALL of your controllers or models for the sake of basically just one view..

Stopword removal with NLTK

You can use string.punctuation with built-in NLTK stopwords list:

from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation

words = tokenize(text)
wordsWOStopwords = removeStopWords(words)

def tokenize(text):
        sents = sent_tokenize(text)
        return [word_tokenize(sent) for sent in sents]

def removeStopWords(words):
        customStopWords = set(stopwords.words('english')+list(punctuation))
        return [word for word in words if word not in customStopWords]

NLTK stopwords complete list

What's the difference between all the Selection Segues?

The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1

Can't copy the icons here, but here are the descriptions:

  • Show: Present the content in the detail or master area depending on the content of the screen.

    If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.

  • Show Detail: Present the content in the detail area.

    If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.

  • Present Modally: Present the content modally.

  • Present as Popover: Present the content as a popover anchored to an existing view.

  • Custom: Create your own behaviors by using a custom segue.

How to remove square brackets in string using regex?

You probably don't even need string substitution for that. If your original string is JSON, try:

js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz

Be careful with eval, of course.

Center content vertically on Vuetify

Still surprised that no one proposed the shortest solution with align-center justify-center to center content vertically and horizontally. Check this CodeSandbox and code below:

<v-container fluid fill-height>
  <v-layout align-center justify-center>
    <v-flex>
      <!-- Some HTML elements... -->
    </v-flex>
  </v-layout>
</v-container>

What is 'Currying'?

In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant -- but, as Moses Schönfinkel (and, independently, Haskell Curry) proved, it's not needed: all you need are functions that take one argument.

So how do you deal with something you'd naturally express as, say, f(x,y)? Well, you take that as equivalent to f(x)(y) -- f(x), call it g, is a function, and you apply that function to y. In other words, you only have functions that take one argument -- but some of those functions return other functions (which ALSO take one argument;-).

As usual, wikipedia has a nice summary entry about this, with many useful pointers (probably including ones regarding your favorite languages;-) as well as slightly more rigorous mathematical treatment.

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

When to use single quotes, double quotes, and backticks in MySQL

Besides all of the (well-explained) answers, there hasn't been the following mentioned and I visit this Q&A quite often.

In a nutshell; MySQL thinks you want to do math on its own table/column and interprets hyphens such as "e-mail" as e minus mail.


Disclaimer: So I thought I would add this as an "FYI" type of answer for those who are completely new to working with databases and who may not understand the technical terms described already.

Default behavior of "git push" without a branch specified

You can set up default behavior for your git with push.default

git config push.default current

or if you have many repositories and want the same for all then

git config --global push.default current

The current in this setup means that by default you will only push the current branch when you do git push

Other options are:

  • nothing : Do not push anything
  • matching : Push all matching branches (default)
  • tracking : Push the current branch to whatever it is tracking
  • current : Push the current branch

UPDATE - NEW WAY TO DO THIS

As of Git 1.7.11 do the following:

git config --global push.default simple

This is a new setting introduced that works in the same way as current, and will be made default to git from v 2.0 according to rumors

grid controls for ASP.NET MVC?

If it is read-only a good idea would be to create a table, then apply some really easy-but-powerful JQuery to that.

For simple alternative colour, try this simple JQuery.

If you need sorting, this JQuery plug-in simply rocks.

Remove the last three characters from a string

read last 3 characters from string [Initially asked question]

You can use string.Substring and give it the starting index and it will get the substring starting from given index till end.

myString.Substring(myString.Length-3)

Retrieves a substring from this instance. The substring starts at a specified character position. MSDN

Edit, for updated post

Remove last 3 characters from string [Updated question]

To remove the last three characters from the string you can use string.Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

myString = myString.Substring(0, myString.Length-3);

String.Substring Method (Int32, Int32)

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

You can also using String.Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.

myString = myString.Remove(myString.Length-3)

String.Remove Method (Int32)

Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted

How to validate an Email in PHP?

User data is very important for a good developer, so don't ask again and again for same data, use some logic to correct some basic error in data.

Before validation of Email: First you have to remove all illegal characters from email.

//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

after that validate your email address using this filter_var() function.

filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email

For e.g.

<?php
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $email." is a valid email address";
} else {
    echo $email." is not a valid email address";
}
?>

How to copy data from one HDFS to another HDFS?

It's also useful to note that you can run the underlying MapReduce jobs with either the source or target cluster like so:

hadoop --config /path/to/hadoop/config distcp <src> <dst>

Stored procedure or function expects parameter which is not supplied

In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :

cmd.CommandType = System.Data.CommandType.StoredProcedure;

This is obviously not the case in the question above, but exception description is not very clear in this case, so I decided to specify that.

Getting the folder name from a path

It's also important to note that while getting a list of directory names in a loop, the DirectoryInfo class gets initialized once thus allowing only first-time call. In order to bypass this limitation, ensure you use variables within your loop to store any individual directory's name.

For example, this sample code loops through a list of directories within any parent directory while adding each found directory-name inside a List of string type:

[C#]

string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // Notice I've created a DirectoryInfo variable.
    DirectoryInfo dirInfo = new DirectoryInfo(directory);

    // And likewise a name variable for storing the name.
    // If this is not added, only the first directory will
    // be captured in the loop; the rest won't.
    string name = dirInfo.Name;

    // Finally we add the directory name to our defined List.
    directories.Add(name);
}

[VB.NET]

Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()

For Each directory In parentDirectory

    ' Notice I've created a DirectoryInfo variable.
    Dim dirInfo As New DirectoryInfo(directory)

    ' And likewise a name variable for storing the name.
    ' If this is not added, only the first directory will
    ' be captured in the loop; the rest won't.
    Dim name As String = dirInfo.Name

    ' Finally we add the directory name to our defined List.
    directories.Add(name)

Next directory

How to create a template function within a class? (C++)

The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.

class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}

Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.

// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}

// .cpp file
//...
template <typename T> void Foo::some_method(T t) 
{//...}
//...

template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);

How to hide a TemplateField column in a GridView

If appears to me that rows where Visible is set to false won't be accessible, that they are removed from the DOM rather than hidden, so I also used the Display: None approach. In my case, I wanted to have a hidden column that contained the key of the Row. To me, this declarative approach is a little cleaner than some of the other approaches that use code.

<style>
   .HiddenCol{display:none;}                
</style>


 <%--ROW ID--%>
      <asp:TemplateField HeaderText="Row ID">
       <HeaderStyle CssClass="HiddenCol" />
       <ItemTemplate>
       <asp:Label ID="lblROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:Label>
       </ItemTemplate>
       <ItemStyle HorizontalAlign="Right" CssClass="HiddenCol" />
       <EditItemTemplate>
       <asp:TextBox ID="txtROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:TextBox>
       </EditItemTemplate>
       <FooterStyle CssClass="HiddenCol" />
      </asp:TemplateField>

PHP Warning: Module already loaded in Unknown on line 0

In Windows 10, I fix this by comment like this

;extension=php_sockets.dll

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

How do I resolve git saying "Commit your changes or stash them before you can merge"?

This is probably being caused by CRLF issues.

See: Why should I use core.autocrlf=true in Git?

Use this to pull and force update:

git pull origin master
git checkout origin/master -f

Converting year and month ("yyyy-mm" format) to a date?

Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

Lines <- "2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

The zoo series, z, that is created above has a "yearmon" time index and looks like this:

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009 
      12      310     2379      234       14        1       34     2386 

"yearmon" can be used alone as well:

> as.yearmon("2000-03")
[1] "Mar 2000"

Note:

  1. "yearmon" class objects sort in calendar order.

  2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

How to resize html canvas element?

Prototypes can be a hassle to work with, and from the _PROTO part of the error it appears your error is caused by, say, HTMLCanvasElement.prototype.width, possibly as an attempt to resize all the canvases at once.

As a suggestion, if you are trying to resize a number of canvases at once, you could try:

<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<script type="text/javascript">
    ...
</script>

In the JavaScript, instead of invoking a prototype, try this:

$$ = function(){
    return document.querySelectorAll.apply(document,arguments);
}
for(var i in $$('canvas')){
    canvas = $$('canvas')[i];
    canvas.width = canvas.width+100;
    canvas.height = canvas.height+100;
}

This would resize all the canvases by adding 100 px to their size, as is demonstrated in this example


Hope this helped.

Converting from IEnumerable to List

I use an extension method for this. My extension method first checks to see if the enumeration is null and if so creates an empty list. This allows you to do a foreach on it without explicitly having to check for null.

Here is a very contrived example:

IEnumerable<string> stringEnumerable = null;
StringBuilder csv = new StringBuilder();
stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));

Here is the extension method:

public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
{
    return obj == null ? new List<T>() : obj.ToList();
}

Removing nan values from an array

@jmetz's answer is probably the one most people need; however it yields a one-dimensional array, e.g. making it unusable to remove entire rows or columns in matrices.

To do so, one should reduce the logical array to one dimension, then index the target array. For instance, the following will remove rows which have at least one NaN value:

x = x[~numpy.isnan(x).any(axis=1)]

See more detail here.

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

How can I verify a Google authentication API access token?

An arbitrary OAuth access token can't be used for authentication, because the meaning of the token is outside of the OAuth Core spec. It could be intended for a single use or narrow expiration window, or it could provide access which the user doesn't want to give. It's also opaque, and the OAuth consumer which obtained it might never have seen any type of user identifier.

An OAuth service provider and one or more consumers could easily use OAuth to provide a verifiable authentication token, and there are proposals and ideas to do this out there, but an arbitrary service provider speaking only OAuth Core can't provide this without other co-ordination with a consumer. The Google-specific AuthSubTokenInfo REST method, along with the user's identifier, is close, but it isn't suitable, either, since it could invalidate the token, or the token could be expired.

If your Google ID is an OpenId identifier, and your 'public interface' is either a web app or can call up the user's browser, then you should probably use Google's OpenID OP.

OpenID consists of just sending the user to the OP and getting a signed assertion back. The interaction is solely for the benefit of the RP. There is no long-lived token or other user-specific handle which could be used to indicate that a RP has successfully authenticated a user with an OP.

One way to verify a previous authentication against an OpenID identifier is to just perform authentication again, assuming the same user-agent is being used. The OP should be able to return a positive assertion without user interaction (by verifying a cookie or client cert, for example). The OP is free to require another user interaction, and probably will if the authentication request is coming from another domain (my OP gives me the option to re-authenticate this particular RP without interacting in the future). And in Google's case, the UI that the user went through to get the OAuth token might not use the same session identifier, so the user will have to re-authenticate. But in any case, you'll be able to assert the identity.

Purge or recreate a Ruby on Rails database

Use like

rake db:drop db:create db:migrate db:seed

All in one line. This is faster since the environment doesn't get reloaded again and again.

db:drop - will drop database.

db:create - will create database (host/db/password will be taken from config/database.yml)

db:migrate - will run existing migrations from directory (db/migration/.rb)*.

db:seed - will run seed data possible from directory (db/migration/seed.rb)..

I usually prefer:

rake db:reset

to do all at once.

Cheers!

Remove all constraints affecting a UIView

This approach worked for me:

@interface UIView (RemoveConstraints)

- (void)removeAllConstraints;

@end


@implementation UIView (RemoveConstraints)

- (void)removeAllConstraints
{
    UIView *superview = self.superview;
    while (superview != nil) {
        for (NSLayoutConstraint *c in superview.constraints) {
            if (c.firstItem == self || c.secondItem == self) {
                [superview removeConstraint:c];
            }
        }
        superview = superview.superview;
    }

    [self removeConstraints:self.constraints];
    self.translatesAutoresizingMaskIntoConstraints = YES;
}

@end

After it's done executing your view remains where it was because it creates autoresizing constraints. When I don't do this the view usually disappears. Additionally, it doesn't just remove constraints from superview but traversing all the way up as there may be constraints affecting it in ancestor views.


Swift 4 Version

extension UIView {
    
    public func removeAllConstraints() {
        var _superview = self.superview
        
        while let superview = _superview {
            for constraint in superview.constraints {
                
                if let first = constraint.firstItem as? UIView, first == self {
                    superview.removeConstraint(constraint)
                }
                
                if let second = constraint.secondItem as? UIView, second == self {
                    superview.removeConstraint(constraint)
                }
            }
            
            _superview = superview.superview
        }
        
        self.removeConstraints(self.constraints)
        self.translatesAutoresizingMaskIntoConstraints = true
    }
}

How to build query string with Javascript

These answers are very helpful, but i want to add another answer, that may help you build full URL. This can help you concat base url, path, hash and parameters.

var url = buildUrl('http://mywebsite.com', {
        path: 'about',
        hash: 'contact',
        queryParams: {
            'var1': 'value',
            'var2': 'value2',
            'arr[]' : 'foo'
        }
    });
    console.log(url);

You can download via npm https://www.npmjs.com/package/build-url

Demo:

_x000D_
_x000D_
;(function () {_x000D_
  'use strict';_x000D_
_x000D_
  var root = this;_x000D_
  var previousBuildUrl = root.buildUrl;_x000D_
_x000D_
  var buildUrl = function (url, options) {_x000D_
    var queryString = [];_x000D_
    var key;_x000D_
    var builtUrl;_x000D_
    var caseChange; _x000D_
    _x000D_
    // 'lowerCase' parameter default = false,  _x000D_
    if (options && options.lowerCase) {_x000D_
        caseChange = !!options.lowerCase;_x000D_
    } else {_x000D_
        caseChange = false;_x000D_
    }_x000D_
_x000D_
    if (url === null) {_x000D_
      builtUrl = '';_x000D_
    } else if (typeof(url) === 'object') {_x000D_
      builtUrl = '';_x000D_
      options = url;_x000D_
    } else {_x000D_
      builtUrl = url;_x000D_
    }_x000D_
_x000D_
    if(builtUrl && builtUrl[builtUrl.length - 1] === '/') {_x000D_
      builtUrl = builtUrl.slice(0, -1);_x000D_
    } _x000D_
_x000D_
    if (options) {_x000D_
      if (options.path) {_x000D_
          var localVar = String(options.path).trim(); _x000D_
          if (caseChange) {_x000D_
            localVar = localVar.toLowerCase();_x000D_
          }_x000D_
          if (localVar.indexOf('/') === 0) {_x000D_
              builtUrl += localVar;_x000D_
          } else {_x000D_
            builtUrl += '/' + localVar;_x000D_
          }_x000D_
      }_x000D_
_x000D_
      if (options.queryParams) {_x000D_
        for (key in options.queryParams) {_x000D_
          if (options.queryParams.hasOwnProperty(key) && options.queryParams[key] !== void 0) {_x000D_
            var encodedParam;_x000D_
            if (options.disableCSV && Array.isArray(options.queryParams[key]) && options.queryParams[key].length) {_x000D_
              for(var i = 0; i < options.queryParams[key].length; i++) {_x000D_
                encodedParam = encodeURIComponent(String(options.queryParams[key][i]).trim());_x000D_
                queryString.push(key + '=' + encodedParam);_x000D_
              }_x000D_
            } else {              _x000D_
              if (caseChange) {_x000D_
                encodedParam = encodeURIComponent(String(options.queryParams[key]).trim().toLowerCase());_x000D_
              }_x000D_
              else {_x000D_
                encodedParam = encodeURIComponent(String(options.queryParams[key]).trim());_x000D_
              }_x000D_
              queryString.push(key + '=' + encodedParam);_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
        builtUrl += '?' + queryString.join('&');_x000D_
      }_x000D_
_x000D_
      if (options.hash) {_x000D_
        if(caseChange)_x000D_
            builtUrl += '#' + String(options.hash).trim().toLowerCase();_x000D_
        else_x000D_
            builtUrl += '#' + String(options.hash).trim();_x000D_
      }_x000D_
    } _x000D_
    return builtUrl;_x000D_
  };_x000D_
_x000D_
  buildUrl.noConflict = function () {_x000D_
    root.buildUrl = previousBuildUrl;_x000D_
    return buildUrl;_x000D_
  };_x000D_
_x000D_
  if (typeof(exports) !== 'undefined') {_x000D_
    if (typeof(module) !== 'undefined' && module.exports) {_x000D_
      exports = module.exports = buildUrl;_x000D_
    }_x000D_
    exports.buildUrl = buildUrl;_x000D_
  } else {_x000D_
    root.buildUrl = buildUrl;_x000D_
  }_x000D_
}).call(this);_x000D_
_x000D_
_x000D_
var url = buildUrl('http://mywebsite.com', {_x000D_
  path: 'about',_x000D_
  hash: 'contact',_x000D_
  queryParams: {_x000D_
   'var1': 'value',_x000D_
   'var2': 'value2',_x000D_
   'arr[]' : 'foo'_x000D_
  }_x000D_
 });_x000D_
 console.log(url);
_x000D_
_x000D_
_x000D_

How to filter in NaN (pandas)?

Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.

W3WP.EXE using 100% CPU - where to start?

Process Explorer is an excellent tool for troubleshooting. You can try it for finding the problem of high CPU usage. It gives you an insight into the way your application works.

You can also try Procdump to dump the process and analyze what really happened on the CPU.

Create an ISO date object in javascript

Try using the ISO string

var isodate = new Date().toISOString()

See also: method definition at MDN.

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Correct way to write loops for promise.

I'd make something like this:

var request = []
while(count<10){
   request.push(db.getUser(email).then(function(res) { return res; }));
   count++
};

Promise.all(request).then((dataAll)=>{
  for (var i = 0; i < dataAll.length; i++) {

      logger.log(dataAll[i]); 
  }  
});

in this way, dataAll is an ordered array of all element to log. And log operation will perform when all promises are done.

How to pass List<String> in post method using Spring MVC?

I had the same use case, You can change your method defination in the following way :

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody Map<String,List<String>> fruits) {
    ..
}

The only problem is it accepts any key in place of "fruits" but You can easily get rid of a wrapper if it is not big functionality.

How to return JSON data from spring Controller using @ResponseBody

Considering @Arpit answer, for me it worked only when I add two jackson dependencies:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>

and configured, of cause, web.xml <mvc:annotation-driven/>.

Original answer that helped me is here: https://stackoverflow.com/a/33896080/3014866

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

The application that you are running is blocked because the application does not comply with security guidelines implemented in Java 7 Update 51

Replacing blank values (white space) with NaN in pandas

I will did this:

df = df.apply(lambda x: x.str.strip()).replace('', np.nan)

or

df = df.apply(lambda x: x.str.strip() if isinstance(x, str) else x).replace('', np.nan)

You can strip all str, then replace empty str with np.nan.

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

Reference member variables as class members

Member references are usually considered bad. They make life hard compared to member pointers. But it's not particularly unsual, nor is it some special named idiom or thing. It's just aliasing.

this in equals method

this is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.

What's the syntax for mod in java

Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainder operator %. For your exact example:

if ((a % 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}

This can be simplified to a one-liner:

isEven = (a % 2) == 0;

yii2 hidden input value

Changing the value here doesn't make sense, because it's active field. It means value will be synchronized with the model value.

Just change the value of $model->hidden1 to change it. Or it will be changed after receiving data from user after submitting form.

With using non-active hidden input it will be like that:

use yii\helpers\Html;

...

echo Html::hiddenInput('name', $value);

But the latter is more suitable for using outside of model.

How to Apply global font to whole HTML document

Use the following css:

* {
    font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}

The *-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.

Note that the !important-flag will render the font-style for * to be absolute, even if other selectors have been used to set the text (for example, the body or maybe a p).

MySQL 'create schema' and 'create database' - Is there any difference

Strictly speaking, the difference between Database and Schema is inexisting in MySql.

However, this is not the case in other database engines such as SQL Server. In SQL server:,

Every table belongs to a grouping of objects in the database called database schema. It's a container or namespace (Querying Microsoft SQL Server 2012)

By default, all the tables in SQL Server belong to a default schema called dbo. When you query a table that hasn't been allocated to any particular schema, you can do something like:

SELECT *
FROM your_table

which is equivalent to:

SELECT *
FROM dbo.your_table

Now, SQL server allows the creation of different schema, which gives you the possibility of grouping tables that share a similar purpose. That helps to organize the database.

For example, you can create an schema called sales, with tables such as invoices, creditorders (and any other related with sales), and another schema called lookup, with tables such as countries, currencies, subscriptiontypes (and any other table used as look up table).

The tables that are allocated to a specific domain are displayed in SQL Server Studio Manager with the schema name prepended to the table name (exactly the same as the tables that belong to the default dbo schema).

There are special schemas in SQL Server. To quote the same book:

There are several built-in database schemas, and they can't be dropped or altered:

1) dbo, the default schema.

2) guest contains objects available to a guest user ("guest user" is a special role in SQL Server lingo, with some default and highly restricted permissions). Rarely used.

3) INFORMATION_SCHEMA, used by the Information Schema Views

4) sys, reserved for SQL Server internal use exclusively

Schemas are not only for grouping. It is actually possible to give different permissions for each schema to different users, as described MSDN.

Doing this way, the schema lookup mentioned above could be made available to any standard user in the database (e.g. SELECT permissions only), whereas a table called supplierbankaccountdetails may be allocated in a different schema called financial, and to give only access to the users in the group accounts (just an example, you get the idea).

Finally, and quoting the same book again:

It isn't the same Database Schema and Table Schema. The former is the namespace of a table, whereas the latter refers to the table definition

File Explorer in Android Studio

Device Explorer path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/...

Logs File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/storage/emulated/0/Android/data/com.app.domain/files/LogFiles/

Shared Preferences File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/data/data/com.app.domain/shared_prefs/

What does API level mean?

An API is ready-made source code library.

In Java for example APIs are a set of related classes and interfaces that come in packages. This picture illustrates the libraries included in the Java Standard Edition API. Packages are denoted by their color.

This pictures illustrates the libraries included in the Java Standard Edition API

Failed to connect to mailserver at "localhost" port 25

First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.

Warning: implode() [function.implode]: Invalid arguments passed

You can try

echo implode(', ', (array)$ret);

How to put a delay on AngularJS instant search?

Another solution is to add a delay functionality to model update. The simple directive seems to do a trick:

app.directive('delayedModel', function() {
    return {
        scope: {
            model: '=delayedModel'
        },
        link: function(scope, element, attrs) {

            element.val(scope.model);

            scope.$watch('model', function(newVal, oldVal) {
                if (newVal !== oldVal) {
                    element.val(scope.model);        
                }
            });

            var timeout;
            element.on('keyup paste search', function() {
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    scope.model = element[0].value;
                    element.val(scope.model);
                    scope.$apply();
                }, attrs.delay || 500);
            });
        }
    };
});

Usage:

<input delayed-model="searchText" data-delay="500" id="searchText" type="search" placeholder="live search..." />

So you just use delayed-model in place of ng-model and define desired data-delay.

Demo: http://plnkr.co/edit/OmB4C3jtUD2Wjq5kzTSU?p=preview

How do you redirect HTTPS to HTTP?

None of the answer works for me on Wordpress website but following works ( it's similar to other answers but have a little change)

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

How do I do a Date comparison in Javascript?

You can try this code for checking which date value is the highest from two dates with a format MM/DD/YYYY:

function d_check() {
    var dl_sdt=document.getElementIdBy("date_input_Id1").value; //date one
    var dl_endt=document.getElementIdBy("date_input_Id2").value; //date two

    if((dl_sdt.substr(6,4)) > (dl_endt.substr(6,4))) {
        alert("first date is greater");
        return false;
    }

    else if((((dl_sdt.substr(0,2)) > (dl_endt.
        substr(0,2)))&&(frdt(dl_sdt.substr(3,2)) > (dl_endt.substr(3,2))))||
        (((dl_sdt.substr(0,2)) > (dl_endt.substr(0,2)))&&
        ((dl_sdt.substr(3,2)) < (dl_endt.substr(3,2))))||
        (((dl_sdt.substr(0,2)) == (dl_endt.substr(0,2)))&&((dl_sdt.substr(3,2)) > 
        (dl_endt.substr(3,2))))) {
            alert("first date is greater");
        return false;
    }

    alert("second date is digher");
    return true;
}

/*for checking this....create a form and give id's to two date inputs.The date format should be mm/dd/yyyy or mm-dd-yyyy or mm:dd:yyyy or mm.dd.yyyy like this. */

get all the images from a folder in php

You can simply show your actual image directory(less secure). By just 2 line of code.

 $dir = base_url()."photos/";

echo"<a href=".$dir.">Photo Directory</a>";

Using multiple delimiters in awk

For a field separator of any number 2 through 5 or letter a or # or a space, where the separating character must be repeated at least 2 times and not more than 6 times, for example:

awk -F'[2-5a# ]{2,6}' ...

I am sure variations of this exist using ( ) and parameters

How are Anonymous inner classes used in Java?

Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:

public interface F<A, B> {
   B f(A a);
}

You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:

public static int larger(final List<Integer> ns, final int i) {
  for (Integer n : ns)
     if (n > i)
        return n;
  return i;
}

And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:

public static int smaller(final List<Integer> ns, final int i) {
   for (Integer n : ns)
      if (n < i)
         return n;
   return i;
}

These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:

public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
   for (T t : ts)
      if (f.f(t))
         return t;
   return z;
}

You can use an anonymous class to use the firstMatch method:

F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
   Boolean f(final Integer n) {
      return n > 10;
   }
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);

This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.

A nice library for programming Java in this style: Functional Java.

How to submit a form when the return key is pressed?

Use the <button> tag. From the W3C standard:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

Basically there is another tag, <button>, which requires no javascript, that also can submit a form. It can be styled much in the way of a <div> tag (including <img /> inside the button tag). The buttons from the <input /> tag are not nearly as flexible.

<button type="submit">
    <img src="my-icon.png" />
    Clicking will submit the form
</button>

There are three types to set on the <button>; they map to the <input> button types.

<button type="submit">Will submit the form</button>
<button type="reset">Will reset the form</button>
<button type="button">Will do nothing; add javascript onclick hooks</button>

Standards

I use <button> tags with and a bit of styling to get colorful and functional form buttons. Note that it's possible to write css for, for example, <a class="button"> links share to styling with the <button> element.

Back to previous page with header( "Location: " ); in PHP

Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}

Switching the order of block elements with CSS

I known this is old, but I found a easier solution and it works on ie10, firefox and chrome:

<div id="wrapper">
  <div id="one">One</div>
  <div id="two">Two</div>
  <div id="three">Three</div>
</div> 

This is the css:

#wrapper {display:table;}
#one {display:table-footer-group;}
#three {display:table-header-group;}

And the result:

"Three"
"Two"
"One"

I found it here.

Serialize Class containing Dictionary member

You can use ExtendedXmlSerializer. If you have a class:

public class ConfigFile
{
    public String guiPath { get; set; }
    public string configPath { get; set; }
    public Dictionary<string, string> mappedDrives {get;set;} 

    public ConfigFile()
    {
        mappedDrives = new Dictionary<string, string>();
    }
}

and create instance of this class:

ConfigFile config = new ConfigFile();
config.guiPath = "guiPath";
config.configPath = "configPath";
config.mappedDrives.Add("Mouse", "Logitech MX Master");
config.mappedDrives.Add("keyboard", "Microsoft Natural Ergonomic Keyboard 4000");

You can serialize this object using ExtendedXmlSerializer:

ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
var xml = serializer.Serialize(config);

Output xml will look like:

<?xml version="1.0" encoding="utf-8"?>
<ConfigFile type="Program+ConfigFile">
    <guiPath>guiPath</guiPath>
    <configPath>configPath</configPath>
    <mappedDrives>
        <Item>
            <Key>Mouse</Key>
            <Value>Logitech MX Master</Value>
        </Item>
        <Item>
            <Key>keyboard</Key>
            <Value>Microsoft Natural Ergonomic Keyboard 4000</Value>
        </Item>
    </mappedDrives>
</ConfigFile>

You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

Here is online example

How to commit a change with both "message" and "description" from the command line?

git commit -a -m "Your commit message here"

will quickly commit all changes with the commit message. Git commit "title" and "description" (as you call them) are nothing more than just the first line, and the rest of the lines in the commit message, usually separated by a blank line, by convention. So using this command will just commit the "title" and no description.

If you want to commit a longer message, you can do that, but it depends on which shell you use.

In bash the quick way would be:

git commit -a -m $'Commit title\n\nRest of commit message...'

javascript if number greater than number

You should convert them to number before compare.

Try:

if (+x > +y) {
  //...
}

or

if (Number(x) > Number(y)) {
  // ...
}

Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.

How to get first record in each group using Linq

var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());

How do I display the value of a Django form field in a template?

I have a simple solution for you!

{{ form.data.email }}

I tried this and it worked. This requires your view to populate the form class with the POST data.

Very simple example:

def your_view(request):
  if request.method == 'POST':
    form = YourForm(request.POST)
    if form.is_valid():
      # some code here
  else:
    form = YourForm()

  return render_to_response('template.html', {'form':form})

Hope that helps you. If you have any questions please let me know.

Are duplicate keys allowed in the definition of binary search trees?

In a BST, all values descending on the left side of a node are less than (or equal to, see later) the node itself. Similarly, all values descending on the right side of a node are greater than (or equal to) that node value(a).

Some BSTs may choose to allow duplicate values, hence the "or equal to" qualifiers above. The following example may clarify:

     14
    /  \
  13    22
 /     /  \
1    16    29
          /  \
        28    29

This shows a BST that allows duplicates(b) - you can see that to find a value, you start at the root node and go down the left or right subtree depending on whether your search value is less than or greater than the node value.

This can be done recursively with something like:

def hasVal (node, srchval):
    if node == NULL:
         return false
    if node.val == srchval:
        return true
    if node.val > srchval:
        return hasVal (node.left, srchval)
    return hasVal (node.right, srchval)

and calling it with:

foundIt = hasVal (rootNode, valToLookFor)

Duplicates add a little complexity since you may need to keep searching once you've found your value, for other nodes of the same value. Obviously that doesn't matter for hasVal since it doesn't matter how many there are, just whether at least one exists. It will however matter for things like countVal, since it needs to know how many there are.


(a) You could actually sort them in the opposite direction should you so wish provided you adjust how you search for a specific key. A BST need only maintain some sorted order, whether that's ascending or descending (or even some weird multi-layer-sort method like all odd numbers ascending, then all even numbers descending) is not relevant.


(b) Interestingly, if your sorting key uses the entire value stored at a node (so that nodes containing the same key have no other extra information to distinguish them), there can be performance gains from adding a count to each node, rather than allowing duplicate nodes.

The main benefit is that adding or removing a duplicate will simply modify the count rather than inserting or deleting a new node (an action that may require re-balancing the tree).

So, to add an item, you first check if it already exists. If so, just increment the count and exit. If not, you need to insert a new node with a count of one then rebalance.

To remove an item, you find it then decrement the count - only if the resultant count is zero do you then remove the actual node from the tree and rebalance.

Searches are also quicker given there are fewer nodes but that may not be a large impact.

For example, the following two trees (non-counting on the left, and counting on the right) would be equivalent (in the counting tree, i.c means c copies of item i):

     __14__                    ___22.2___
    /      \                  /          \
  14        22             7.1            29.1
 /  \      /  \           /   \          /    \
1    14  22    29      1.1     14.3  28.1      30.1
 \            /  \
  7         28    30

Removing the leaf-node 22 from the left tree would involve rebalancing (since it now has a height differential of two) the resulting 22-29-28-30 subtree such as below (this is one option, there are others that also satisfy the "height differential must be zero or one" rule):

\                      \
 22                     29
   \                   /  \
    29      -->      28    30
   /  \             /
 28    30         22

Doing the same operation on the right tree is a simple modification of the root node from 22.2 to 22.1 (with no rebalancing required).

Retrieving the first digit of a number

    int number = 534;
    int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));

Focusable EditText inside ListView

Just try this

android:windowSoftInputMode="adjustNothing"

in the

activity

section of your manifest. Yes, it adjusts nothings, which means the editText will stay where it is when IME is opening. But that's just an little inconvenience that still completely solves the problem of losing focus.

Where does the iPhone Simulator store its data?

Where Xcode stores simulators in 2019+ Catalina, Xcode 11.0

Runtimes

$ open ~/Library/Developer/CoreSimulator/Profiles/Runtimes

For example: iOS 13.0, watchOS 6.0 These take the most space, by far. Each one can be up to ~5GB

Devices

$ open ~/Library/Developer/CoreSimulator/Devices

For example: iPhone Xr, iPhone 11 Pro Max. These are typically <15 mb each.

Explanation

Simulators are split between runtimes and devices. If you run $ xcrun simctl list you can see an overview, but if you want to find the physical location of these simulators, look in these directories I've shown.

It's totally safe to delete runtimes you don't support. You can reinstall these later if you want.

C# switch on type

Update: This got fixed in C# 7.0 with pattern matching

switch (MyObj)
    case Type1 t1: 
    case Type2 t2:
    case Type3 t3:

Old answer:

It is a hole in C#'s game, no silver bullet yet.

You should google on the 'visitor pattern' but it might be a little heavy for you but still something you should know about.

Here's another take on the matter using Linq: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx

Otherwise something along these lines could help

// nasty..
switch(MyObj.GetType.ToString()){
  case "Type1": etc
}

// clumsy...
if myObj  is Type1 then
if myObj is Type2 then

etc.

How to view log output using docker-compose run?

Unfortunately we need to run docker-compose logs separately from docker-compose run. In order to get this to work reliably we need to suppress the docker-compose run exit status then redirect the log and exit with the right status.

#!/bin/bash
set -euo pipefail
docker-compose run app | tee app.log || failed=yes
docker-compose logs --no-color > docker-compose.log
[[ -z "${failed:-}" ]] || exit 1

Undefined symbols for architecture x86_64 on Xcode 6.1

It turned out I forgot to write my @implementation part.

Difference between variable declaration syntaxes in Javascript (including global variables)?

<title>Index.html</title>
<script>
    var varDeclaration = true;
    noVarDeclaration = true;
    window.hungOnWindow = true;
    document.hungOnDocument = true;
</script>
<script src="external.js"></script>

/* external.js */

console.info(varDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(noVarDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(window.hungOnWindow == true); // could be .log, alert etc
// returns true in IE8

console.info(document.hungOnDocument == true); // could be .log, alert etc
// returns ??? in IE8 (untested!)  *I personally find this more clugy than hanging off window obj

Is there a global object that all vars are hung off of by default? eg: 'globals.noVar declaration'

jQuery Ajax PUT with parameters

Use:

$.ajax({
    url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
        console.log(data);
    }
});

Always remember to use _METHOD=PUT.

What is SuppressWarnings ("unchecked") in Java?

A warning by which the compiler indicates that it cannot ensure type safety. The term "unchecked" warning is misleading. It does not mean that the warning is unchecked in any way. The term "unchecked" refers to the fact that the compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. In this sense, certain operations are "unchecked".

The most common source of "unchecked" warnings is the use of raw types. "unchecked" warnings are issued when an object is accessed through a raw type variable, because the raw type does not provide enough type information to perform all necessary type checks.

Example (of unchecked warning in conjunction with raw types):

TreeSet set = new TreeSet(); 
set.add("abc");        // unchecked warning 
set.remove("abc");
warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.TreeSet 
               set.add("abc");  
                      ^

When the add method is invoked the compiler does not know whether it is safe to add a String object to the collection. If the TreeSet is a collection that contains String s (or a supertype thereof), then it would be safe. But from the type information provided by the raw type TreeSet the compiler cannot tell. Hence the call is potentially unsafe and an "unchecked" warning is issued.

"unchecked" warnings are also reported when the compiler finds a cast whose target type is either a parameterized type or a type parameter.

Example (of an unchecked warning in conjunction with a cast to a parameterized type or type variable):

  class Wrapper<T> { 
  private T wrapped ; 
  public Wrapper (T arg) {wrapped = arg;} 
  ... 
  public Wrapper <T> clone() { 
    Wrapper<T> clon = null; 
     try {  
       clon = (Wrapper<T>) super.clone(); // unchecked warning 
     } catch (CloneNotSupportedException e) {  
       throw new InternalError();  
     } 
     try {  
       Class<?> clzz = this.wrapped.getClass(); 
       Method   meth = clzz.getMethod("clone", new Class[0]); 
       Object   dupl = meth.invoke(this.wrapped, new Object[0]); 
       clon.wrapped = (T) dupl; // unchecked warning 
     } catch (Exception e) {} 
     return clon; 
  } 
} 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: Wrapper <T> 
                  clon = ( Wrapper <T>)super.clone();  
                                                ^ 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: T 
                  clon. wrapped = (T)dupl;

A cast whose target type is either a (concrete or bounded wildcard) parameterized type or a type parameter is unsafe, if a dynamic type check at runtime is involved. At runtime, only the type erasure is available, not the exact static type that is visible in the source code. As a result, the runtime part of the cast is performed based on the type erasure, not on the exact static type.

In the example, the cast to Wrapper would check whether the object returned from super.clone is a Wrapper , not whether it is a wrapper with a particular type of members. Similarly, the casts to the type parameter T are cast to type Object at runtime, and probably optimized away altogether. Due to type erasure, the runtime system is unable to perform more useful type checks at runtime.

In a way, the source code is misleading, because it suggests that a cast to the respective target type is performed, while in fact the dynamic part of the cast only checks against the type erasure of the target type. The "unchecked" warning is issued to draw the programmer's attention to this mismatch between the static and dynamic aspect of the cast.

Please refer: What is an "unchecked" warning?

Java Comparator class to sort arrays

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

Using Axios GET with Authorization Header in React-Native App

For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

Big thanks to @swapnil for trying to help me debug this.

   const data = {
      grant_type: USER_GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE_INT,
      username: DEMO_EMAIL,
      password: DEMO_PASSWORD
    };



  axios.post(TOKEN_URL, Querystring.stringify(data))   
   .then(response => {
      console.log(response.data);
      USER_TOKEN = response.data.access_token;
      console.log('userresponse ' + response.data.access_token); 
    })   
   .catch((error) => {
      console.log('error ' + error);   
   });



const AuthStr = 'Bearer '.concat(USER_TOKEN); 
axios.get(URL, { headers: { Authorization: AuthStr } })
 .then(response => {
     // If request is good...
     console.log(response.data);
  })
 .catch((error) => {
     console.log('error ' + error);
  });

Hide console window from Process.Start C#

This doesn't show the window:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;

...
cmd.Start();

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

How do I get the picture size with PIL?

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

When to Redis? When to MongoDB?

All of the answers (at the time of this writing) assume each of Redis, MongoDB, and perhaps an SQL-based relational database are essentially the same tool: "store data". They don't consider data models at all.

MongoDB: Complex Data

MongoDB is a document store. To compare with an SQL-driven relational database: relational databases simplify to indexed CSV files, each file being a table; document stores simplify to indexed JSON files, each file being a document, with multiple files grouped together.

JSON files are similar in structure to XML and YAML files, and to dictionaries as in Python, so think of your data in that sort of hierarchy. When indexing, the structure is the key: A document contains named keys, which contain either further documents, arrays, or scalar values. Consider the below document.

{
  _id:  0x194f38dc491a,
  Name:  "John Smith",
  PhoneNumber:
    Home: "555 999-1234",
    Work: "555 999-9876",
    Mobile: "555 634-5789"
  Accounts:
    - "379-1111"
    - "379-2574"
    - "414-6731"
}

The above document has a key, PhoneNumber.Mobile, which has value 555 634-5789. You can search through a collection of documents where the key, PhoneNumber.Mobile, has some value; they're indexed.

It also has an array of Accounts which hold multiple indexes. It is possible to query for a document where Accounts contains exactly some subset of values, all of some subset of values, or any of some subset of values. That means you can search for Accounts = ["379-1111", "379-2574"] and not find the above; you can search for Accounts includes ["379-1111"] and find the above document; and you can search for Accounts includes any of ["974-3785","414-6731"] and find the above and whatever document includes account "974-3785", if any.

Documents go as deep as you want. PhoneNumber.Mobile could hold an array, or even a sub-document (PhoneNumber.Mobile.Work and PhoneNumber.Mobile.Personal). If your data is highly structured, documents are a large step up from relational databases.

If your data is mostly flat, relational, and rigidly structured, you're better off with a relational database. Again, the big sign is whether your data models best to a collection of interrelated CSV files or a collection of XML/JSON/YAML files.

For most projects, you'll have to compromise, accepting a minor work-around in some small areas where either SQL or Document Stores don't fit; for some large, complex projects storing a broad spread of data (many columns; rows are irrelevant), it will make sense to store some data in one model and other data in another model. Facebook uses both SQL and a graph database (where data is put into nodes, and nodes are connected to other nodes); Craigslist used to use MySQL and MongoDB, but had been looking into moving entirely onto MongoDB. These are places where the span and relationship of the data faces significant handicaps if put under one model.

Redis: Key-Value

Redis is, most basically, a key-value store. Redis lets you give it a key and look up a single value. Redis itself can store strings, lists, hashes, and a few other things; however, it only looks up by name.

Cache invalidation is one of computer science's hard problems; the other is naming things. That means you'll use Redis when you want to avoid hundreds of excess look-ups to a back-end, but you'll have to figure out when you need a new look-up.

The most obvious case of invalidation is update on write: if you read user:Simon:lingots = NOTFOUND, you might SELECT Lingots FROM Store s INNER JOIN UserProfile u ON s.UserID = u.UserID WHERE u.Username = Simon and store the result, 100, as SET user:Simon:lingots = 100. Then when you award Simon 5 lingots, you read user:Simon:lingots = 100, SET user:Simon:lingots = 105, and UPDATE Store s INNER JOIN UserProfile u ON s.UserID = u.UserID SET s.Lingots = 105 WHERE u.Username = Simon. Now you have 105 in your database and in Redis, and can get user:Simon:lingots without querying the database.

The second case is updating dependent information. Let's say you generate chunks of a page and cache their output. The header shows the player's experience, level, and amount of money; the player's Profile page has a block that shows their statistics; and so forth. The player gains some experience. Well, now you have several templates:Header:Simon, templates:StatsBox:Simon, templates:GrowthGraph:Simon, and so forth fields where you've cached the output of a half-dozen database queries run through a template engine. Normally, when you display these pages, you say:

$t = GetStringFromRedis("templates:StatsBox:" + $playerName);
if ($t == null) {
  $t = BuildTemplate("StatsBox.tmpl",
                     GetStatsFromDatabase($playerName));
  SetStringInRedis("Templates:StatsBox:" + $playerName, $t);
}
print $t;

Because you just updated the results of GetStatsFromDatabase("Simon"), you have to drop templates:*:Simon out of your key-value cache. When you try to render any of these templates, your application will churn away fetching data from your database (PostgreSQL, MongoDB) and inserting it into your template; then it will store the result in Redis and, hopefully, not bother making database queries and rendering templates the next time it displays that block of output.

Redis also lets you do publisher-subscribe message queues and such. That's another topic entirely. Point here is Redis is a key-value cache, which differs from a relational database or a document store.

Conclusion

Pick your tools based on your needs. The largest need is usually data model, as that determines how complex and error-prone your code is. Specialized applications will lean on performance, places where you write everything in a mixture of C and Assembly; most applications will just handle the generalized case and use a caching system such as Redis or Memcached, which is a lot faster than either a high-performance SQL database or a document store.

How to find all duplicate from a List<string>?

I'm assuming each string in your list contains several words, let me know if that's incorrect.

List<string> list = File.RealAllLines("foobar.txt").ToList();

var words = from line in list
            from word in line.Split(new[] { ' ', ';', ',', '.', ':', '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
            select word;

var duplicateWords = from w in words
                     group w by w.ToLower() into g
                     where g.Count() > 1
                     select new
                     {
                         Word = g.Key,
                         Count = g.Count()
                     }

Is there any way to delete local commits in Mercurial?

You can get around this even more easily with the Rebase extension, just use hg pull --rebase and your commits are automatically re-comitted to the pulled revision, avoiding the branching issue.

Extract values in Pandas value_counts()

If anyone missed it out in the comments, try this:

dataframe[column].value_counts().to_frame()

How to get docker-compose to always re-create containers from fresh images?

By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:

docker-compose down

Then if you have new changes on your images or Dockerfiles use:

docker-compose build --no-cache

Finally:docker-compose up

In one command: docker-compose down && docker-compose build --no-cache && docker-compose up

Bold & Non-Bold Text In A Single UILabel?

To make text bold as well as underline in a UILabel. Just add the following lines in your code.

NSRange range1 = [lblTermsAndCondition.text rangeOfString:NSLocalizedString(@"bold_terms", @"")];
NSRange range2 = [lblTermsAndCondition.text rangeOfString:NSLocalizedString(@"bold_policy", @"")];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:lblTermsAndCondition.text];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:fontBold size:12.0]}
                        range:range1];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:fontBold size:12.0]}
                        range:range2];


[attributedText addAttribute:(NSString*)kCTUnderlineStyleAttributeName
                  value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
                  range:range1];

[attributedText addAttribute:(NSString*)kCTUnderlineStyleAttributeName
                       value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
                       range:range2];



lblTermsAndCondition.attributedText = attributedText;

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

ORA-01843 not a valid month- Comparing Dates

If the source date contains minutes and seconds part, your date comparison will fail. you need to convert source date to the required format using to_char and the target date also.

Comment out HTML and PHP together

The <!-- --> is only for HTML commenting and the PHP will still run anyway...

Therefore the best thing I would do is also to comment out the PHP...

Favicon dimensions?

favicon.ico is 16x16

<link rel="shortcut icon" href="favicon.ico"/>

And I use these ones to be beautiful in mobile and tablet:

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/ico144.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/ico114.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/ico72.png">
<link rel="apple-touch-icon-precomposed" href="img/ico57.png">

It's important to use the name "favicon.ico" in the root because many browsers will try to find there first.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Handling a timeout error in python sockets

Here is a solution I use in one of my project.

network_utils.telnet

import socket
from timeit import default_timer as timer

def telnet(hostname, port=23, timeout=1):
    start = timer()
    connection = socket.socket()
    connection.settimeout(timeout)
    try:
        connection.connect((hostname, port))
        end = timer()
        delta = end - start
    except (socket.timeout, socket.gaierror) as error:
        logger.debug('telnet error: ', error)
        delta = None
    finally:
        connection.close()

    return {
        hostname: delta
    }

Tests

def test_telnet_is_null_when_host_unreachable(self):
    hostname = 'unreachable'

    response = network_utils.telnet(hostname)

    self.assertDictEqual(response, {'unreachable': None})

def test_telnet_give_time_when_reachable(self):
    hostname = '127.0.0.1'

    response = network_utils.telnet(hostname, port=22)

    self.assertGreater(response[hostname], 0)

How to check if ZooKeeper is running or up from command prompt?

From a Windows 10

  • Open Command Promt then type telnet localhost 2181and then you type srvr OR
  • From inside bin folder, open a PowerShell window and type zkServer.sh status

Properly Handling Errors in VBA (Excel)

Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume statement to clear the Error Handler. The Resume also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.

Block 3 fails because there is no Resume statement so any attempt at error handling after that will fail.

Every error handler must be ended by exiting the procedure or a Resume statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.

But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.

Sub InLineErrorHandling()

    'code without error handling

BeginTry1:

    'activate inline error handler
    On Error GoTo ErrHandler1

        'code block that may result in an error
        Dim a As String: a = "Abc"
        Dim c As Integer: c = a 'type mismatch

ErrHandler1:

    'handle the error
    If Err.Number <> 0 Then

        'the error handler has deactivated the previous error handler

        MsgBox (Err.Description)

        'Resume (or exit procedure) is the only way to get out of an error handling block
        'otherwise the following On Error statements will have no effect
        'CAUTION: it also reactivates the previous error handler
        Resume EndTry1
    End If

EndTry1:
    'CAUTION: since the Resume statement reactivates the previous error handler
    'you must ALWAYS use an On Error GoTo statement here
    'because another error here would cause an endless loop
    'use On Error GoTo 0 or On Error GoTo <Label>
    On Error GoTo 0

    'more code with or without error handling

End Sub

Sources:

The key to making this work is to use a Resume statement immediately followed by another On Error statement. The Resume is within the error handler and diverts code to the EndTry1 label. You must immediately set another On Error statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.

To avoid using the previous error handler again you need to set On Error to a new error handler or simply use On Error Goto 0 to cancel all error handling.

How does Python return multiple values from a function?

mentioned also here, you can use this:

import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2

Custom exception type

I often use an approach with prototypal inheritance. Overriding toString() gives you the advantage that tools like Firebug will log the actual information instead of [object Object] to the console for uncaught exceptions.

Use instanceof to determine the type of exception.

main.js

// just an exemplary namespace
var ns = ns || {};

// include JavaScript of the following
// source files here (e.g. by concatenation)

var someId = 42;
throw new ns.DuplicateIdException('Another item with ID ' +
    someId + ' has been created');
// Firebug console:
// uncaught exception: [Duplicate ID] Another item with ID 42 has been created

Exception.js

ns.Exception = function() {
}

/**
 * Form a string of relevant information.
 *
 * When providing this method, tools like Firebug show the returned 
 * string instead of [object Object] for uncaught exceptions.
 *
 * @return {String} information about the exception
 */
ns.Exception.prototype.toString = function() {
    var name = this.name || 'unknown';
    var message = this.message || 'no description';
    return '[' + name + '] ' + message;
};

DuplicateIdException.js

ns.DuplicateIdException = function(message) {
    this.name = 'Duplicate ID';
    this.message = message;
};

ns.DuplicateIdException.prototype = new ns.Exception();

XAMPP Start automatically on Windows 7 startup

In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:

  • open the directory where XAMPP is installed. By default it's installed at C:\xampp
  • Create Shortcut to the file xampp-control.exe, the XAMPP Control Panel
  • Paste it in

C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

or

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

The XAMPP Control Panel should now auto-start whenever you reboot Windows.

Change image size via parent div

Actually using 100% will not make the image bigger if the image is smaller than the div size you specified. You need to set one of the dimensions, height or width in order to have all images fill the space. In my experience it's better to have the height set so each row is the same size, then all items wrap to next line properly. This will produce an output similar to fotolia.com (stock image website)

with css:

parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 42px;
}

without:

<div style="height:42px;width:42px">
    <img style="height:42px" src="http://someimage.jpg">
</div>

C++ String Concatenation operator<<

You can combine strings using stream string like that:

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    string name = "Bill";
    stringstream ss;
    ss << "Your name is: " << name;
    string info = ss.str();
    cout << info << endl;
    return 0;
}

How to listen for changes to a MongoDB collection?

Since MongoDB 3.6 there will be a new notifications API called Change Streams which you can use for this. See this blog post for an example. Example from it:

cursor = client.my_db.my_collection.changes([
    {'$match': {
        'operationType': {'$in': ['insert', 'replace']}
    }},
    {'$match': {
        'newDocument.n': {'$gte': 1}
    }}
])

# Loops forever.
for change in cursor:
    print(change['newDocument'])

Drawing a simple line graph in Java

Just complementing Hovercraft Full Of Eels's solution:

I reworked his code, tweaked it a bit, adding a grid, axis labels and now the Y-axis goes from the minimum value present up to the maximum value. I planned on adding a couple of getters/setters but I didn't need them, you can add them if you want.

Here is the Gist link, I'll also paste the code below: GraphPanel on Gist

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphPanel extends JPanel {

    private int width = 800;
    private int heigth = 400;
    private int padding = 25;
    private int labelPadding = 25;
    private Color lineColor = new Color(44, 102, 230, 180);
    private Color pointColor = new Color(100, 100, 100, 180);
    private Color gridColor = new Color(200, 200, 200, 200);
    private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
    private int pointWidth = 4;
    private int numberYDivisions = 10;
    private List<Double> scores;

    public GraphPanel(List<Double> scores) {
        this.scores = scores;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1);
        double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());

        List<Point> graphPoints = new ArrayList<>();
        for (int i = 0; i < scores.size(); i++) {
            int x1 = (int) (i * xScale + padding + labelPadding);
            int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding);
            graphPoints.add(new Point(x1, y1));
        }

        // draw white background
        g2.setColor(Color.WHITE);
        g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);
        g2.setColor(Color.BLACK);

        // create hatch marks and grid lines for y axis.
        for (int i = 0; i < numberYDivisions + 1; i++) {
            int x0 = padding + labelPadding;
            int x1 = pointWidth + padding + labelPadding;
            int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
            int y1 = y0;
            if (scores.size() > 0) {
                g2.setColor(gridColor);
                g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1);
                g2.setColor(Color.BLACK);
                String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
                FontMetrics metrics = g2.getFontMetrics();
                int labelWidth = metrics.stringWidth(yLabel);
                g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
            }
            g2.drawLine(x0, y0, x1, y1);
        }

        // and for x axis
        for (int i = 0; i < scores.size(); i++) {
            if (scores.size() > 1) {
                int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding;
                int x1 = x0;
                int y0 = getHeight() - padding - labelPadding;
                int y1 = y0 - pointWidth;
                if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) {
                    g2.setColor(gridColor);
                    g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
                    g2.setColor(Color.BLACK);
                    String xLabel = i + "";
                    FontMetrics metrics = g2.getFontMetrics();
                    int labelWidth = metrics.stringWidth(xLabel);
                    g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
                }
                g2.drawLine(x0, y0, x1, y1);
            }
        }

        // create x and y axes 
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding);

        Stroke oldStroke = g2.getStroke();
        g2.setColor(lineColor);
        g2.setStroke(GRAPH_STROKE);
        for (int i = 0; i < graphPoints.size() - 1; i++) {
            int x1 = graphPoints.get(i).x;
            int y1 = graphPoints.get(i).y;
            int x2 = graphPoints.get(i + 1).x;
            int y2 = graphPoints.get(i + 1).y;
            g2.drawLine(x1, y1, x2, y2);
        }

        g2.setStroke(oldStroke);
        g2.setColor(pointColor);
        for (int i = 0; i < graphPoints.size(); i++) {
            int x = graphPoints.get(i).x - pointWidth / 2;
            int y = graphPoints.get(i).y - pointWidth / 2;
            int ovalW = pointWidth;
            int ovalH = pointWidth;
            g2.fillOval(x, y, ovalW, ovalH);
        }
    }

//    @Override
//    public Dimension getPreferredSize() {
//        return new Dimension(width, heigth);
//    }
    private double getMinScore() {
        double minScore = Double.MAX_VALUE;
        for (Double score : scores) {
            minScore = Math.min(minScore, score);
        }
        return minScore;
    }

    private double getMaxScore() {
        double maxScore = Double.MIN_VALUE;
        for (Double score : scores) {
            maxScore = Math.max(maxScore, score);
        }
        return maxScore;
    }

    public void setScores(List<Double> scores) {
        this.scores = scores;
        invalidate();
        this.repaint();
    }

    public List<Double> getScores() {
        return scores;
    }

    private static void createAndShowGui() {
        List<Double> scores = new ArrayList<>();
        Random random = new Random();
        int maxDataPoints = 40;
        int maxScore = 10;
        for (int i = 0; i < maxDataPoints; i++) {
            scores.add((double) random.nextDouble() * maxScore);
//            scores.add((double) i);
        }
        GraphPanel mainPanel = new GraphPanel(scores);
        mainPanel.setPreferredSize(new Dimension(800, 600));
        JFrame frame = new JFrame("DrawGraph");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

It looks like this: Example pic

Check if all values of array are equal

The accepted answer worked great but I wanted to add a tiny bit. It didn't work for me to use === because I was comparing arrays of arrays of objects, however throughout my app I've been using the fast-deep-equal package which I highly recommend. With that, my code looks like this:

let areAllEqual = arrs.every((val, i, arr) => equal(val, arr[0]) );

and my data looks like this:

[  
  [
    {
      "ID": 28,
      "AuthorID": 121,
      "VisitTypeID": 2
    },
    {
      "ID": 115,
      "AuthorID": 121,
      "VisitTypeID": 1
    },
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ],
  [
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ],
  [
    {
      "ID": 5,
      "AuthorID": 121,
      "VisitTypeID": 1
    },
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ]
]

Search for all files in project containing the text 'querystring' in Eclipse

press Ctrl + H . Then choose "File Search" tab.

additional search options

search for resources: Ctrl + Shift + R

search for Java types: Ctrl + Shift + T

Draw line in UIView

Add label without text and with background color corresponding frame size(ex:height=1). Do it through code or in interface builder.

Removing empty rows of a data file in R

Alternative solution for rows of NAs using janitor package

myData %>% remove_empty("rows")

Creating a new dictionary in Python

>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

Will add the value in the python dictionary.

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

Get Environment Variable from Docker Container

To view all env variables:

docker exec container env

To get one:

docker exec container env | grep VARIABLE | cut -d'=' -f2

Getting parts of a URL (Regex)

Propose a much more readable solution (in Python, but applies to any regex):

def url_path_to_dict(path):
    pattern = (r'^'
               r'((?P<schema>.+?)://)?'
               r'((?P<user>.+?)(:(?P<password>.*?))?@)?'
               r'(?P<host>.*?)'
               r'(:(?P<port>\d+?))?'
               r'(?P<path>/.*?)?'
               r'(?P<query>[?].*?)?'
               r'$'
               )
    regex = re.compile(pattern)
    m = regex.match(path)
    d = m.groupdict() if m is not None else None

    return d

def main():
    print url_path_to_dict('http://example.example.com/example/example/example.html')

Prints:

{
'host': 'example.example.com', 
'user': None, 
'path': '/example/example/example.html', 
'query': None, 
'password': None, 
'port': None, 
'schema': 'http'
}

How exactly do you configure httpOnlyCookies in ASP.NET?

With props to Rick (second comment down in the blog post mentioned), here's the MSDN article on httpOnlyCookies.

Bottom line is that you just add the following section in your system.web section in your web.config:

<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

What are the true benefits of ExpandoObject?

One advantage is for binding scenarios. Data grids and property grids will pick up the dynamic properties via the TypeDescriptor system. In addition, WPF data binding will understand dynamic properties, so WPF controls can bind to an ExpandoObject more readily than a dictionary.

Interoperability with dynamic languages, which will be expecting DLR properties rather than dictionary entries, may also be a consideration in some scenarios.

else & elif statements not working in Python

Python can generate same 'invalid syntax' error even if ident for 'elif' block not matching to 'if' block ident (tabs for the first, spaces for second or vice versa).

Git refusing to merge unrelated histories on rebase

I am using the rebase for years and I had never encountered such a problem. However, your first problem is, that you try to do it directly on the remote branch development from the remote repository, called origin. That is literally wrong because rebase is a dangerous command, that restructures the git history. Having said that, you should first try on your local repository and pushing it only, if it works for you as expected.

So, my usual rebase workflow looks like following (but please keep in mind, that you should not use rebase on branches, which you are not the only one committee. For such branches, use simply merge and resolve conflicts, if applicable):

  1. make sure you have a clean working tree (no uncommit changes)
  2. checkout to the branch you want to rebase onto (for instance, let's say it's master; as a one-line command): git checkout master && git pull origin master && git checkout development
  3. Do the actual rebase: git rebase master
  4. If it's done and everything works as expected, push it to your remote. For doing so, you need to force it, because the remote host already has the history in another order, the remote would answer with nothing to push. So, we need to say "my local version of the history is correct, overwrite everything on that remote branch using my local version of the history": git push -f origin development

As I already mentioned, keep in mind, that rebase manipulates the git history, that is usually a bad thing. However, it's possible to do that on branches, where no one else commits to. In order to keep the branch pull-able for the other developers, use another merge strategy like merge itself, squash or cherrypick. So, in other words: Rebase shouldn't be your tool on distributed development. It works fine for you if you are the only one who works on this repository.

We use the feature branch strategy. In this, I usually use rebase in order to get the "updates" from the other developers, that happened in the meantime on the master branch. Doing so, it reduces the size of commits that are visible in a pull request. Therefore, it makes it easier for the code reviewer to see my changes made in this feature branch.

How to restart service using command prompt?

You can start and stop and query services using the SC command. As for innosetup i'm not sure.

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

Adding a newline character within a cell (CSV)

I struggled with this as well but heres the solution. If you add " before and at the end of the csv string you are trying to display, it will consolidate them into 1 cell while honoring new line.

csvString += "\""+"Date Generated: \n" ; 
csvString += "Doctor: " + "\n"+"\"" + "\n"; 

Form inline inside a form horizontal in twitter bootstrap?

Since bootstrap 4 use div class="form-row" in combination with div class="form-group col-X". X is the width you need. You will get nice inline columns. See fiddle.

<form class="form-horizontal" name="FORMNAME" method="post" action="ACTION" enctype="multipart/form-data">
    <div class="form-group">
        <label class="control-label col-sm-2" for="naam">Naam:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="naam" name="Naam" placeholder="Uw naam" value="{--NAAM--}" >
            <div id="naamx" class="form-error form-hidden">Wat is uw naam?</div>
        </div>
    </div>

    <div class="form-row">

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="telefoon">Telefoon:&nbsp;*</label>
            <div class="col-sm-12">
                <input type="tel" require class="form-control" id="telefoon" name="Telefoon" placeholder="Telefoon nummer" value="{--TELEFOON--}" >
                <div id="telefoonx" class="form-error form-hidden">Wat is uw telefoonnummer?</div>
            </div>
        </div>

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="email">E-mail: </label>
            <div class="col-sm-12">
                <input type="email" require class="form-control" id="email" name="E-mail" placeholder="E-mail adres" value="{--E-MAIL--}" >
                <div id="emailx" class="form-error form-hidden">Wat is uw e-mail adres?</div>
                    </div>
                </div>

        </div>

    <div class="form-group">
        <label class="control-label col-sm-2" for="titel">Titel:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="titel" name="Titel" placeholder="Titel van uw vraag of aanbod" value="{--TITEL--}" >
            <div id="titelx" class="form-error form-hidden">Wat is de titel van uw vraag of aanbod?</div>
        </div>
    </div>
<from>

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

I was getting the same error and could not figure it out. I have a functional component exported and then imported into my App component. I set up my functional component in arrow function format, and was getting the error. I put a "return" statement inside the curly braquets, "return ()" and put all my JSX inside the parens. Hopefully this is useful to someone and not redundant. It seems stackoverflow will auto format this into a single line, however, in my editor, VSCode, it's over multiple lines. Maybe not a big deal, but want to be concise.

import React from 'react';

const Layout = (props) => {
    return (
        <>
            <div>toolbar, sidedrawer, backdrop</div>
            <main>
                {props.children}
            </main>
        </>
    );
};

export default Layout;

ASP.NET Core Identity - get current user

If you are using Bearing Token Auth, the above samples do not return an Application User.

Instead, use this:

ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);

This works in apsnetcore 2.0. Have not tried in earlier versions.

How to install ADB driver for any android device?

I have found a solution by myself. I use the PDANet tool to find the driver automatically.

http://www.junefabrics.com/android/download.php

Appending a line to a file only if it does not already exist

If, one day, someone else have to deal with this code as "legacy code", then that person will be grateful if you write a less exoteric code, such as

grep -q -F 'include "/configs/projectname.conf"' lighttpd.conf
if [ $? -ne 0 ]; then
  echo 'include "/configs/projectname.conf"' >> lighttpd.conf
fi

How to remove entry from $PATH on mac

when you login, or start a bash shell, environment variables are loaded/configured according to .bashrc, or .bash_profile. Whatever export you are doing, it's valid only for current session. so export PATH=/Applications/SenchaSDKTools-2.0.0-beta3:$PATH this command is getting executed each time you are opening a shell, you can override it, but again that's for the current session only. edit the .bashrc file to suite your need. If it's saying permission denied, perhaps the file is write-protected, a link to some other file (many organisations keep a master .bashrc file and gives each user a link of it to their home dir, you can copy the file instead of link and the start adding content to it)

check if array is empty (vba excel)

Above methods didn´t work for me. This did:

  Dim arrayIsNothing As Boolean

    On Error Resume Next
    arrayIsNothing = IsNumeric(UBound(YOUR_ARRAY)) And False
    If Err.Number <> 0 Then arrayIsNothing = True
    Err.Clear
    On Error GoTo 0

    'Now you can test:
    if arrayIsNothing then ...

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

fopen deprecated warning

Consider using a portability library like glib or the apache portable runtime. These usually provide safe, portable alternatives to calls like these. It's a good thing too, because these insecure calls are deprecated in most modern environments.

How to check whether a int is not null or empty?

An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.

Example:

int x;

// Some Code...

if (x <= 0 || x > 0){
    // What you want the code to do if x has a value
} else {
    // What you want the code to do if x has no value 
}

Disclaimer: I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.

Maintain image aspect ratio when changing height

Declare where display: flex; was given Element.
align-items: center;

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

The answers are provided here amazing, but if you are new in that and you don't realize full error then you may see at the end of that error net/http: TLS handshake timeout. message means that you have a slow internet connection. So it can be only that problem that's it. Toodles

Serializing and submitting a form with jQuery and PHP

Have you looked in firebug if POST or GET?.

check the console display.

Put in the test script:

console.log(data);

You can see the response from the server, if it shows something.

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {
     fn(results[0].geometry.location); 
  });
}

foo("address", function(location){
  alert(location); // this is where you get the return value
});

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

Add to integers in a list

Here is an example where the things to add come from a dictionary

>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
...     L[item['idx']] += item['amount']
... 
>>> L
[0, 1, 1, 0]

Here is an example adding elements from another list

>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

You could also achieve the above with a list comprehension and zip

L[:] = [sum(i) for i in zip(L, things_to_add)]

Here is an example adding from a list of tuples

>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

React won't load local images

By doing a simple import you can access the image in React

import logo from "../images/logo.png";
<img src={logo}/>

Everything solved! Just a simple fix =)

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

I've heard this doesn't always work on the designer, but it compiles fine.

Changing java platform on which netbeans runs

open etc folder in netbeans folder then edit the netbeans.conf with notepad and you will find a line like this :

Default location of JDK, can be overridden by using --jdkhome :
netbeans_jdkhome="G:\Program Files\Java\jdk1.6.0_13"

here you can set your jdk version.

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

How do I do a not equal in Django queryset filtering?

This will give your desired result.

from django.db.models import Q
results = Model.objects.exclude(Q(a=True) & ~Q(x=5))

for not equal you can use ~ on an equal query. obviously, Q can be used to reach the equal query.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

This is what then SQL2003 standard (§6.1 Data Types) says about the two:

 <exact numeric type> ::=
    NUMERIC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DECIMAL [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DEC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | SMALLINT
  | INTEGER
  | INT
  | BIGINT

 ...

21) NUMERIC specifies the data type
    exact numeric, with the decimal
    precision and scale specified by the
    <precision> and <scale>.

22) DECIMAL specifies the data type
    exact numeric, with the decimal scale
    specified by the <scale> and the
    implementation-defined decimal
    precision equal to or greater than the
    value of the specified <precision>.

Passing arguments to C# generic new() of templated type

I found that I was getting an error "cannot provide arguments when creating an instance of type parameter T" so I needed to do this:

var x = Activator.CreateInstance(typeof(T), args) as T;

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

in my case,

dev@Dev-007:~$ mysql -u root -p
Enter password: 
ERROR 1698 (28000): Access denied for user 'root'@'localhost'

I am sure my password was correct otherwise error code would be ERROR 1045 (28000): Access denied for user

so i relogin using sudo,

dev@Dev-007:~$ sudo mysql -u root -p

this time it worked for me . see the docs

and then change root password,

mysql> alter user 'root'@'%' identified with mysql_native_password by 'me123';
Query OK, 0 rows affected (0.14 sec)

mysql> 

then restart server using sudo /etc/init.d/mysql restart

How to turn on WCF tracing?

The following configuration taken from MSDN can be applied to enable tracing on your WCF service.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
             <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
        <add name="xml"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="Error.svclog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".

If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:

Windows SDK Download

You don't have to install the entire thing, just the ".NET Development / Tools" part.

When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.

Iif equivalent in C#

Also useful is the coalesce operator ??:

VB:

Return Iif( s IsNot Nothing, s, "My Default Value" )

C#:

return s ?? "My Default Value";

Can you nest html forms?

Although the question is pretty old and I agree with the @everyone that nesting of form is not allowed in HTML

But this something all might want to see this

where you can hack(I'm calling it a hack since I'm sure this ain't legitimate) html to allow browser to have nested form

<form id="form_one" action="http://apple.com">
  <div>
    <div>
        <form id="form_two" action="/">
            <!-- DUMMY FORM TO ALLOW BROWSER TO ACCEPT NESTED FORM -->
      </form>
    </div>
      <br/>
    <div>
      <form id="form_three" action="http://www.linuxtopia.org/">
          <input type='submit' value='LINUX TOPIA'/>
      </form>
    </div>
      <br/>

    <div>
      <form id="form_four" action="http://bing.com">
          <input type='submit' value='BING'/>
      </form>
    </div>
      <br/>  
    <input type='submit' value='Apple'/>
  </div>  
</form>

JS FIDDLE LINK

http://jsfiddle.net/nzkEw/10/

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"