Programs & Examples On #Gwt2

GWT is an open source and free framework made by Google.

How to force open links in Chrome not download them?

Just found your question whilst trying to solve another problem I'm having, you will find that currently Google isn't able to perform a temporary download so therefore you have to download instead.

See: http://productforums.google.com/forum/#!topic/chrome/Drge_Zrwg-c

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Look. This is way old, but on the off chance that someone from Google finds this, absolutely the best solution to this - (and it is AWESOME) - is to use ConEmu (or a package that includes and is built on top of ConEmu called cmder) and then either use plink or putty itself to connect to a specific machine, or, even better, set up a development environment as a local VM using Vagrant.

This is the only way I can ever see myself developing from a Windows box again.

I am confident enough to say that every other answer - while not necessarily bad answers - offer garbage solutions compared to this.

Update: As Of 1/8/2020 not all other solutions are garbage - Windows Terminal is getting there and WSL exists.

Invalid syntax when using "print"?

The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")

check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:

$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...

As an alias:

$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...

Please note that I control my Python version via conda environments, because of that I can use python instead of python3 for using Python 3.

HTML5 Video tag not working in Safari , iPhone and iPad

As of iOS 6.1, it is no longer possible to auto-play videos on the iPad. According to Apple documentation Autoplay feature is not working on Safari in all ios devices including iPad:

"Apple has made the decision to disable the automatic playing of video on iOS devices, through both script and attribute implementations.

In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and auto-play are disabled. No data is loaded until the user initiates it."

You can read more abut it in this Apple documentation

Multiple HttpPost method in Web API controller

You can have multiple actions in a single controller.

For that you have to do the following two things.

  • First decorate actions with ActionName attribute like

     [ActionName("route")]
     public class VTRoutingController : ApiController
     {
       [ActionName("route")]
       public MyResult PostRoute(MyRequestTemplate routingRequestTemplate)
       {
         return null;
       }
    
      [ActionName("tspRoute")]
      public MyResult PostTSPRoute(MyRequestTemplate routingRequestTemplate)
      {
         return null;
      }
    }
    
  • Second define the following routes in WebApiConfig file.

    // Controller Only
    // To handle routes like `/api/VTRouting`
    config.Routes.MapHttpRoute(
        name: "ControllerOnly",
        routeTemplate: "api/{controller}"               
    );
    
    
    // Controller with ID
    // To handle routes like `/api/VTRouting/1`
    config.Routes.MapHttpRoute(
        name: "ControllerAndId",
        routeTemplate: "api/{controller}/{id}",
        defaults: null,
        constraints: new { id = @"^\d+$" } // Only integers 
    );
    
    // Controllers with Actions
    // To handle routes like `/api/VTRouting/route`
    config.Routes.MapHttpRoute(
        name: "ControllerAndAction",
        routeTemplate: "api/{controller}/{action}"
    );
    

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

By default, Elasticsearch installed goes into read-only mode when you have less than 5% of free disk space. If you see errors similar to this:

Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"error":{"root_cause":[{"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"}],"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"},"status":403}

Or in /usr/local/var/log/elasticsearch.log you can see logs similar to:

flood stage disk watermark [95%] exceeded on [nCxquc7PTxKvs6hLkfonvg][nCxquc7][/usr/local/var/lib/elasticsearch/nodes/0] free: 15.3gb[4.1%], all indices on this node will be marked read-only

Then you can fix it by running the following commands:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

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).

Extract a page from a pdf as a jpeg

Their is a utility called pdftojpg which can be used to convert the pdf to img

You can found the code here https://github.com/pankajr141/pdf2jpg

from pdf2jpg import pdf2jpg
inputpath = r"D:\inputdir\pdf1.pdf"
outputpath = r"D:\outputdir"
# To convert single page
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="1")
print(result)

# To convert multiple pages
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="1,0,3")
print(result)

# to convert all pages
result = pdf2jpg.convert_pdf2jpg(inputpath, outputpath, pages="ALL")
print(result)

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

SQL Query with Join, Count and Where

You have to use GROUP BY so you will have multiple records returned,

SELECT  COUNT(*) TotalCount, 
        b.category_id, 
        b.category_name 
FROM    table1 a
        INNER JOIN table2 b
            ON a.category_id = b.category_id 
WHERE   a.colour <> 'red'
GROUP   BY b.category_id, b.category_name

What is a callback in java

A callback is commonly used in asynchronous programming, so you could create a method which handles the response from a web service. When you call the web service, you could pass the method to it so that when the web service responds, it call's the method you told it ... it "calls back".

In Java this can commonly be done through implementing an interface and passing an object (or an anonymous inner class) that implements it. You find this often with transactions and threading - such as the Futures API.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html

How to send email by using javascript or jquery

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Simple PHP mail script

Using a script like that, you'd POST the contents of your web form to the script, using a function like this:

jQuery.post

And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.

Why does adb return offline after the device string?

  1. make sure the device is set for usb debugging
  2. Have the adb client running (e.g. via "adb usb" or adb start-server"
  3. LEAVE the device connected via usb!!!
  4. AND THEN reboot the device.

This always brings my Motorola MB525 "online" again, after adb complains it would be "offline". I'm using OSX btw.

Get last field using awk substr

I know I'm like 3 years late on this but.... you should consider parameter expansion, it's built-in and faster.

if your input is in a var, let's say, $var1, just do ${var1##*/}. Look below

$ var1='/home/parent/child1/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/child3/filename'
$ echo ${var1##*/}
filename

Choose newline character in Notepad++

on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF) or Unix(LF)

Differences between JDK and Java SDK

I think jdk has certain features which can be used along with particular framework. Well call it SDK as a whole.

Like Android or Blackberry both use java along with their framework.

Python Pandas : pivot table with aggfunc = count unique distinct

Since at least version 0.16 of pandas, it does not take the parameter "rows"

As of 0.23, the solution would be:

df2.pivot_table(values='X', index='Y', columns='Z', aggfunc=pd.Series.nunique)

which returns:

Z    Z1   Z2   Z3
Y                
Y1  1.0  1.0  NaN
Y2  NaN  NaN  1.0

Use multiple @font-face rules in CSS

@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Thin.otf);
    font-weight: 200;
}
@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Light.otf);
    font-weight: 300;
}
@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Regular.otf);
    font-weight: normal;
}
@font-face {
    font-family: Kaffeesatz;
    src: url(YanoneKaffeesatz-Bold.otf);
    font-weight: bold;
}
h3, h4, h5, h6 {
    font-size:2em;
    margin:0;
    padding:0;
    font-family:Kaffeesatz;
    font-weight:normal;
}
h6 { font-weight:200; }
h5 { font-weight:300; }
h4 { font-weight:normal; }
h3 { font-weight:bold; }

Compare two DataFrames and output their differences side-by-side

Highlighting the difference between two DataFrames

It is possible to use the DataFrame style property to highlight the background color of the cells where there is a difference.

Using the example data from the original question

The first step is to concatenate the DataFrames horizontally with the concat function and distinguish each frame with the keys parameter:

df_all = pd.concat([df.set_index('id'), df2.set_index('id')], 
                   axis='columns', keys=['First', 'Second'])
df_all

enter image description here

It's probably easier to swap the column levels and put the same column names next to each other:

df_final = df_all.swaplevel(axis='columns')[df.columns[1:]]
df_final

enter image description here

Now, its much easier to spot the differences in the frames. But, we can go further and use the style property to highlight the cells that are different. We define a custom function to do this which you can see in this part of the documentation.

def highlight_diff(data, color='yellow'):
    attr = 'background-color: {}'.format(color)
    other = data.xs('First', axis='columns', level=-1)
    return pd.DataFrame(np.where(data.ne(other, level=0), attr, ''),
                        index=data.index, columns=data.columns)

df_final.style.apply(highlight_diff, axis=None)

enter image description here

This will highlight cells that both have missing values. You can either fill them or provide extra logic so that they don't get highlighted.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.

TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

How do I get a value of a <span> using jQuery?

You could use id in span directly in your html.

<span id="span_id">Client</span>

Then your jQuery code would be

$("#span_id").text();

Some one helped me to check errors and found that he used val() instead of text(), it is not possible to use val() function in span. So

$("#span_id").val();

will return null.

Converting <br /> into a new line for use in a text area

<?php

$var1 = "Line 1 info blah blah <br /> Line 2 info blah blah";
$var1 = str_replace("<br />", "\n", $var1);

?>

<textarea><?php echo $var1; ?></textarea>

How can I get the Google cache age of any URL or web page?

This one good also to view cachepage http://www.cachepage.net

  1. Cache page view via google: webcache.googleusercontent.com/search?q=cache: Your url

  2. Cache page view via archive.org: web.archive.org/web/*/Your url

Table and Index size in SQL Server

It’s been a long time since the creation of this post, but I wanted to share my script:

WITH CteIndex
AS
(
SELECT 
     reservedpages = (reserved_page_count)
     ,usedpages = (used_page_count)
     ,pages = (
            CASE
                WHEN (s.index_id < 2) THEN (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                ELSE lob_used_page_count + row_overflow_used_page_count
            END
            )    
     ,s.object_id   
     ,i.index_id        
     ,i.type_desc AS IndexType
     ,i.name AS indexname
    FROM sys.dm_db_partition_stats s
    INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id   
)
SELECT DISTINCT
DB_NAME(DB_ID()) AS DatabaseName
,o.name AS TableName
,o.object_id
,ct.indexname
,ct.IndexType
,ct.index_id
, IndexSpace = LTRIM (STR ((CASE WHEN usedpages > pages THEN CASE WHEN ct.index_id < 2 THEN  pages ELSE (usedpages - pages) END ELSE 0 END) * 8, 15, 0) + ' KB')
FROM CteIndex ct
INNER JOIN sys.objects o ON o.object_id = ct.object_id
INNER JOIN sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL , NULL) ps ON ps.object_id = o.object_id
AND ps.index_id = ct.index_id
ORDER BY name ASC

This works for :

  • SQL Server (starting with 2008)
  • Includes info for all tables per current database

unix - count of columns in file

This is a workaround (for me: I don't use awk very often):

Display the first row of the file containing the data, replace all pipes with newlines and then count the lines:

$ head -1 stores.dat | tr '|' '\n' | wc -l

Datatables on-the-fly resizing

I got this to work as follows:

First ensure that in your dataTable definition your aoColumns array includes sWidth data expressed as a % not fixed pixels or ems. Then ensure you have set the bAutoWidth property to false Then add this little but of JS:

update_table_size = function(a_datatable) {
  if (a_datatable == null) return;
  var dtb;
  if (typeof a_datatable === 'string') dtb = $(a_datatable)
  else dtb = a_datatable;
  if (dtb == null) return;

  dtb.css('width', dtb.parent().width());
  dtb.fnAdjustColumSizing();
}

$(window).resize(function() {
  setTimeout(function(){update_table_size(some_table_selector_or_table_ref)}, 250);
});

Works a treat and my table cells handle the white-space: wrap; CSS (which wasn't working without setting the sWidth, and was what led me to this question.)

Disable Proximity Sensor during call

edit build.prop in folder /system if below line is exist change the value and if not exist add this line and save.(device must be rooted)

ro.lge.proximity.delay=25
mot.proximity.delay=25  

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

A full outer join combines a left outer join and a right outer join. The result set returns rows from both tables where the conditions are met but returns null columns where there is no match.

A cross join is a Cartesian product that does not require any condition to join tables. The result set contains rows and columns that are a multiplication of both tables.

How to print to console in pytest?

According to the pytest docs, pytest --capture=sys should work. If you want to capture standard out inside a test, refer to the capsys fixture.

Difference between logical addresses, and physical addresses?

Logical Vs Physical Address space

An address generated by the CPU is commonly refereed as Logical Address,whereas the address seen by the memory unit,that is one loaded into the memory address register of the memory is commonly refereed as the Physical Address.The compile time and load time address binding generates the identical logical and physical addresses.However, the execution time address binding scheme results in differing logical and physical addresses.

The set of all logical addresses generated by a program is known as Logical Address Space,whereas the set of all physical addresses corresponding to these logical addresses is Physical Address Space.Now, the run time mapping from virtual address to physical address is done by a hardware device known as Memory Management Unit.Here in the case of mapping the base register is known as relocation register.The value in the relocation register is added to the address generated by a user process at the time it is sent to memory.Let's understand this situation with the help of example:If the base register contains the value 1000,then an attempt by the user to address location 0 is dynamically relocated to location 1000,an access to location 346 is mapped to location 1346.

The user program never sees the real physical address space,it always deals with the Logical addresses.As we have two different type of addresses Logical address in the range (0 to max) and Physical addresses in the range(R to R+max) where R is the value of relocation register.The user generates only logical addresses and thinks that the process runs in location to 0 to max.As it is clear from the above text that user program supplies only logical addresses,these logical addresses must be mapped to physical address before they are used.

Getting result of dynamic SQL into a variable for sql-server

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
declare @counts int
SET @city = 'New York'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75),@cnt int OUTPUT', @city = @city, @cnt=@counts OUTPUT
select @counts as Counts

What is the difference between compileSdkVersion and targetSdkVersion?

I see a lot of differences about compiledSdkVersion in previous answers, so I'll try to clarify a bit here, following android's web page.

A - What Android says

According https://developer.android.com/guide/topics/manifest/uses-sdk-element.html:

Selecting a platform version and API Level When you are developing your application, you will need to choose the platform version against which you will compile the application. In general, you should compile your application against the lowest possible version of the platform that your application can support.

So, this would be the right order according to Android:

compiledSdkVersion = minSdkVersion <= targetSdkVersion

B - What others also say

Some people prefer to always use the highest compiledSkdVersion available. It is because they will rely on code hints to check if they are using newer API features than minSdkVersion, thus either changing the code to not use them or checking the user API version at runtime to conditionally use them with fallbacks for older API versions.

Hints about deprecated uses would also appear in code, letting you know that something is deprecated in newer API levels, so you can react accordingly if you wish.

So, this would be the right order according to others:

minSdkVersion <= targetSdkVersion <= compiledSdkVersion (highest possible)

What to do?

It depends on you and your app.

If you plan to offer different API features according to the API level of the user at runtime, use option B. You'll get hints about the features you use while coding. Just make sure you never use newer API features than minSdkVersion without checking user API level at runtime, otherwise your app will crash. This approach also has the benefit of learning what's new and what's old while coding.

If you already know what's new or old and you are developing a one time app that for sure will never be updated, or you are sure you are not going to offer new API features conditionally, then use option A. You won't get bothered with deprecated hints and you will never be able to use newer API features even if you're tempted to do it.

How to download and save an image in Android

I have a simple solution which is working perfectly. The code is not mine, I found it on this link. Here are the steps to follow:

1. Before downloading the image, let’s write a method for saving bitmap into an image file in the internal storage in android. It needs a context, better to use the pass in the application context by getApplicationContext(). This method can be dumped into your Activity class or other util classes.

public void saveImage(Context context, Bitmap b, String imageName) 
{
    FileOutputStream foStream;
    try 
    {
        foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
        b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
        foStream.close();
    } 
    catch (Exception e) 
    {
        Log.d("saveImage", "Exception 2, Something went wrong!");
        e.printStackTrace();
    }
}

2. Now we have a method to save bitmap into an image file in andorid, let’s write the AsyncTask for downloading images by url. This private class need to be placed in your Activity class as a subclass. After the image is downloaded, in the onPostExecute method, it calls the saveImage method defined above to save the image. Note, the image name is hardcoded as “my_image.png”.

private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    private String TAG = "DownloadImage";
    private Bitmap downloadImageBitmap(String sUrl) {
        Bitmap bitmap = null;
        try {
            InputStream inputStream = new URL(sUrl).openStream();   // Download Image from URL
            bitmap = BitmapFactory.decodeStream(inputStream);       // Decode Bitmap
            inputStream.close();
        } catch (Exception e) {
            Log.d(TAG, "Exception 1, Something went wrong!");
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        return downloadImageBitmap(params[0]);
    }

    protected void onPostExecute(Bitmap result) {
        saveImage(getApplicationContext(), result, "my_image.png");
    }
}

3. The AsyncTask for downloading the image is defined, but we need to execute it in order to run that AsyncTask. To do so, write this line in your onCreate method in your Activity class, or in an onClick method of a button or other places you see fit.

new DownloadImage().execute("http://developer.android.com/images/activity_lifecycle.png");

The image should be saved in /data/data/your.app.packagename/files/my_image.jpeg, check this post for accessing this directory from your device.

IMO this solves the issue! If you want further steps such as load the image you can follow these extra steps:

4. After the image is downloaded, we need a way to load the image bitmap from the internal storage, so we can use it. Let’s write the method for loading the image bitmap. This method takes two paramethers, a context and an image file name, without the full path, the context.openFileInput(imageName) will look up the file at the save directory when this file name was saved in the above saveImage method.

public Bitmap loadImageBitmap(Context context, String imageName) {
    Bitmap bitmap = null;
    FileInputStream fiStream;
    try {
        fiStream    = context.openFileInput(imageName);
        bitmap      = BitmapFactory.decodeStream(fiStream);
        fiStream.close();
    } catch (Exception e) {
        Log.d("saveImage", "Exception 3, Something went wrong!");
        e.printStackTrace();
    }
    return bitmap;
}

5. Now we have everything we needed for setting the image of an ImageView or any other Views that you like to use the image on. When we save the image, we hardcoded the image name as “my_image.jpeg”, now we can pass this image name to the above loadImageBitmap method to get the bitmap and set it to an ImageView.

someImageView.setImageBitmap(loadImageBitmap(getApplicationContext(), "my_image.jpeg"));

6. To get the image full path by image name.

File file            = getApplicationContext().getFileStreamPath("my_image.jpeg");
String imageFullPath = file.getAbsolutePath();

7. Check if the image file exists.

File file =

getApplicationContext().getFileStreamPath("my_image.jpeg");
if (file.exists()) Log.d("file", "my_image.jpeg exists!");
  1. To delete the image file.

    File file = getApplicationContext().getFileStreamPath("my_image.jpeg"); if (file.delete()) Log.d("file", "my_image.jpeg deleted!");

Fragment MyFragment not attached to Activity

I faced similar issues when the application settings activity with the loaded preferences was visible. If I would change one of the preferences and then make the display content rotate and change the preference again, it would crash with a message that the fragment (my Preferences class) was not attached to an activity.

When debugging it looked like the onCreate() Method of the PreferencesFragment was being called twice when the display content rotated. That was strange enough already. Then I added the isAdded() check outside of the block where it would indicate the crash and it solved the issue.

Here is the code of the listener that updates the preferences summary to show the new entry. It is located in the onCreate() method of my Preferences class which extends the PreferenceFragment class:

public static class Preferences extends PreferenceFragment {
    SharedPreferences.OnSharedPreferenceChangeListener listener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ...
        listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                // check if the fragment has been added to the activity yet (necessary to avoid crashes)
                if (isAdded()) {
                    // for the preferences of type "list" set the summary to be the entry of the selected item
                    if (key.equals(getString(R.string.pref_fileviewer_textsize))) {
                        ListPreference listPref = (ListPreference) findPreference(key);
                        listPref.setSummary("Display file content with a text size of " + listPref.getEntry());
                    } else if (key.equals(getString(R.string.pref_fileviewer_segmentsize))) {
                        ListPreference listPref = (ListPreference) findPreference(key);
                        listPref.setSummary("Show " + listPref.getEntry() + " bytes of a file at once");
                    }
                }
            }
        };
        // ...
    }

I hope this will help others!

Delete the first three rows of a dataframe in pandas

I think a more explicit way of doing this is to use drop.

The syntax is:

df.drop(label)

And as pointed out by @tim and @ChaimG, this can be done in-place:

df.drop(label, inplace=True)

One way of implementing this could be:

df.drop(df.index[:3], inplace=True)

And another "in place" use:

df.drop(df.head(3).index, inplace=True)

Deep copy in ES6 using the spread syntax

Here's my deep copy algorithm.

const DeepClone = (obj) => {
     if(obj===null||typeof(obj)!=='object')return null;
    let newObj = { ...obj };

    for (let prop in obj) {
      if (
        typeof obj[prop] === "object" ||
        typeof obj[prop] === "function"
      ) {
        newObj[prop] = DeepClone(obj[prop]);
      }
    }

    return newObj;
  };

Reading values from DataTable

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
    QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
    //Similarly for QuantityInIssueUnit_uom.
}

Find all tables containing column with specified name - MS SQL Server

In MS SQL, you can write the below line to check the column names of a particular table:

sp_help your_tablename

Or, you can first select your table name in the query windows (highlight the schema and table name) and then press key combination below:

Alt + F1

How to get all of the immediate subdirectories in Python

import os, os.path

To get (full-path) immediate sub-directories in a directory:

def SubDirPath (d):
    return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])

To get the latest (newest) sub-directory:

def LatestDirectory (d):
    return max(SubDirPath(d), key=os.path.getmtime)

Get size of folder or file

In Java 8:

long size = Files.walk(path).mapToLong( p -> p.toFile().length() ).sum();

It would be nicer to use Files::size in the map step but it throws a checked exception.

UPDATE:
You should also be aware that this can throw an exception if some of the files/folders are not accessible. See this question and another solution using Guava.

How to get main div container to align to centre?

The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:

body {
     margin: 0;
     padding: 0;
     text-align: center;
}
#main_container {
     margin: 0 auto;
     text-align: left;
}

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

Reading Excel files from C#

Just did a quick demo project that required managing some excel files. The .NET component from GemBox software was adequate for my needs. It has a free version with a few limitations.

http://www.gemboxsoftware.com/GBSpreadsheet.htm

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Convert Pixels to Points

System.Drawing.Graphics has DpiX and DpiY properties. DpiX is pixels per inch horizontally. DpiY is pixels per inch vertically. Use those to convert from points (72 points per inch) to pixels.

Ex: 14 horizontal points = (14 * DpiX) / 72 pixels

Why is volatile needed in C?

Volatile tells the compiler not to optimize anything that has to do with the volatile variable.

There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there's another thread running that also uses the variable; or when there's a signal handler that might change the value of the variable.

Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:

typedef struct
{
  int command;
  int data;
  int isbusy;
} MyHardwareGadget;

Now you want to send some command:

void SendCommand (MyHardwareGadget * gadget, int command, int data)
{
  // wait while the gadget is busy:
  while (gadget->isbusy)
  {
    // do nothing here.
  }
  // set data first:
  gadget->data    = data;
  // writing the command starts the action:
  gadget->command = command;
}

Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of isbusy just once and then go into an infinite loop. That's not what you want.

The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either:

This is the correct version:

   void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
    {
      // wait while the gadget is busy:
      while (gadget->isbusy)
      {
        // do nothing here.
      }
      // set data first:
      gadget->data    = data;
      // writing the command starts the action:
      gadget->command = command;
    }

How do I get logs/details of ansible-playbook module executions?

Ansible command-line help, such as ansible-playbook --help shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.

Echo newline in Bash prints literal \n

This could better be done as

x="\n"
echo -ne $x

-e option will interpret backslahes for the escape sequence
-n option will remove the trailing newline in the output

PS: the command echo has an effect of always including a trailing newline in the output so -n is required to turn that thing off (and make it less confusing)

Access maven properties defined in the pom

You can parse the pom file with JDOM (http://www.jdom.org/).

Find a string by searching all tables in SQL Server Management Studio 2008

This was very helpful. I wanted to import this function to a Postgre SQL database. Thought i would share it with anyone who is interested. Will have them a few hours. Note: this function creates a list of SQL statements that can be copied and executed on the Postgre database. Maybe someone smarter then me can get Postgre to create and execute the statements all in one function.

CREATE OR REPLACE FUNCTION SearchAllTables(_search text) RETURNS TABLE( txt text ) as $funct$
    DECLARE __COUNT int;
    __SQL text;
BEGIN
    EXECUTE 'SELECT COUNT(0) FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE    DATA_TYPE = ''text'' 
                    AND          table_schema = ''public'' ' INTO __COUNT;

    RETURN QUERY 
        SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY table_name) < __COUNT THEN 
            'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "'  || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search  || '%'' UNION ALL' 
            ELSE 
            'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "'  || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search  || '%'''
        END AS txt

                    FROM     INFORMATION_SCHEMA.COLUMNS
                    WHERE    DATA_TYPE = 'text' 
                    AND          table_schema = 'public';
END
$funct$ LANGUAGE plpgsql;

How to check if a specified key exists in a given S3 bucket using Java

Break your path into bucket and object. Testing the bucket using the method doesBucketExist, Testing the object using the size of the listing (0 in case not exist). So this code will do:

String bucket = ...;
String objectInBucket = ...;
AmazonS3 s3 = new AmazonS3Client(...);
return s3.doesBucketExist(bucket) 
       && !s3.listObjects(bucket, objectInBucket).getObjectSummaries().isEmpty();

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

Defining a HTML template to append using JQuery

Add somewhere in body

<div class="hide">
<a href="#" class="list-group-item">
    <table>
        <tr>
            <td><img src=""></td>
            <td><p class="list-group-item-text"></p></td>
        </tr>
    </table>
</a>
</div>

then create css

.hide { display: none; }

and add to your js

$('#output').append( $('.hide').html() );

MySQL - SELECT * INTO OUTFILE LOCAL ?

The path you give to LOAD DATA INFILE is for the filesystem on the machine where the server is running, not the machine you connect from. LOAD DATA LOCAL INFILE is for the client's machine, but it requires that the server was started with the right settings, otherwise it's not allowed. You can read all about it here: http://dev.mysql.com/doc/refman/5.0/en/load-data-local.html

As for SELECT INTO OUTFILE I'm not sure why there is not a local version, besides it probably being tricky to do over the connection. You can get the same functionality through the mysqldump tool, but not through sending SQL to the server.

create table in postgreSQL

First the bigint(20) not null auto_increment will not work, simply use bigserial primary key. Then datetime is timestamp in PostgreSQL. All in all:

CREATE TABLE article (
    article_id bigserial primary key,
    article_name varchar(20) NOT NULL,
    article_desc text NOT NULL,
    date_added timestamp default NULL
);

How can I check if a var is a string in JavaScript?

Combining the previous answers provides these solutions:

if (typeof str == 'string' || str instanceof String)

or

Object.prototype.toString.call(str) == '[object String]'

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

First, the possible values for the hbm2ddl configuration property are the following ones:

  • none - No action is performed. The schema will not be generated.
  • create-only - The database schema will be generated.
  • drop - The database schema will be dropped.
  • create - The database schema will be dropped and created afterward.
  • create-drop - The database schema will be dropped and created afterward. Upon closing the SessionFactory, the database schema will be dropped.
  • validate - The database schema will be validated using the entity mappings.
  • update - The database schema will be updated by comparing the existing database schema with the entity mappings.

The hibernate.hbm2ddl.auto="update" is convenient but less flexible if you plan on adding functions or executing some custom scripts.

So, The most flexible approach is to use Flyway.

However, even if you use Flyway, you can still generate the initial migration script using hbm2ddl.

How can I open a website in my web browser using Python?

From the doc.

The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.

You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.

To open in new tab:

import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)

Also from the doc.

If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible

So according to the value of new, you can either open page in same browser window or in new tab etc.

Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.

What does the "@" symbol do in SQL?

@ is used as a prefix denoting stored procedure and function parameter names, and also variable names

The developers of this app have not set up this app properly for Facebook Login?

after a lot of tries, I've read in other topics which someone said "delete all your apps and create it again". I did that but, as you can imagine, a new App will create a new Application ID on Facebook's page.

So, even after all the "set public things" it didn't work because the application ID was wrong in my code due to the creation of a new App on Facebook developer page.

So, as AndrewSmiley said above, you should remeber to update that in your app @strings

How can I add a custom HTTP header to ajax request with js or jQuery?

You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});

How to make --no-ri --no-rdoc the default for gem install?

A oneliner for the windows 7 users:

(echo install: --no-document && echo update: --no-document) >> c:\ProgramData\gemrc

Accessing certain pixel RGB value in openCV

uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values 
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{

        if (r > 2) r = 0;

        if (r == 0) value[i] = 0;
        if (r == 1)value[i] =  0;
        if (r == 2)value[i] = 255;

        r++;
}

Bind TextBox on Enter-key press

Here is an approach that to me seems quite straightforward, and easier that adding an AttachedBehaviour (which is also a valid solution). We use the default UpdateSourceTrigger (LostFocus for TextBox), and then add an InputBinding to the Enter Key, bound to a command.

The xaml is as follows

       <TextBox Grid.Row="0" Text="{Binding Txt1}" Height="30" Width="150">
        <TextBox.InputBindings>
            <KeyBinding Gesture="Enter" 
                        Command="{Binding UpdateText1Command}"
                        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type TextBox}},Path=Text}" />
        </TextBox.InputBindings>
    </TextBox>

Then the Command methods are

Private Function CanExecuteUpdateText1(ByVal param As Object) As Boolean
    Return True
End Function
Private Sub ExecuteUpdateText1(ByVal param As Object)

    If TypeOf param Is String Then
        Txt1 = CType(param, String)
    End If
End Sub

And the TextBox is bound to the Property

 Public Property Txt1 As String
    Get
        Return _txt1
    End Get
    Set(value As String)
        _txt1 = value
        OnPropertyChanged("Txt1")
    End Set
End Property

So far this seems to work well and catches the Enter Key event in the TextBox.

How to create streams from string in Node.Js?

Heres a tidy solution in TypeScript:

import { Readable } from 'stream'

class ReadableString extends Readable {
    private sent = false

    constructor(
        private str: string
    ) {
        super();
    }

    _read() {
        if (!this.sent) {
            this.push(Buffer.from(this.str));
            this.sent = true
        }
        else {
            this.push(null)
        }
    }
}

const stringStream = new ReadableString('string to be streamed...')

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

declare @T int

set @T = 10455836
--set @T = 421151

select (@T / 1000000) % 100 as hour,
       (@T / 10000) % 100 as minute,
       (@T / 100) % 100 as second,
       (@T % 100) * 10 as millisecond

select dateadd(hour, (@T / 1000000) % 100,
       dateadd(minute, (@T / 10000) % 100,
       dateadd(second, (@T / 100) % 100,
       dateadd(millisecond, (@T % 100) * 10, cast('00:00:00' as time(2))))))  

Result:

hour        minute      second      millisecond
----------- ----------- ----------- -----------
10          45          58          360

(1 row(s) affected)


----------------
10:45:58.36

(1 row(s) affected)

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

IntelliJ - Convert a Java project/module into a Maven project/module

Right-click on the module, select "Add framework support...", and check the "Maven" technology.

(This also creates a pom.xml for you to modify.)

If you mean adding source repository elements, I think you need to do that manually–not sure.

Pre-IntelliJ 13 this won't convert the project to the Maven Standard Directory Layout, 13+ it will.

How do I check my gcc C++ compiler version for my Eclipse?

The answer is:

gcc --version

Rather than searching on forums, for any possible option you can always type:

gcc --help

haha! :)

How do I check if I'm running on Windows in Python?

You should be able to rely on os.name.

import os
if os.name == 'nt':
    # ...

edit: Now I'd say the clearest way to do this is via the platform module, as per the other answer.

Default Activity not found in Android Studio

I had the same problem while importing a project into Android Studio, probably caused by the fact that the project has been developed on an earlier version of Android Studio than currently installed on my computer.

What solved it was simply choosing:

File -> Invalidate Caches / Restart...

and then selecting Invalidate and Restart.

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

How do I set Java's min and max heap size through environment variables?

You can use JAVA_TOOL_OPTIONS.

Example:

export JAVA_TOOL_OPTIONS=-Xmx512m

It has been mentioned in some comments, and in another answer.

The OP's question is quite old, but as it is the first google result for the question, I thought i would add the answer here for clarity's sake.

Date formatting in WPF datagrid

This is a very old question, but I found a new solution, so I wrote about it.

First of all, is this way of solution possible while using AutoGenerateColumns?

Yes, that can be done with AttachedProperty as follows.

<DataGrid AutoGenerateColumns="True" 
   local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
   ItemsSource="{Binding}" />

AttachedProperty

There are two AttachedProperty defined that allow you to specify two formats. DateTimeFormatAutoGenerate for DateTime and TimeSpanFormatAutoGenerate for TimeSpan.

class DataGridOperation
{
    public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
    public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));

    public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
    public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));

    private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is DataGrid dGrid))
            return;

        if ((e.NewValue is string format))
            dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
    }

    private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
    {
        if (e.PropertyType == typeof(T))
            (e.Column as DataGridTextColumn).Binding.StringFormat = format;
    }
}

How to use

View

<Window
   x:Class="DataGridAutogenerateCustom.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:DataGridAutogenerateCustom"
   Width="400" Height="250">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <StackPanel>
      <TextBlock Text="DEFAULT FORMAT" />
      <DataGrid ItemsSource="{Binding Dates}" />

      <TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
      <DataGrid
         local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
         local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
         ItemsSource="{Binding Dates}" />
   </StackPanel>
</Window>

ViewModel

public class MainWindowViewModel
{
    public DatePairs[] Dates { get; } = new DatePairs[]
    {
        new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
        new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
    };
}

public class DatePairs
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan Span => EndDate - StartDate;
}

demo_wpf_datagrid

JavaScript - Use variable in string match

Example. To find number of vowels within the string

var word='Web Development Tutorial';
var vowels='[aeiou]'; 
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);

How to convert 'binary string' to normal string in Python3?

Please, see oficial encode() and decode() documentation from codecs library. utf-8 is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1 or utf_32.

How many bytes does one Unicode character take?

Well I just pulled up the Wikipedia page on it too, and in the intro portion I saw "Unicode can be implemented by different character encodings. The most commonly used encodings are UTF-8 (which uses one byte for any ASCII characters, which have the same code values in both UTF-8 and ASCII encoding, and up to four bytes for other characters), the now-obsolete UCS-2 (which uses two bytes for each character but cannot encode every character in the current Unicode standard)"

As this quote demonstrates, your problem is that you are assuming Unicode is a single way of encoding characters. There are actually multiple forms of Unicode, and, again in that quote, one of them even has 1 byte per character just like what you are used to.

So your simple answer that you want is that it varies.

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

How can I declare enums using java

public enum MyEnum
{
    ONE(1),
    TWO(2);

    private int value;

    private MyEnum(int val){
        value = val;
    }

    public int getValue(){
        return value;
    }
}

Comprehensive methods of viewing memory usage on Solaris

Top can be compiled from sources or downloaded from sunfreeware.com. As previously posted, vmstat is available (I believe it's in the core install?).

draw diagonal lines in div background with CSS

I needed to draw arbitrary diagonal lines inside any div. My issue with the other answers posted is that none of them allowed to draw an arbitrary line from point A to point B without doing the trigonometry yourself for the angles. With javascript & CSS you can do this. Hope it's helpful, just specify a pair of points and you're golden.

_x000D_
_x000D_
const objToStyleString = (obj) => {_x000D_
  const reducer = (acc, curr) => acc += curr + ": " + obj[curr] + ";"; _x000D_
  return Object.keys(obj).reduce(reducer, "")_x000D_
};_x000D_
_x000D_
const lineStyle = (xy1, xy2, borderStyle) => {_x000D_
  const p1 = {x: xy1[0], y: xy1[1]};_x000D_
  const p2 = {x: xy2[0], y: xy2[1]};_x000D_
  _x000D_
  const a = p2.x - p1.x;_x000D_
  const xOffset = p1.x;_x000D_
  const b = p2.y - p1.y;_x000D_
  const yOffset = p1.y;_x000D_
  _x000D_
  const c = Math.sqrt(a*a + b*b);_x000D_
  _x000D_
  const ang = Math.acos(a/c);_x000D_
  _x000D_
  const tX1 = `translateX(${-c/2 + xOffset}px) `;_x000D_
  const tY1 = `translateY(${yOffset}px) `;_x000D_
  const rot = `rotate(${ang}rad) `;_x000D_
  const tX2 = `translateX(${c/2}px) `;_x000D_
  const tY2 = `translateY(${0}px) `;_x000D_
  _x000D_
  return {_x000D_
    "width": Math.floor(c) + "px",_x000D_
    "height": "0px",_x000D_
    "border-top": borderStyle,_x000D_
    "-webkit-transform": tX1+tY1+rot+tX2+tY2,_x000D_
    "position": "relative",_x000D_
    "top": "0px",_x000D_
    "left": "0px",_x000D_
    "box-sizing": "border-box",_x000D_
  };_x000D_
};_x000D_
_x000D_
function drawLine(parent, p1, p2, borderStyle) {_x000D_
  const style = lineStyle(p1, p2, borderStyle);_x000D_
  const line = document.createElement("div");_x000D_
  line.style = objToStyleString(style);_x000D_
  parent.appendChild(line);_x000D_
}_x000D_
_x000D_
drawLine(container, [100,5], [25,195], "1px dashed purple");_x000D_
drawLine(container, [100,100], [190,190], "1px solid blue");_x000D_
drawLine(container, [25,150], [175,150], "2px solid red");_x000D_
drawLine(container, [25,10], [175,20], "5px dotted green");
_x000D_
#container {_x000D_
  background-color: #BCBCBC;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0; _x000D_
  margin: 0;_x000D_
}
_x000D_
<div id="container">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to analyze information from a Java core dump?

Okay if you've created the core dump with gcore or gdb then you'll need to convert it to something called a HPROF file. These can be used by VisualVM, Netbeans or Eclipse's Memory Analyzer Tool (formerly SAP Memory Analyzer). I'd recommend Eclipse MAT.

To convert the file use the commandline tool jmap.

# jmap -dump:format=b,file=dump.hprof /usr/bin/java core.1234

where:

dump.hprof is the name of the hprof file you wish to create

/usr/bin/java is the path to the version of the java binary that generated the core dump

core.1234 is your regular core file.

Convert from ASCII string encoded in Hex to plain ASCII?

>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

i'm just having fun, but the important parts are:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

will look at binascii now...

>>> print binascii.unhexlify('7061756c')
paul

cool (and i have no idea why other people want to make you jump through hoops before they'll help).

How to access a value defined in the application.properties file in Spring Boot

You can use the @Value to load variables from the application.properties if you will use this value in one place, but if you need a more centralized way to load this variables @ConfigurationProperties is a better approach.

Additionally you can load variables and cast it automatically if you need different data types to perform your validations and business logic.

application.properties
custom-app.enable-mocks = false

@Value("${custom-app.enable-mocks}")
private boolean enableMocks;

Get path from open file in Python

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

AngularJS - Binding radio buttons to models with boolean values

You might take a look at this:

https://github.com/michaelmoussa/ng-boolean-radio/

This guy wrote a custom directive to get around the issue that "true" and "false" are strings, not booleans.

remove borders around html input

Try this

#generic_search_button
{
    float: left;
    width: 24px; /*new width*/
    height: 24px; /*new width*/
    border: none !important; /* no border and override any inline styles*/
    margin-top: 7px;
    cursor: pointer;
    background-color: White;
    background-image: url(/Images/search.png);
    background-repeat: no-repeat;
    background-position: center center;
}

I think the image size might be wrong

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

Apply global variable to Vuejs

You can use a Global Mixin to affect every Vue instance. You can add data to this mixin, making a value/values available to all vue components.

To make that value Read Only, you can use the method described in this Stack Overflow answer.

Here is an example:

_x000D_
_x000D_
// This is a global mixin, it is applied to every vue instance. 
// Mixins must be instantiated *before* your call to new Vue(...)
Vue.mixin({
  data: function() {
    return {
      get globalReadOnlyProperty() {
        return "Can't change me!";
      }
    }
  }
})

Vue.component('child', {
  template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});

new Vue({
  el: '#app',
  created: function() {
    this.globalReadOnlyProperty = "This won't change it";
  }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
  In Root: {{globalReadOnlyProperty}}
  <child></child>
</div>
_x000D_
_x000D_
_x000D_

Can a background image be larger than the div itself?

You can use a css3 psuedo element (:before and/or :after) as shown in this article

https://www.exratione.com/2011/09/how-to-overflow-a-background-image-using-css3/

Good Luck...

C++, copy set to vector

You need to use a back_inserter:

std::copy(input.begin(), input.end(), std::back_inserter(output));

std::copy doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy, you must make sure it points to a range that is at least large enough to hold the input range.

std::back_inserter creates an output iterator that calls push_back on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector to hold the range being copied:

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

Or, you could use the std::vector range constructor:

std::vector<double> output(input.begin(), input.end()); 

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

Android: Create spinner programmatically from array

This actually worked for me

    Spinner spinner = new Spinner(this);
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, spinnerArray);
    spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );

    spinner = (Spinner) findViewById( R.id.spinner );
    spinner.setAdapter(spinnerArrayAdapter);

Function to calculate R2 (R-squared) in R

Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]

# 1. 'Actual' and 'Predicted' data
df <- data.frame(
  y_actual = c(1:5),
  y_predicted  = c(0.8, 2.4, 2, 3, 4.8))

# 2. R2 Score components

# 2.1. Average of actual data
avr_y_actual <- mean(df$y_actual)

# 2.2. Total sum of squares
ss_total <- sum((df$y_actual - avr_y_actual)^2)

# 2.3. Regression sum of squares
ss_regression <- sum((df$y_predicted - avr_y_actual)^2)

# 2.4. Residual sum of squares
ss_residuals <- sum((df$y_actual - df$y_predicted)^2)

# 3. R2 Score
r2 <- 1 - ss_residuals / ss_total

Difference between javacore, thread dump and heap dump in Websphere

JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects.

JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads.

Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place. Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser.

Core dump is a os level memory usage of objects. It has more informaiton than a head dump. core dump is not created when we kill a process purposely.

How to return the current timestamp with Moment.js?

Here you are assigning an instance of momentjs to CurrentDate:

var CurrentDate = moment();

Here just a string, the result from default formatting of a momentjs instance:

var CurrentDate = moment().format();

And here the number of seconds since january of... well, unix timestamp:

var CurrentDate = moment().unix();

And here another string as ISO 8601 (What's the difference between ISO 8601 and RFC 3339 Date Formats?):

var CurrentDate = moment().toISOString();

And this can be done too:

var a = moment();
var b = moment(a.toISOString());

console.log(a.isSame(b)); // true

Use of contains in Java ArrayList<String>

Thanks to you all for answering so quickly. I could always use a set but I have the ArrayList working now. The problem was that in the constructor of the class containing the ArrayList, I was not saying:

public RSS_Feed_Miner() {
    ...
    this.rssFeedURLs = new ArrayList<String>();
    ... 
}

D'Oh! for a Friday afternoon.

How to pass parameter to a promise function

Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:

var some_function = function(username, password)
{
 return new Promise(function(resolve, reject)
 {
  /*stuff using username, password*/
  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
}

Then, use it:

some_module.some_function(username, password).then(function(uid)
{
 // stuff
})

 

ES6:

const some_function = (username, password) =>
{
 return new Promise((resolve, reject) =>
 {
  /*stuff using username, password*/

  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
};

Use:

some_module.some_function(username, password).then(uid =>
{
 // stuff
});

How to connect to a remote Git repository?

Like you said remote_repo_url is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.

There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons. You can refer to the documentation about protocols and how to connect to the server

You can check the rest of chapter 4 for more detailed information, as it's talking about how to set up your own server

How to start IIS Express Manually

Once you have IIS Express installed (the easiest way is through Microsoft Web Platform Installer), you will find the executable file in %PROGRAMFILES%\IIS Express (%PROGRAMFILES(x86)%\IIS Express on x64 architectures) and its called iisexpress.exe.

To see all the possible command-line options, just run:

iisexpress /?

and the program detailed help will show up.

If executed without parameters, all the sites defined in the configuration file and marked to run at startup will be launched. An icon in the system tray will show which sites are running.

There are a couple of useful options once you have some sites created in the configuration file (found in %USERPROFILE%\Documents\IISExpress\config\applicationhost.config): the /site and /siteId.

With the first one, you can launch a specific site by name:

iisexpress /site:SiteName

And with the latter, you can launch by specifying the ID:

iisexpress /siteId:SiteId

With this, if IISExpress is launched from the command-line, a list of all the requests made to the server will be shown, which can be quite useful when debugging.

Finally, a site can be launched by specifying the full directory path. IIS Express will create a virtual configuration file and launch the site (remember to quote the path if it contains spaces):

iisexpress /path:FullSitePath

This covers the basic IISExpress usage from the command line.

Python equivalent to 'hold on' in Matlab

The hold on feature is switched on by default in matplotlib.pyplot. So each time you evoke plt.plot() before plt.show() a drawing is added to the plot. Launching plt.plot() after the function plt.show() leads to redrawing the whole picture.

Test if a vector contains a given element

I really like grep() and grepl() for this purpose.

grep() returns a vector of integers, which indicate where matches are.

yo <- c("a", "a", "b", "b", "c", "c")

grep("b", yo)
[1] 3 4

grepl() returns a logical vector, with "TRUE" at the location of matches.

yo <- c("a", "a", "b", "b", "c", "c")

grepl("b", yo)
[1] FALSE FALSE  TRUE  TRUE FALSE FALSE

These functions are case-sensitive.

Iterating Through a Dictionary in Swift

Arrays are ordered collections but dictionaries and sets are unordered collections. Thus you can't predict the order of iteration in a dictionary or a set.

Read this article to know more about Collection Types: Swift Programming Language

How to use JavaScript to change the form action

Try this:

var frm = document.getElementById('search-theme-form') || null;
if(frm) {
   frm.action = 'whatever_you_need.ext' 
}

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

Center an element in Bootstrap 4 Navbar

I had a similar problem; the anchor text in my Bootstrap4 navbar wasn't centered. Simply added text-center in the anchor's class.

How to revert the last migration?

This answer is for similar cases if the top answer by Alasdair does not help. (E.g. if the unwanted migration is created soon again with every new migration or if it is in a bigger migration that can not be reverted or the table has been removed manually.)

...delete the migration, without creating a new migration?

TL;DR: You can delete a few last reverted (confused) migrations and make a new one after fixing models. You can also use other methods to configure it to not create a table by migrate command. The last migration must be created so that it match the current models.


Cases why anyone do not want to create a table for a Model that must exist:

A) No such table should exist in no database on no machine and no conditions

  • When: It is a base model created only for model inheritance of other model.
  • Solution: Set class Meta: abstract = True

B) The table is created rarely, by something else or manually in a special way.

  • Solution: Use class Meta: managed = False
    The migration is created, but never used, only in tests. Migration file is important, otherwise database tests can't run, starting from reproducible initial state.

C) The table is used only on some machine (e.g. in development).

  • Solution: Move the model to a new application that is added to INSTALLED_APPS only under special conditions or use a conditional class Meta: managed = some_switch.

D) The project uses multiple databases in settings.DATABASES

  • Solution: Write a Database router with method allow_migrate in order to differentiate the databases where the table should be created and where not.

The migration is created in all cases A), B), C), D) with Django 1.9+ (and only in cases B, C, D with Django 1.8), but applied to the database only in appropriate cases or maybe never if required so. Migrations have been necessary for running tests since Django 1.8. The complete relevant current state is recorded by migrations even for models with managed=False in Django 1.9+ to be possible to create a ForeignKey between managed/unmanaged models or to can make the model managed=True later. (This question has been written at the time of Django 1.8. Everything here should be valid for versions between 1.8 to the current 2.2.)

If the last migration is (are) not easily revertible then it is possible to cautiously (after database backup) do a fake revert ./manage.py migrate --fake my_app 0010_previous_migration, delete the table manually.

If necessary, create a fixed migration from the fixed model and apply it without changing the database structure ./manage.py migrate --fake my_app 0011_fixed_migration.

Where are the recorded macros stored in Notepad++?

Hit F6

Insert::

npp_open $(PLUGINS_CONFIG_DIR)\..\..\shortcuts.xml

Click OK

You now have the file opened in your editor.


Before altering things checkout the related docs:

How to get the HTML's input element of "file" type to only accept pdf files?

It can be useful to prevent the distracted user to make an involuntary bad choice, but in any case, you have to do the check on the server side anyway.
The best way is to be clear in the upload page. After that, if the user stupidly upload a big file with the wrong type, that's their loss of time, no?

Create table (structure) from existing table

Create table abc select * from def limit 0;

This will definite work

<> And Not In VB.NET

in fact the Is is really good, since to the developpers, you may want to override the operator ==, to compare with the value. say you have a class A, operator == of A is to compare some of the field of A to the parameter. then you will be in trouble in c# to verify whether the object of A is null with following code,

    A a = new A();
...
    if (a != null)
it will totally wrong, you always need to use if((object)a != null)
but in vb.net you cannot write in this way, you always need to write
    if not a is nothing then
or
    if a isnot nothing then

which just as Christian said, vb.net does not 'expected' anything.

os.walk without digging into directories below

You can use this snippet

for root, dirs, files in os.walk(directory):
    if level > 0:
        # do some stuff
    else:
        break
    level-=1

Delete a row from a table by id

How about:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    row.parentNode.removeChild(row);
}

And, if that fails, this should really work:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    var table = row.parentNode;
    while ( table && table.tagName != 'TABLE' )
        table = table.parentNode;
    if ( !table )
        return;
    table.deleteRow(row.rowIndex);
}

Twitter Bootstrap Form File Element Upload Button

/* * Bootstrap 3 filestyle * http://dev.tudosobreweb.com.br/bootstrap-filestyle/ * * Copyright (c) 2013 Markus Vinicius da Silva Lima * Update bootstrap 3 by Paulo Henrique Foxer * Version 2.0.0 * Licensed under the MIT license. * */

(function ($) {
"use strict";

var Filestyle = function (element, options) {
    this.options = options;
    this.$elementFilestyle = [];
    this.$element = $(element);
};

Filestyle.prototype = {
    clear: function () {
        this.$element.val('');
        this.$elementFilestyle.find(':text').val('');
    },

    destroy: function () {
        this.$element
            .removeAttr('style')
            .removeData('filestyle')
            .val('');
        this.$elementFilestyle.remove();
    },

    icon: function (value) {
        if (value === true) {
            if (!this.options.icon) {
                this.options.icon = true;
                this.$elementFilestyle.find('label').prepend(this.htmlIcon());
            }
        } else if (value === false) {
            if (this.options.icon) {
                this.options.icon = false;
                this.$elementFilestyle.find('i').remove();
            }
        } else {
            return this.options.icon;
        }
    },

    input: function (value) {
        if (value === true) {
            if (!this.options.input) {
                this.options.input = true;
                this.$elementFilestyle.prepend(this.htmlInput());

                var content = '',
                    files = [];
                if (this.$element[0].files === undefined) {
                    files[0] = {'name': this.$element[0].value};
                } else {
                    files = this.$element[0].files;
                }

                for (var i = 0; i < files.length; i++) {
                    content += files[i].name.split("\\").pop() + ', ';
                }
                if (content !== '') {
                    this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, ''));
                }
            }
        } else if (value === false) {
            if (this.options.input) {
                this.options.input = false;
                this.$elementFilestyle.find(':text').remove();
            }
        } else {
            return this.options.input;
        }
    },

    buttonText: function (value) {
        if (value !== undefined) {
            this.options.buttonText = value;
            this.$elementFilestyle.find('label span').html(this.options.buttonText);
        } else {
            return this.options.buttonText;
        }
    },

    classButton: function (value) {
        if (value !== undefined) {
            this.options.classButton = value;
            this.$elementFilestyle.find('label').attr({'class': this.options.classButton});
            if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
                this.$elementFilestyle.find('label i').addClass('icon-white');
            } else {
                this.$elementFilestyle.find('label i').removeClass('icon-white');
            }
        } else {
            return this.options.classButton;
        }
    },

    classIcon: function (value) {
        if (value !== undefined) {
            this.options.classIcon = value;
            if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
                this.$elementFilestyle.find('label').find('i').attr({'class': 'icon-white '+this.options.classIcon});
            } else {
                this.$elementFilestyle.find('label').find('i').attr({'class': this.options.classIcon});
            }
        } else {
            return this.options.classIcon;
        }
    },

    classInput: function (value) {
        if (value !== undefined) {
            this.options.classInput = value;
            this.$elementFilestyle.find(':text').addClass(this.options.classInput);
        } else {
            return this.options.classInput;
        }
    },

    htmlIcon: function () {
        if (this.options.icon) {
            var colorIcon = '';
            if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
                colorIcon = ' icon-white ';
            }

            return '<i class="'+colorIcon+this.options.classIcon+'"></i> ';
        } else {
            return '';
        }
    },

    htmlInput: function () {
        if (this.options.input) {
            return '<input type="text" class="'+this.options.classInput+'" style="width: '+this.options.inputWidthPorcent+'% !important;display: inline !important;" disabled> ';
        } else {
            return '';
        }
    },

    constructor: function () {
        var _self = this,
            html = '',
            id = this.$element.attr('id'),
            files = [];

        if (id === '' || !id) {
            id = 'filestyle-'+$('.bootstrap-filestyle').length;
            this.$element.attr({'id': id});
        }

        html = this.htmlInput()+
             '<label for="'+id+'" class="'+this.options.classButton+'">'+
                this.htmlIcon()+
                '<span>'+this.options.buttonText+'</span>'+
             '</label>';

        this.$elementFilestyle = $('<div class="bootstrap-filestyle" style="display: inline;">'+html+'</div>');

        var $label = this.$elementFilestyle.find('label');
        var $labelFocusableContainer = $label.parent();

        $labelFocusableContainer
            .attr('tabindex', "0")
            .keypress(function(e) {
                if (e.keyCode === 13 || e.charCode === 32) {
                    $label.click();
                }
            });

        // hidding input file and add filestyle
        this.$element
            .css({'position':'absolute','left':'-9999px'})
            .attr('tabindex', "-1")
            .after(this.$elementFilestyle);

        // Getting input file value
        this.$element.change(function () {
            var content = '';
            if (this.files === undefined) {
                files[0] = {'name': this.value};
            } else {
                files = this.files;
            }

            for (var i = 0; i < files.length; i++) {
                content += files[i].name.split("\\").pop() + ', ';
            }

            if (content !== '') {
                _self.$elementFilestyle.find(':text').val(content.replace(/\, $/g, ''));
            }
        });

        // Check if browser is Firefox
        if (window.navigator.userAgent.search(/firefox/i) > -1) {
            // Simulating choose file for firefox
            this.$elementFilestyle.find('label').click(function () {
                _self.$element.click();
                return false;
            });
        }
    }
};

var old = $.fn.filestyle;

$.fn.filestyle = function (option, value) {
    var get = '',
        element = this.each(function () {
            if ($(this).attr('type') === 'file') {
                var $this = $(this),
                    data = $this.data('filestyle'),
                    options = $.extend({}, $.fn.filestyle.defaults, option, typeof option === 'object' && option);

                if (!data) {
                    $this.data('filestyle', (data = new Filestyle(this, options)));
                    data.constructor();
                }

                if (typeof option === 'string') {
                    get = data[option](value);
                }
            }
        });

    if (typeof get !== undefined) {
        return get;
    } else {
        return element;
    }
};

$.fn.filestyle.defaults = {
    'buttonText': 'Escolher arquivo',
    'input': true,
    'icon': true,
    'inputWidthPorcent': 65,
    'classButton': 'btn btn-primary',
    'classInput': 'form-control file-input-button',
    'classIcon': 'icon-folder-open'
};

$.fn.filestyle.noConflict = function () {
    $.fn.filestyle = old;
    return this;
};

// Data attributes register
$('.filestyle').each(function () {
    var $this = $(this),
        options = {
            'buttonText': $this.attr('data-buttonText'),
            'input': $this.attr('data-input') === 'false' ? false : true,
            'icon': $this.attr('data-icon') === 'false' ? false : true,
            'classButton': $this.attr('data-classButton'),
            'classInput': $this.attr('data-classInput'),
            'classIcon': $this.attr('data-classIcon')
        };

    $this.filestyle(options);
});
})(window.jQuery);

How do I verify that an Android apk is signed with a release certificate?

Use this command : (Jarsigner is in your Java bin folder goto java->jdk->bin path in cmd prompt)

$ jarsigner -verify my_signed.apk

If the .apk is signed properly, Jarsigner prints "jar verified"

jQuery issue in Internet Explorer 8

I had the same problems.

I solved it verifying that IE8 was not configured correctly to reach the SRC URL.

I changed this, it works right.

Coerce multiple columns to factors at once

and, for completeness and with regards to this question asking about changing string columns only, there's mutate_if:

data <- cbind(stringVar = sample(c("foo","bar"),10,replace=TRUE),
              data.frame(matrix(sample(1:40), 10, 10, dimnames = list(1:10, LETTERS[1:10]))),stringsAsFactors=FALSE)     

factoredData = data %>% mutate_if(is.character,funs(factor(.)))

How to upload file using Selenium WebDriver in Java

I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(

//open upload window upload.click();

//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);

Custom thread pool in Java 8 parallel stream

We can change the default parallelism using the following property:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=16

which can set up to use more parallelism.

Proper way to wait for one function to finish before continuing?

An elegant way to wait for one function to complete first is to use Promises with async/await function.


  1. Firstly, create a Promise. The function I created will be completed after 2s. I used setTimeout in order to demonstrate the situation where the instructions would take some time to execute.
  2. For the second function, you can use async/await function where you will await for the first function to complete before proceeding with the instructions.

Example:

_x000D_
_x000D_
    //1. Create a new function that returns a promise
    function firstFunction() {
      return new Promise((resolve, reject) => {
          let y = 0
          setTimeout(() => {
            for(i=0; i<10; i++){
               y++
            }
             console.log('loop completed')  
             resolve(y)
          }, 2000)
      })
    }
    
    //2. Create an async function
    async function secondFunction() {
        console.log('before promise call')
        //3. Await for the first function to complete
        let result = await firstFunction()
        console.log('promise resolved: ' + result)
        console.log('next step')
    }; 

    secondFunction()
_x000D_
_x000D_
_x000D_


Note:

You could simply resolve the Promise without any value like so resolve(). In my example, I resolved the Promise with the value of y that I can then use in the second function.

Check if a varchar is a number (TSQL)

ISNUMERIC will do

Check the NOTES section too in the article.

How can I close a window with Javascript on Mozilla Firefox 3?

This code will work it out definitely

function closing() {
var answer = confirm("Do you wnat to close this window ?");
    if (answer){
        netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');
        window.close();
    }
    else{
        stop;
    }
}

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

Lot's of similar answers but no explanations...

The error is thrown because the private key file permissions are too open. It is a security risk.

Change the permissions on the private key file to be minimal (read only by owner)

  1. Change owner chown <unix-name> <private-key-file>
  2. Set minimal permissions (read only to file owner) chmod 400 <private-key-file>

Arrays vs Vectors: Introductory Similarities and Differences

arrays:

  • are a builtin language construct;
  • come almost unmodified from C89;
  • provide just a contiguous, indexable sequence of elements; no bells and whistles;
  • are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with malloc);
  • their size must be a compile-time constant unless they are allocated dynamically;
  • they take their storage space depending from the scope where you declare them;
  • if dynamically allocated, you must explicitly deallocate them;
  • if they are dynamically allocated, you just get a pointer, and you can't determine their size; otherwise, you can use sizeof (hence the common idiom sizeof(arr)/sizeof(*arr), that however fails silently when used inadvertently on a pointer);
  • automatically decay to a pointers in most situations; in particular, this happens when passing them to a function, which usually requires passing a separate parameter for their size;
  • can't be returned from a function;
  • can't be copied/assigned directly;
  • dynamical arrays of objects require a default constructor, since all their elements must be constructed first;

std::vector:

  • is a template class;
  • is a C++ only construct;
  • is implemented as a dynamic array;
  • grows and shrinks dynamically;
  • automatically manage their memory, which is freed on destruction;
  • can be passed to/returned from functions (by value);
  • can be copied/assigned (this performs a deep copy of all the stored elements);
  • doesn't decay to pointers, but you can explicitly get a pointer to their data (&vec[0] is guaranteed to work as expected);
  • always brings along with the internal dynamic array its size (how many elements are currently stored) and capacity (how many elements can be stored in the currently allocated block);
  • the internal dynamic array is not allocated inside the object itself (which just contains a few "bookkeeping" fields), but is allocated dynamically by the allocator specified in the relevant template parameter; the default one gets the memory from the freestore (the so-called heap), independently from how where the actual object is allocated;
  • for this reason, they may be less efficient than "regular" arrays for small, short-lived, local arrays;
  • when reallocating, the objects are copied (moved, in C++11);
  • does not require a default constructor for the objects being stored;
  • is better integrated with the rest of the so-called STL (it provides the begin()/end() methods, the usual STL typedefs, ...)

Also consider the "modern alternative" to arrays - std::array; I already described in another answer the difference between std::vector and std::array, you may want to have a look at it.

Can't execute jar- file: "no main manifest attribute"

I faced the same issue and it's fixed now:) Just follow the below steps and the error could be for anything, but the below steps makes the process smoother. I spend lot of time to find the fix.

1.Try restart the Eclipse (if you are using Eclipse to built JAR file) --> Actually this helped my issue in exporting the JAR file properly.

2.After eclipse restart, try to see if your eclipse is able to recognize the main class/method by your Java project --> right click --> Run as --> Run configurations --> Main --> click Search button to see if your eclipse is able to lookup for your main class in the JAR file. --> This is for the validation that JAR file will have the entry point to the main class.

  1. After this, export your Java Dynamic project as "Runnable JAR" file and not JAR file.

  2. In Java launch configuration, choose your main class.

  3. Once export the jar file, use the below command to execute. java -cp [Your JAR].jar [complete package].MainClass eg: java -cp AppleTCRuleAudit.jar com.apple.tcruleaudit.classes.TCRuleAudit

  4. You might face the unsupported java version error. the fix is to change the java_home in your shell bash profile to match the java version used to compile the project in eclipse.

Hope this helps! Kindly let me know if you still have any issues.

How do I execute a file in Cygwin?

gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.

-AD.

What does bundle exec rake mean?

I have not used bundle exec much, but am setting it up now.

I have had instances where the wrong rake was used and much time wasted tracking down the problem. This helps you avoid that.

Here's how to set up RVM so you can use bundle exec by default within a specific project directory:

https://thoughtbot.com/blog/use-bundlers-binstubs

Laravel whereIn OR whereIn

You could have searched just for whereIn function in the core to see that. Here you are. This must answer all your questions

/**
 * Add a "where in" clause to the query.
 *
 * @param  string  $column
 * @param  mixed   $values
 * @param  string  $boolean
 * @param  bool    $not
 * @return \Illuminate\Database\Query\Builder|static
 */
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
    $type = $not ? 'NotIn' : 'In';

    // If the value of the where in clause is actually a Closure, we will assume that
    // the developer is using a full sub-select for this "in" statement, and will
    // execute those Closures, then we can re-construct the entire sub-selects.
    if ($values instanceof Closure)
    {
        return $this->whereInSub($column, $values, $boolean, $not);
    }

    $this->wheres[] = compact('type', 'column', 'values', 'boolean');

    $this->bindings = array_merge($this->bindings, $values);

    return $this;
}

Look that it has a third boolean param. Good luck.

Python SQL query string formatting

Cleanest way I have come across is inspired by the sql style guide.

sql = """
    SELECT field1, field2, field3, field4
      FROM table
     WHERE condition1 = 1
       AND condition2 = 2;
"""

Essentially, the keywords that begin a clause should be right-aligned and the field names etc, should be left aligned. This looks very neat and is easier to debug as well.

UICollectionView auto scroll to cell at IndexPath

Swift:

your_CollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)

Swift 3

let indexPath = IndexPath(row: itemIndex, section: sectionIndex)

collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.right, animated: true)

Scroll Position:

UICollectionViewScrollPosition.CenteredHorizontally / UICollectionViewScrollPosition.CenteredVertically

replace special characters in a string python

One way is to use re.sub, that's my preferred way.

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

Output:

hey there

Another way is to use re.escape:

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub(r'['+chars+']', '',my_str)

Output:

hey there

Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars

Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]

How to return value from Action()?

You can also take advantage of the fact that a lambda or anonymous method can close over variables in its enclosing scope.

MyType result;

SimpleUsing.DoUsing(db => 
{
  result = db.SomeQuery(); //whatever returns the MyType result
}); 

//do something with result

Jquery asp.net Button Click Event via ajax

ASP.NET web forms page already have a JavaScript method for handling PostBacks called "__doPostBack".

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

Use the following in your code file to generate the JavaScript that performs the PostBack. Using this method will ensure that the proper ClientID for the control is used.

protected string GetLoginPostBack()
{
    return Page.ClientScript.GetPostBackEventReference(btnLogin, string.Empty);
}

Then in the ASPX page add a javascript block.

<script language="javascript">
function btnLogin_Click() {
  <%= GetLoginPostBack() %>;
}
</script>

The final javascript will be rendered like this.

<script language="javascript">
function btnLogin_Click() {
  __doPostBack('btnLogin','');
}
</script>

Now you can use "btnLogin_Click()" from your javascript to submit the button click to the server.

what's the easiest way to put space between 2 side-by-side buttons in asp.net

you can use btnSubmit::before { margin-left: 20px; }

Postgres manually alter sequence

The parentheses are misplaced:

SELECT setval('payments_id_seq', 21, true);  # next value will be 22

Otherwise you're calling setval with a single argument, while it requires two or three.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

For me, the below helped

Find org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional, add it to your dependency.

Source

copying all contents of folder to another folder using batch file?

if you want remove the message that tells if the destination is a file or folder you just add a slash:

xcopy /s c:\Folder1 d:\Folder2\

What is "not assignable to parameter of type never" error in typescript?

Remove "strictNullChecks": true from "compilerOptions" or set it to false in the tsconfig.json file of your Ng app. These errors will go away like anything and your app would compile successfully.

Disclaimer: This is just a workaround. This error appears only when the null checks are not handled properly which in any case is not a good way to get things done.

PHP-FPM and Nginx: 502 Bad Gateway

Hope this tip will save someone else's life. In my case the problem was that I ran out of memory, but only slightly, was hard to think about it. Wasted 3hrs on that. I recommend running:

sudo htop

or

sudo free -m

...along with running problematic requests on the server to see if your memory doesn't run out. And if it does like in my case, you need to create swap file (unless you already have one).

I have followed this tutorial to create swap file on Ubuntu Server 14.04 and it worked just fine: http://www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/

Adding Counter in shell script

Try this:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter limit reached, exit script."
       exit 1
  else
       let counter++
       echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Explanation

  • break - if files are present, it will break and allow the script to process the files.
  • [[ "$counter" -gt 20 ]] - if the counter variable is greater than 20, the script will exit.
  • let counter++ - increments the counter by 1 at each pass.

How to copy directory recursively in python and overwrite all?

My simple answer.

def get_files_tree(src="src_path"):
    req_files = []
    for r, d, files in os.walk(src):
        for file in files:
            src_file = os.path.join(r, file)
            src_file = src_file.replace('\\', '/')
            if src_file.endswith('.db'):
                continue
            req_files.append(src_file)

    return req_files
def copy_tree_force(src_path="",dest_path=""):
    """
    make sure that all the paths has correct slash characters.
    """
    for cf in get_files_tree(src=src_path):
        df= cf.replace(src_path, dest_path)
        if not os.path.exists(os.path.dirname(df)):
            os.makedirs(os.path.dirname(df))
        shutil.copy2(cf, df)

Format ints into string of hex

With python 2.X, you can do the following:

numbers = [0, 1, 2, 3, 127, 200, 255]
print "".join(chr(i).encode('hex') for i in numbers)

print

'000102037fc8ff'

Convert Base64 string to an image file?

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}

Compiling with g++ using multiple cores

distcc can also be used to distribute compiles not only on the current machine, but also on other machines in a farm that have distcc installed.

check if a file is open in Python

Using

try:
with open("path", "r") as file:#or just open

may cause some troubles when file is opened by some other processes (i.e. user opened it manually). You can solve your poblem using win32com library. Below code checks if any excel files are opened and if none of them matches the name of your particular one, openes a new one.

import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')

my_workbook = "wb_name.xls"
xlPath="my_wb_path//" + my_workbook


if xl.Workbooks.Count > 0:
    # if none of opened workbooks matches the name, openes my_workbook 
    if not any(i.Name == my_workbook for i in xl.Workbooks): 
        xl.Workbooks.Open(Filename=xlPath)
        xl.Visible = True
#no workbooks found, opening
else:  
    xl.Workbooks.Open(Filename=xlPath)
    xl.Visible = True

'xl.Visible = True is not necessary, used just for convenience'

Hope this will help

Bootstrap: wider input field

I am going to assume you were having the same issue I was. Even though you specify larger sizes for the TextBox and mark it as important, the box would not get larger. That is likely because in your site.css file the MaxWidth is being set to 280px.

Add a style attribute to your input to remove the MaxWidth like this:

<input type="text"  style="max-width:none !important" class="input-medium">

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

Delete files older than 15 days using PowerShell

If you are having problems with the above examples on a Windows 10 box, try replacing .CreationTime with .LastwriteTime. This worked for me.

dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force

Command line to remove an environment variable from the OS level configuration

setx FOOBAR ""

just causes the value of FOOBAR to be a null string. (Although, it shows with the set command with the "" so maybe double-quotes is the string.)

I used:

set FOOBAR=

and then FOOBAR was no longer listed in the set command. (Log-off was not required.)

Windows 7 32 bit, using the command prompt, non-administrator is what I used. (Not cmd or Windows + R, which might be different.)

BTW, I did not see the variable I created anywhere in the registry after I created it. I'm using RegEdit not as administrator.

Google Authenticator available as a public service?

The project is open source. I have not used it. But it's using a documented algorithm (noted in the RFC listed on the open source project page), and the authenticator implementations support multiple accounts.

The actual process is straightforward. The one time code is, essentially, a pseudo random number generator. A random number generator is a formula that once given a seed, or starting number, continues to create a stream of random numbers. Given a seed, while the numbers may be random to each other, the sequence itself is deterministic. So, once you have your device and the server "in sync" then the random numbers that the device creates, each time you hit the "next number button", will be the same, random, numbers the server expects.

A secure one time password system is more sophisticated than a random number generator, but the concept is similar. There are also other details to help keep the device and server in sync.

So, there's no need for someone else to host the authentication, like, say OAuth. Instead you need to implement that algorithm that is compatible with the apps that Google provides for the mobile devices. That software is (should be) available on the open source project.

Depending on your sophistication, you should have all you need to implement the server side of this process give the OSS project and the RFC. I do not know if there is a specific implementation for your server software (PHP, Java, .NET, etc.)

But, specifically, you don't need an offsite service to handle this.

How to get the selected radio button’s value?

Since jQuery 1.8, the correct syntax for the query is

$('input[name="genderS"]:checked').val();

Not $('input[@name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the @).

Add to integers in a list

Yes, it is possible since lists are mutable.

Look at the built-in enumerate() function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).

Text blinking jQuery

One more made from the core jQuery functionality(it could be better):

function blink( el ) {
    if (!el) {
        el = this
    }

    $(el).animate( { opacity: 0.5 },1200, function() {
        $(this).animate( {opacity: 1 }, 1200, blink );
    } );
}

You can tweak the animation opacity change(0.5- 1) and delay(1200) to get a better "blink". This one is less annoying than the blink of the 90es :-)

Auto-increment on partial primary key with Entity Framework Core

To anyone who came across this question who are using SQL Server Database and still having an exception thrown even after adding the following annotation on the int primary key

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

Please check your SQL, make sure your the primary key has 'IDENTITY(startValue, increment)' next to it,

CREATE TABLE [dbo].[User]
(
    [Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY
)

This will make the database increments the id every time a new row is added, with a starting value of 1 and increments of 1.

I accidentally overlooked that in my SQL which cost me an hour of my life, so hopefully this helps someone!!!

Lightweight workflow engine for Java

CamundaBPM is one option. You can check here: https://camunda.com/

make div's height expand with its content

I added Bootstrap to a project with section tags that I had set to 100% of screen height. It worked well until I made the project responsive, at which point I borrowed part of jennyfofenny's answer so my section background matched background of the content when the screen size changed on smaller screens.

My new section CSS looks like this:

section {
    // min-height so it looks good on big screen
    // but resizes on a small-screen
    min-height: 100%;
    min-height: 100vh;
    width:100%;
    width:100vh;
}

Let's say you've got a section that's a certain color. By using min-height, if the width of the section shrinks because of a smaller-screen, the height of the section will expand, the content will stay within the section, and your background will stay the desired color.

Parallel.ForEach vs Task.Factory.StartNew

I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.

I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.

I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.

Experiment 1

Parallel.For(0, 1000000000, x => Method1());

Experiment 2

for (int i = 0; i < 1000000000; i++)
{
    Task o = new Task(Method1);
    o.Start();
}

Processor time comparison

How can I convert tabs to spaces in every file of a directory?

You can use the generally available pr command (man page here). For example, to convert tabs to four spaces, do this:

pr -t -e=4 file > file.expanded
  • -t suppresses headers
  • -e=num expands tabs to num spaces

To convert all files in a directory tree recursively, while skipping binary files:

#!/bin/bash
num=4
shopt -s globstar nullglob
for f in **/*; do
  [[ -f "$f" ]]   || continue # skip if not a regular file
  ! grep -qI "$f" && continue # skip binary files
  pr -t -e=$num "$f" > "$f.expanded.$$" && mv "$f.expanded.$$" "$f"
done

The logic for skipping binary files is from this post.

NOTE:

  1. Doing this could be dangerous in a git or svn repo
  2. This is not the right solution if you have code files that have tabs embedded in string literals

Local package.json exists, but node_modules missing

This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.

please check on it and run npm install first and then npm start.

Swift extract regex matches

I found that the accepted answer's solution unfortunately does not compile on Swift 3 for Linux. Here's a modified version, then, that does:

import Foundation

func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try RegularExpression(pattern: regex, options: [])
        let nsString = NSString(string: text)
        let results = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range) }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

The main differences are:

  1. Swift on Linux seems to require dropping the NS prefix on Foundation objects for which there is no Swift-native equivalent. (See Swift evolution proposal #86.)

  2. Swift on Linux also requires specifying the options arguments for both the RegularExpression initialization and the matches method.

  3. For some reason, coercing a String into an NSString doesn't work in Swift on Linux but initializing a new NSString with a String as the source does work.

This version also works with Swift 3 on macOS / Xcode with the sole exception that you must use the name NSRegularExpression instead of RegularExpression.

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.

What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:

header('Content-Type: application/json; charset=utf-8');

The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.

Java: how do I initialize an array size if it's unknown?

If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

import java.util.Scanner;

public class ArrayModify {

    public static void main(String[] args) {
        int[] list;
        String st;
        String[] stNew;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
        st = scan.nextLine();
        stNew = st.split("\\s+");
        list = new int[stNew.length]; // Sets array size to 5

        for (int i = 0; i < stNew.length; i++){
            list[i] =  Integer.parseInt(stNew[i]);
            System.out.println("You Enterred: " + list[i]);
        }
    }
}

An Authentication object was not found in the SecurityContext - Spring 3.2.2

The security's authorization check part gets the authenticated object from SecurityContext, which will be set when a request gets through the spring security filter. My assumption here is that soon after the login this is not being set. You probably can use a hack as given below to set the value.

try {
    SecurityContext ctx = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(ctx);
    ctx.setAuthentication(event.getAuthentication());

    //Do what ever you want to do

} finally {
    SecurityContextHolder.clearContext();
}

Update:

Also you can have a look at the InteractiveAuthenticationSuccessEvent which will be called once the SecurityContext is set.

Using SSIS BIDS with Visual Studio 2012 / 2013

First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]

Basically this question has the title ...Visual Studio 2012 / 2013 What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.

So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj project. Now this computer does not yet have sql server installed on it yet.

Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates

Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.

In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396

Animate text change in UILabel

Swift 2.0:

UIView.transitionWithView(self.view, duration: 1.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
    self.sampleLabel.text = "Animation Fade1"
    }, completion: { (finished: Bool) -> () in
        self.sampleLabel.text = "Animation Fade - 34"
})

OR

UIView.animateWithDuration(0.2, animations: {
    self.sampleLabel.alpha = 1
}, completion: {
    (value: Bool) in
    self.sampleLabel.alpha = 0.2
})

Bootstrap Align Image with text

  <div class="container">
          <h1>About me</h1>
       <div class="row">
         <div class="pull-left ">
             <img src="http://lorempixel.com/200/200" class="col-lg-3" class="img-    responsive" alt="Responsive image">
                <p class="col-md-4">Lots of text here... </p> 
                </div>

          </div>
      </div>
   </div>

Does Git Add have a verbose switch

Well, like (almost) every console program for unix-like systems, git does not tell you anything if a command succeeds. It prints out something only if there's something wrong.

However if you want to be sure of what just happened, just type

git status

and see which changes are going to be committed and which not. I suggest you to use this before every commit, just to be sure that you are not forgetting anything.

Since you seem new to git, here is a link to a free online book that introduces you to git. It's very useful, it writes about basics as well as well known different workflows: http://git-scm.com/book

NodeJs : TypeError: require(...) is not a function

Remember to export your routes.js.

In routes.js, write your routes and all your code in this function module:

exports = function(app, passport) {

/* write here your code */ 

}

How to calculate the angle between a line and the horizontal axis?

import math
from collections import namedtuple


Point = namedtuple("Point", ["x", "y"])


def get_angle(p1: Point, p2: Point) -> float:
    """Get the angle of this line with the horizontal axis."""
    dx = p2.x - p1.x
    dy = p2.y - p1.y
    theta = math.atan2(dy, dx)
    angle = math.degrees(theta)  # angle is in (-180, 180]
    if angle < 0:
        angle = 360 + angle
    return angle

Testing

For testing I let hypothesis generate test cases.

enter image description here

import hypothesis.strategies as s
from hypothesis import given


@given(s.floats(min_value=0.0, max_value=360.0))
def test_angle(angle: float):
    epsilon = 0.0001
    x = math.cos(math.radians(angle))
    y = math.sin(math.radians(angle))
    p1 = Point(0, 0)
    p2 = Point(x, y)
    assert abs(get_angle(p1, p2) - angle) < epsilon

iOS download and save image inside app

Since we are on IO5 now, you no longer need to write images to disk neccessarily.
You are now able to set "allow external storage" on an coredata binary attribute. According to apples release notes it means the following:

Small data values like image thumbnails may be efficiently stored in a database, but large photos or other media are best handled directly by the file system. You can now specify that the value of a managed object attribute may be stored as an external record - see setAllowsExternalBinaryDataStorage: When enabled, Core Data heuristically decides on a per-value basis if it should save the data directly in the database or store a URI to a separate file which it manages for you. You cannot query based on the contents of a binary data property if you use this option.

Session variables in ASP.NET MVC

Well, IMHO..

  1. never reference a Session inside your view/master page
  2. minimize your useage of Session. MVC provides TempData obj for this, which is basically a Session that lives for a single trip to the server.

With regards to #1, I have a strongly typed Master View which has a property to access whatever the Session object represents....in my instance the stongly typed Master View is generic which gives me some flexibility with regards to strongly typed View Pages

ViewMasterPage<AdminViewModel>

AdminViewModel
{
    SomeImportantObjectThatWasInSession ImportantObject
}

AdminViewModel<TModel> : AdminViewModel where TModel : class
{
   TModel Content
}

and then...

ViewPage<AdminViewModel<U>>

Load HTML page dynamically into div with jQuery

You can use jQuery's getJSON() or Load(); with the latter, you can reference an existing html file. For more details, see http://www.codeproject.com/Articles/661782/Three-Ways-to-Dynamically-Load-HTML-Content-into-a

Working with huge files in VIM

emacs works very well with files into the 100's of megabytes, I've used it on log files without too much trouble.

But generally when I have some kind of analysis task, I find writing a perl script a better choice.

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

Mismatched anonymous define() module

In getting started with require.js I ran into the issue and as a beginner the docs may as well been written in greek.

The issue I ran into was that most of the beginner examples use "anonymous defines" when you should be using a "string id".

anonymous defines

define(function() {
        return { helloWorld: function() { console.log('hello world!') } };
 })
    
  
define(function() {
        return { helloWorld2: function() { console.log('hello world again!') } };
 })

define with string id

define('moduleOne',function() {
    return { helloWorld: function() { console.log('hello world!') } };
})

 define('moduleTwo', function() {
      return { helloWorld2: function() { console.log('hello world again!') } };
})

When you use define with a string id then you will avoid this error when you try to use the modules like so:

require([ "moduleOne", "moduleTwo" ], function(moduleOne, moduleTwo) {
    moduleOne.helloWorld();
    moduleTwo.helloWorld2();
});

SQL, How to Concatenate results?

Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .

       SELECT STUFF((  SELECT ',' + ModuleValue AS ModuleValue
                           FROM ModuleValue WHERE ModuleID=@ModuleID
                      FOR XML PATH('') 
                     ), 1, 1, '' )

release Selenium chromedriver.exe from memory

I came here initially thinking surely this would have been answered/resolved but after reading all the answers I was a bit surprised no one tried to call all three methods together:

try
{
    blah
}
catch
{
    blah
}
finally
{
    driver.Close(); // Close the chrome window
    driver.Quit(); // Close the console app that was used to kick off the chrome window
    driver.Dispose(); // Close the chromedriver.exe
}

I was only here to look for answers and didn't intend to provide one. So the above solution is based on my experience only. I was using chrome driver in a C# console app and I was able to clean up the lingering processes only after calling all three methods together.

How to uninstall Golang?

From the official install page -

To remove an existing Go installation from your system delete the go directory. This is usually /usr/local/go under Linux, macOS, and FreeBSD or c:\Go under Windows.

You should also remove the Go bin directory from your PATH environment variable. Under Linux and FreeBSD you should edit /etc/profile or $HOME/.profile. If you installed Go with the macOS package then you should remove the /etc/paths.d/go file. Windows users should read the section about setting environment variables under Windows.

How to get visitor's location (i.e. country) using geolocation?

You can use ip-api.io to get visitor's location. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

JavaScript Code:

function getIPDetails() {
    var ipAddress = document.getElementById("txtIP").value;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(JSON.parse(xhttp.responseText));
        }
    };
    xhttp.open("GET", "http://ip-api.io/json/" + ipAddress, true);
    xhttp.send();
}

<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>

jQuery Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('Country Name: ' + result.country_name)
                     console.log(result);
                 });
        });
    });

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>
</div>

Can I do Android Programming in C++, C?

You should use Android NDK to develop performance-critical portions of your apps in native code. See Android NDK.

Anyway i don't think it is the right way to develop an entire application.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

It got resolved for me, when I enable checkbox for UrlRoutingModule-4.0:

IIS Manager > Modules > select UrlRoutingModule-4.0 > Edit Module > check the check-box "Invoke only for requests to ASP.NET applications or managed handlers".

How do I handle Database Connections with Dapper in .NET?

I created extension methods with a property that retrieves the connection string from configuration. This lets the callers not have to know anything about the connection, whether it's open or closed, etc. This method does limit you a bit since you're hiding some of the Dapper functionality, but in our fairly simple app it's worked fine for us, and if we needed more functionality from Dapper we could always add a new extension method that exposes it.

internal static string ConnectionString = new Configuration().ConnectionString;

    internal static IEnumerable<T> Query<T>(string sql, object param = null)
    {
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            return conn.Query<T>(sql, param);
        }
    }

    internal static int Execute(string sql, object param = null)
    {
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            return conn.Execute(sql, param);
        }
    }

MySQL Query - Records between Today and Last 30 Days

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

Can two applications listen to the same port?

Yes Definitely. As far as i remember From kernel version 3.9 (Not sure on the version) onwards support for the SO_REUSEPORT was introduced. SO_RESUEPORT allows binding to the exact same port and address, As long as the first server sets this option before binding its socket.

It works for both TCP and UDP. Refer to the link for more details: SO_REUSEPORT

Note: Accepted answer no longer holds true as per my opinion.

Take a char input from the Scanner

There are three ways to approach this problem:

  • Call next() on the Scanner, and extract the first character of the String (e.g. charAt(0)) If you want to read the rest of the line as characters, iterate over the remaining characters in the String. Other answers have this code.

  • Use setDelimiter("") to set the delimiter to an empty string. This will cause next() to tokenize into strings that are exactly one character long. So then you can repeatedly call next().charAt(0) to iterate the characters. You can then set the delimiter to its original value and resume scanning in the normal way!

  • Use the Reader API instead of the Scanner API. The Reader.read() method delivers a single character read from the input stream. For example:

    Reader reader = new InputStreamReader(System.in);
    int ch = reader.read();
    if (ch != -1) {  // check for EOF
        // we have a character ...
    }
    

When you read from the console via System.in, the input is typically buffered by the operating system, and only "released" to the application when the user types ENTER. So if you intend your application to respond to individual keyboard strokes, this is not going to work. You would need to do some OS-specific native code stuff to turn off or work around line-buffering for console at the OS level.

Reference:

PHP code to remove everything but numbers

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

How to stop mongo DB in one command

I simply did:

quit();

Please note I'm using mongo 3.0.

Mongo