Programs & Examples On #Sockets

An endpoint of a bidirectional inter-process communication flow. This often refers to a process flow over a network connection, but by no means is limited to such. Not to be confused with websocket (a protocol) or other abstractions (e.g. socket.io).

How to find an available port?

If your server starts up, then that socket was not used.

EDIT

Something like:

ServerSocket s = null ;

try { 
    s = new ServerSocket( 0 ); 
} catch( IOException ioe ){
   for( int i = START; i < END ; i++ ) try {
        s = new ServerSocket( i );
    } catch( IOException ioe ){}
}
// At this point if s is null we are helpless
if( s == null ) {
    throw new IOException(
       Strings.format("Unable to open server in port range(%d-%d)",START,END));
}

Socket.io + Node.js Cross-Origin Request Blocked

Take a look at this: Complete Example

Server:

let exp = require('express');
let app = exp();

//UPDATE: this is seems to be deprecated
//let io = require('socket.io').listen(app.listen(9009));
//New Syntax:
const io = require('socket.io')(app.listen(9009));

app.all('/', function (request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
});

Client:

<!--LOAD THIS SCRIPT FROM SOMEWHERE-->
<script src="http://127.0.0.1:9009/socket.io/socket.io.js"></script>
<script>
    var socket = io("127.0.0.1:9009/", {
        "force new connection": true,
        "reconnectionAttempts": "Infinity", 
        "timeout": 10001, 
        "transports": ["websocket"]
        }
    );
</script>

I remember this from the combination of stackoverflow answers many days ago; but I could not find the main links to mention them

Getting the IP Address of a Remote Socket Endpoint

I've made this code in VB.NET but you can translate. Well pretend you have the variable Client as a TcpClient

Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))

Hope it helps! Cheers.

TypeError: a bytes-like object is required, not 'str'

Whenever you encounter an error with this message use my_string.encode().

(where my_string is the string you're passing to a function/method).

The encode method of str objects returns the encoded version of the string as a bytes object which you can then use. In this specific instance, socket methods such as .send expect a bytes object as the data to be sent, not a string object.

Since you have an object of type str and you're passing it to a function/method that expects an object of type bytes, an error is raised that clearly explains that:

TypeError: a bytes-like object is required, not 'str'

So the encode method of strings is needed, applied on a str value and returning a bytes value:

>>> s = "Hello world"
>>> print(type(s))
<class 'str'>
>>> byte_s = s.encode()
>>> print(type(byte_s))
<class 'bytes'>
>>> print(byte_s)
b"Hello world"

Here the prefix b in b'Hello world' denotes that this is indeed a bytes object. You can then pass it to whatever function is expecting it in order for it to run smoothly.

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

Server Client send/receive simple text

    static void Main(string[] args)
    {
        //---listen at the specified IP and port no.---
        IPAddress localAdd = IPAddress.Parse(SERVER_IP);
        TcpListener listener = new TcpListener(localAdd, PORT_NO);
        Console.WriteLine("Listening...");
        listener.Start();
        while (true)
        {
            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();

            //---get the incoming data through a network stream---
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received : " + dataReceived);

            //---write back the text to the client---
            Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffer, 0, bytesRead);
            client.Close();
        }
        listener.Stop();
        Console.ReadLine();
    }

In addition to @Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

Closing WebSocket correctly (HTML5, Javascript)

please use this

var uri = "ws://localhost:5000/ws";
var socket = new WebSocket(uri);
socket.onclose = function (e){
    console.log(connection closed);
};
window.addEventListener("unload", function () {
    if(socket.readyState == WebSocket.OPEN)
        socket.close();
});

Close browser doesn't trigger websocket close event. You must call socket.close() manually.

No connection could be made because the target machine actively refused it 127.0.0.1

I had the same issue with a site which previously was running fine. I resolved the issue by deleting the temporary files from C:\WINDOWS\Microsoft.NET\Framework\v#.#.#####\Temporary ASP.NET Files\@projectName\###CC##C\###C#CC

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

How to fix java.net.SocketException: Broken pipe?

I noticed I was using the incorrect HTTP request url while making it, later which i changed that it resolved my problem. my upload url was : http://192.168.0.31:5000/uploader while i was using http://192.168.0.31:5000. that was a get call. and got a java.net.SocketException: Broken pipe? exception.

That was my reason. might lead you to check one more point when this issue

  public void postRequest()  {


        Security.insertProviderAt(Conscrypt.newProvider(), 1);

        System.out.println("mediafilename-->>" + mediaFileName);
        String[] dirarray = mediaFileName.split("/");
        String file_name = dirarray[6];
        //Thread.sleep(10000);

        RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file",file_name, RequestBody.create(MediaType.parse("video/mp4"), new File(mediaFileName))).build();
        OkHttpClient okHttpClient = new OkHttpClient();
//        ExecutorService executor = newFixedThreadPool(20);
//        Request request = new Request.Builder().post(requestBody).url("https://192.168.0.31:5000/uploader").build();
        Request request = new Request.Builder().url("http://192.168.0.31:5000/uploader").post(requestBody).build();
//        Request request = new Request.Builder().url("http://192.168.0.31:5000").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

//

                call.cancel();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Something went wrong:" + " ", Toast.LENGTH_SHORT).show();

                    }
                });
                e.printStackTrace();

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            System.out.println(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });


                System.out.println("Response ; " + response.body().toString());
//                Toast.makeText(getApplicationContext(), response.body().toString(),Toast.LENGTH_LONG).show();
                System.out.println(response);

            }
        });

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

  1. The fd is already closed somewhere.
  2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

How to tell if a connection is dead in python

I translated the code sample in this blog post into Python: How to detect when the client closes the connection?, and it works well for me:

from ctypes import (
    CDLL, c_int, POINTER, Structure, c_void_p, c_size_t,
    c_short, c_ssize_t, c_char, ARRAY
)


__all__ = 'is_remote_alive',


class pollfd(Structure):
    _fields_ = (
        ('fd', c_int),
        ('events', c_short),
        ('revents', c_short),
    )


MSG_DONTWAIT = 0x40
MSG_PEEK = 0x02

EPOLLIN = 0x001
EPOLLPRI = 0x002
EPOLLRDNORM = 0x040

libc = CDLL(None)

recv = libc.recv
recv.restype = c_ssize_t
recv.argtypes = c_int, c_void_p, c_size_t, c_int

poll = libc.poll
poll.restype = c_int
poll.argtypes = POINTER(pollfd), c_int, c_int


class IsRemoteAlive:  # not needed, only for debugging
    def __init__(self, alive, msg):
        self.alive = alive
        self.msg = msg

    def __str__(self):
        return self.msg

    def __repr__(self):
        return 'IsRemoteClosed(%r,%r)' % (self.alive, self.msg)

    def __bool__(self):
        return self.alive


def is_remote_alive(fd):
    fileno = getattr(fd, 'fileno', None)
    if fileno is not None:
        if hasattr(fileno, '__call__'):
            fd = fileno()
        else:
            fd = fileno

    p = pollfd(fd=fd, events=EPOLLIN|EPOLLPRI|EPOLLRDNORM, revents=0)
    result = poll(p, 1, 0)
    if not result:
        return IsRemoteAlive(True, 'empty')

    buf = ARRAY(c_char, 1)()
    result = recv(fd, buf, len(buf), MSG_DONTWAIT|MSG_PEEK)
    if result > 0:
        return IsRemoteAlive(True, 'readable')
    elif result == 0:
        return IsRemoteAlive(False, 'closed')
    else:
        return IsRemoteAlive(False, 'errored')

Cannot assign requested address using ServerSocket.socketBind

I came across this error when copying configurations from one server to another.

I had the old host's hostname in my ${JETTY_BASE}/start.ini jetty.host property. Setting the correct jetty.host property value solved the issue for me.

Hope this helps someone in the future who has to work on multiple servers at once.

java.net.SocketException: Software caused connection abort: recv failed

This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.

Python Socket Receive Large Amount of Data

For anyone else who's looking for an answer in cases where you don't know the length of the packet prior. Here's a simple solution that reads 4096 bytes at a time and stops when less than 4096 bytes were received. However, it will not work in cases where the total length of the packet received is exactly 4096 bytes - then it will call recv() again and hang.

def recvall(sock):
    data = b''
    bufsize = 4096
    while True:
        packet = sock.recv(bufsize)
        data += packet
        if len(packet) < bufsize:
            break
    return data

Using Sockets to send and receive data

    //Client

    import java.io.*;
    import java.net.*;

    public class Client {
        public static void main(String[] args) {

        String hostname = "localhost";
        int port = 6789;

        // declaration section:
        // clientSocket: our client socket
        // os: output stream
        // is: input stream

            Socket clientSocket = null;  
            DataOutputStream os = null;
            BufferedReader is = null;

        // Initialization section:
        // Try to open a socket on the given port
        // Try to open input and output streams

            try {
                clientSocket = new Socket(hostname, port);
                os = new DataOutputStream(clientSocket.getOutputStream());
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: " + hostname);
            }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on the given port

        if (clientSocket == null || os == null || is == null) {
            System.err.println( "Something is wrong. One variable is null." );
            return;
        }

        try {
            while ( true ) {
            System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String keyboardInput = br.readLine();
            os.writeBytes( keyboardInput + "\n" );

            int n = Integer.parseInt( keyboardInput );
            if ( n == 0 || n == -1 ) {
                break;
            }

            String responseLine = is.readLine();
            System.out.println("Server returns its square as: " + responseLine);
            }

            // clean up:
            // close the output stream
            // close the input stream
            // close the socket

            os.close();
            is.close();
            clientSocket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
        }           
    }





//Server




import java.io.*;
import java.net.*;

public class Server1 {
    public static void main(String args[]) {
    int port = 6789;
    Server1 server = new Server1( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int port;

    public Server1( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)

        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }   

    System.out.println( "Waiting for connections. Only one connection is allowed." );

    // Create a socket object from the ServerSocket to listen and accept connections.
    // Use Server1Connection to process the connection.

    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        Server1Connection oneconnection = new Server1Connection(clientSocket, this);
        oneconnection.run();
        }   
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server1Connection {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    Server1 server;

    public Server1Connection(Socket clientSocket, Server1 server) {
    this.clientSocket = clientSocket;
    this.server = server;
    System.out.println( "Connection established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n ); 
            }

        System.out.println( "Connection closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}

Python [Errno 98] Address already in use

$ ps -fA | grep python
501 81211 12368   0  10:11PM ttys000    0:03.12  
python -m SimpleHTTPServer

$ kill 81211

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read into that buffer, and write from that buffer into your socket (you could also use send and recv, which are socket-specific ways of writing and reading data). The outline would look something like this:

while (1) {
    // Read data into buffer.  We may not have enough to fill up buffer, so we
    // store how many bytes were actually read in bytes_read.
    int bytes_read = read(input_file, buffer, sizeof(buffer));
    if (bytes_read == 0) // We're done reading from the file
        break;

    if (bytes_read < 0) {
        // handle errors
    }

    // You need a loop for the write, because not all of the data may be written
    // in one call; write will return how many bytes were written. p keeps
    // track of where in the buffer we are, while we decrement bytes_read
    // to keep track of how many bytes are left to write.
    void *p = buffer;
    while (bytes_read > 0) {
        int bytes_written = write(output_socket, p, bytes_read);
        if (bytes_written <= 0) {
            // handle errors
        }
        bytes_read -= bytes_written;
        p += bytes_written;
    }
}

Make sure to read the documentation for read and write carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue statement, while others mean something is broken and you need to stop.

For sending the file to a socket, there is a system call, sendfile that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap (as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile call but no analogous recvfile.

Beware that sendfile is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile, but the exact interface may vary (FreeBSD, Mac OS X, Solaris).

In Linux 2.6.17, the splice system call was introduced, and as of 2.6.23 is used internally to implement sendfile. splice is a more general purpose API than sendfile. For a good description of splice and tee, see the rather good explanation from Linus himself. He points out how using splice is basically just like the loop above, using read and write, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:

import sys
import socket
import fcntl, os
import errno
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)

while True:
    try:
        msg = s.recv(4096)
    except socket.error, e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            sleep(1)
            print 'No data available'
            continue
        else:
            # a "real" error occurred
            print e
            sys.exit(1)
    else:
        # got a message, do something :)

The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n) or socket.setblocking(False). In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:

import sys
import socket
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)

while True:
    try:
        msg = s.recv(4096)
    except socket.timeout, e:
        err = e.args[0]
        # this next if/else is a bit redundant, but illustrates how the
        # timeout exception is setup
        if err == 'timed out':
            sleep(1)
            print 'recv timed out, retry later'
            continue
        else:
            print e
            sys.exit(1)
    except socket.error, e:
        # Something else happened, handle error, exit, etc.
        print e
        sys.exit(1)
    else:
        if len(msg) == 0:
            print 'orderly shutdown on server end'
            sys.exit(0)
        else:
            # got a message do something :)

As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.

See recv(2) and python socket for more details.

Detecting TCP Client Disconnect

"""
tcp_disconnect.py
Echo network data test program in python. This easily translates to C & Java.

A server program might want to confirm that a tcp client is still connected 
before it sends a data. That is, detect if its connected without reading from socket.
This will demonstrate how to detect a TCP client disconnect without reading data.

The method to do this:
1) select on socket as poll (no wait)
2) if no recv data waiting, then client still connected
3) if recv data waiting, the read one char using PEEK flag 
4) if PEEK data len=0, then client has disconnected, otherwise its connected.
Note, the peek flag will read data without removing it from tcp queue.

To see it in action: 0) run this program on one computer 1) from another computer, 
connect via telnet port 12345, 2) type a line of data 3) wait to see it echo, 
4) type another line, 5) disconnect quickly, 6) watch the program will detect the 
disconnect and exit.

John Masinter, 17-Dec-2008
"""

import socket
import time
import select

HOST = ''       # all local interfaces
PORT = 12345    # port to listen

# listen for new TCP connections
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
# accept new conneciton
conn, addr = s.accept()
print 'Connected by', addr
# loop reading/echoing, until client disconnects
try:
    conn.send("Send me data, and I will echo it back after a short delay.\n")
    while 1:
        data = conn.recv(1024)                          # recv all data queued
        if not data: break                              # client disconnected
        time.sleep(3)                                   # simulate time consuming work
        # below will detect if client disconnects during sleep
        r, w, e = select.select([conn], [], [], 0)      # more data waiting?
        print "select: r=%s w=%s e=%s" % (r,w,e)        # debug output to command line
        if r:                                           # yes, data avail to read.
            t = conn.recv(1024, socket.MSG_PEEK)        # read without remove from queue
            print "peek: len=%d, data=%s" % (len(t),t)  # debug output
            if len(t)==0:                               # length of data peeked 0?
                print "Client disconnected."            # client disconnected
                break                                   # quit program
        conn.send("-->"+data)                           # echo only if still connected
finally:
    conn.close()

Java simple code: java.net.SocketException: Unexpected end of file from server

In my case it was solved just passing proxy to connection. Thanks to @Andreas Panagiotidis.

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

Where to find the complete definition of off_t type?

Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t defined on my machine" is "how is off_t defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.

In this case, off_t isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.

Unfortunately, off_t isn't very rigorously defined. All I could find to define it is on the page on sys/types.h:

blkcnt_t and off_t shall be signed integer types.

This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).


So, I think "where do I find the definition in my header files" isn't the best question. But, for completeness here's the answer:

On my machine (and most machines using glibc) you'll find the definition in bits/types.h (as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:

#include <stdio.h>
#include <sys/types.h>

int main(void) {
  off_t blah;

  return 0;
}

And then:

$ gcc -E sizes.c  | grep __off_t
typedef long int __off_t;
....

However, if you want to know the size of something, you can always use the sizeof() operator.

Edit: Just saw the part of your question about the __. This answer has a good discussion. The key point is that names starting with __ are reserved for the implementation (so you shouldn't start your own definitions with __).

How to connect to a remote Windows machine to execute commands using python?

do the client machines have python loaded? if so, I'm doing this with psexec

On my local machine, I use subprocess in my .py file to call a command line.

import subprocess
subprocess.call("psexec {server} -c {}") 

the -c copies the file to the server so i can run any executable file (which in your case could be a .bat full of connection tests or your .py file from above).

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

What does it mean to bind a multicast (UDP) socket?

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application. (Same holds true for TCP sockets).

When you bind to "0.0.0.0" (INADDR_ANY), you are basically telling the TCP/IP layer to use all available adapters for listening and to choose the best adapter for sending. This is standard practice for most socket code. The only time you wouldn't specify 0 for the IP address is when you want to send/receive on a specific network adapter.

Similarly if you specify a port value of 0 during bind, the OS will assign a randomly available port number for that socket. So I would expect for UDP multicast, you bind to INADDR_ANY on a specific port number where multicast traffic is expected to be sent to.

The "join multicast group" operation (IP_ADD_MEMBERSHIP) is needed because it basically tells your network adapter to listen not only for ethernet frames where the destination MAC address is your own, it also tells the ethernet adapter (NIC) to listen for IP multicast traffic as well for the corresponding multicast ethernet address. Each multicast IP maps to a multicast ethernet address. When you use a socket to send to a specific multicast IP, the destination MAC address on the ethernet frame is set to the corresponding multicast MAC address for the multicast IP. When you join a multicast group, you are configuring the NIC to listen for traffic sent to that same MAC address (in addition to its own).

Without the hardware support, multicast wouldn't be any more efficient than plain broadcast IP messages. The join operation also tells your router/gateway to forward multicast traffic from other networks. (Anyone remember MBONE?)

If you join a multicast group, all the multicast traffic for all ports on that IP address will be received by the NIC. Only the traffic destined for your binded listening port will get passed up the TCP/IP stack to your app. In regards to why ports are specified during a multicast subscription - it's because multicast IP is just that - IP only. "ports" are a property of the upper protocols (UDP and TCP).

You can read more about how multicast IP addresses map to multicast ethernet addresses at various sites. The Wikipedia article is about as good as it gets:

The IANA owns the OUI MAC address 01:00:5e, therefore multicast packets are delivered by using the Ethernet MAC address range 01:00:5e:00:00:00 - 01:00:5e:7f:ff:ff. This is 23 bits of available address space. The first octet (01) includes the broadcast/multicast bit. The lower 23 bits of the 28-bit multicast IP address are mapped into the 23 bits of available Ethernet address space.

Handling a timeout error in python sockets

When you do from socket import * python is loading a socket module to the current namespace. Thus you can use module's members as if they are defined within your current python module.

When you do import socket, a module is loaded in a separate namespace. When you are accessing its members, you should prefix them with a module name. For example, if you want to refer to a socket class, you will need to write client_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM).

As for the problem with timeout - all you need to do is to change except socket.Timeouterror: to except timeout:, since timeout class is defined inside socket module and you have imported all its members to your namespace.

Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

What is the difference between a port and a socket?

A socket address is an IP address & port number

123.132.213.231         # IP address
               :1234    # port number
123.132.213.231:1234    # socket address

A connection occurs when 2 sockets are bound together.

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Official reasons for "Software caused connection abort: socket write error"

ssl client side will throw such exception in below situation(I had tested), :

server is asked to authenticate client certificate, but the client provide a certificate which Extended Key Usage donot support client auth.

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

java.net.SocketException: Connection reset

Embarrassing to say it, but when I had this problem, it was simply a mistake that I was closing the connection before I read all the data. In cases with small strings being returned, it worked, but that was probably due to the whole response was buffered, before I closed it.

In cases of longer amounts of text being returned, the exception was thrown, since more then a buffer was coming back.

You might check for this oversight. Remember opening a URL is like a file, be sure to close it (release the connection) once it has been fully read.

Connecting to TCP Socket from browser using javascript

ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.

ws2s schematic diagram

enter image description here

code sample:

var socket = new WS2S("wss://ws2s.feling.io/").newSocket()

socket.onReady = () => {
  socket.connect("feling.io", 80)
  socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}

socket.onRecv = (data) => {
  console.log('onRecv', data)
}

What's causing my java.net.SocketException: Connection reset?

This error occurs on the server side when the client closed the socket connection before the response could be returned over the socket. In a web app scenario not all of these are dangerous, since they can be created manually. For example, by quitting the browser before the reponse was retrieved.

What is the correct way to read from NetworkStream in .NET

Networking code is notoriously difficult to write, test and debug.

You often have lots of things to consider such as:

  • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

  • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

  • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

Here are several different ways to handle the exchange:

  • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

  • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

  • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

  • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

Each approach has its pros and cons for "correctness".

The code below uses the "timeout" method, as that seems to be the one you want.

See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  // Set a 250 millisecond timeout for reading (instead of Infinite the default)
  stm.ReadTimeout = 250;
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  int bytesread = stm.Read(resp, 0, resp.Length);
  while (bytesread > 0)
  {
      memStream.Write(resp, 0, bytesread);
      bytesread = stm.Read(resp, 0, resp.Length);
  }
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

Instantly detect client disconnection from server socket

Implementing heartbeat into your system might be a solution. This is only possible if both client and server are under your control. You can have a DateTime object keeping track of the time when the last bytes were received from the socket. And assume that the socket not responded over a certain interval are lost. This will only work if you have heartbeat/custom keep alive implemented.

Why is my method undefined for the type object?

The line

Object EchoServer0;

says that you are allocating an Object named EchoServer0. This has nothing to do with the class EchoServer0. Furthermore, the object is not initialized, so EchoServer0 is null. Classes and identifiers have separate namespaces. This will actually compile:

String String = "abc";  // My use of String String was deliberate.

Please keep to the Java naming standards: classes begin with a capital letter, identifiers begin with a small letter, constants and enums are all-capitals.

public final String ME = "Eric Jablow";
public final double GAMMA = 0.5772;
public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
public COLOR background = Color.RED;

Reading inputStream using BufferedReader.readLine() is too slow

I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader's fault. Try measuring this:

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

I think you'll find it's almost exactly the same time as when you're parsing the text.

Note that you should also give InputStreamReader an appropriate encoding - the platform default encoding is almost certainly not what you should be using.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Firstly, I would try a non-secure websocket connection. So remove one of the s's from the connection address:

conn = new WebSocket('ws://localhost:8080');

If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080 both in TCP_IN and TCP_OUT.

What is the largest Safe UDP Packet Size on the Internet

576 is the minimum maximum reassembly buffer size, i.e. each implementation must be able to reassemble packets of at least that size. See IETF RFC 1122 for details.

java.net.SocketTimeoutException: Read timed out under Tomcat

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

What is AF_INET, and why do I need it?

You need arguments like AF_UNIX or AF_INET to specify which type of socket addressing you would be using to implement IPC socket communication. AF stands for Address Family.

As in BSD standard Socket (adopted in Python socket module) addresses are represented as follows:

  1. A single string is used for the AF_UNIX/AF_LOCAL address family. This option is used for IPC on local machines where no IP address is required.

  2. A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer. Used to communicate between processes over the Internet.

AF_UNIX , AF_INET6 , AF_NETLINK , AF_TIPC , AF_CAN , AF_BLUETOOTH , AF_PACKET , AF_RDS are other option which could be used instead of AF_INET.

This thread about the differences between AF_INET and PF_INET might also be useful.

When does socket.recv(recv_size) return?

Yes, your conclusion is correct. socket.recv is a blocking call.

socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

socket.recv will also end with an empty string if the connection is closed or there is an error.

If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

I had issues with socket.setblocking in the past, but feel free to try it if you want.

socket.shutdown vs socket.close

Explanation of shutdown and close: Graceful shutdown (msdn)

Shutdown (in your case) indicates to the other end of the connection there is no further intention to read from or write to the socket. Then close frees up any memory associated with the socket.

Omitting shutdown may cause the socket to linger in the OSs stack until the connection has been closed gracefully.

IMO the names 'shutdown' and 'close' are misleading, 'close' and 'destroy' would emphasise their differences.

How do I debug error ECONNRESET in Node.js?

I also get ECONNRESET error during my development, the way I solve it is by not using nodemon to start my server, just use "node server.js" to start my server fixed my problem.

It's weird, but it worked for me, now I never see the ECONNRESET error again.

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Your local port is using by another app. I faced the same problem! You can try the following step:

  1. Go to command line and run it as administrator!

  2. Type:

    netstat -ano | find ":5000"
    => TCP    0.0.0.0:5000           0.0.0.0:0              LISTENING       4032
       TCP    [::]:5000              [::]:0                 LISTENING       4032
    
  3. Type:

    TASKKILL /F /PID 4032
    

=> SUCCESS: The process with PID 4032 has been terminated.

Note: My 5000 local port was listing by PID 4032. You should give yours!

socket programming multiple client to one server

See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.

Pay attention that accept() is not thread safe, so the call is wrapped within synchronized.

64: synchronized(servSock) {
65:     clientSocket = servSock.accept();
66: }

How do I check if a Socket is currently connected in Java?

Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.

TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.

See Do I need to heartbeat to keep a TCP connection open? for more discussion.

Why am I getting the error "connection refused" in Python? (Sockets)

try this command in terminal:

sudo ufw enable
ufw allow 12397

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

What is the difference between 127.0.0.1 and localhost

The main difference is that the connection can be made via Unix Domain Socket, as stated here: localhost vs. 127.0.0.1

Java socket API: How to tell if a connection has been closed?

On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.

socket.emit() vs. socket.send()

socket.send is implemented for compatibility with vanilla WebSocket interface. socket.emit is feature of Socket.IO only. They both do the same, but socket.emit is a bit more convenient in handling messages.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

This worked for me with Nginx, Node server and Angular 4

Edit your nginx web server config file as:

server {
listen 80;
server_name 52.xx.xxx.xx;

location / {
    proxy_set_header   X-Forwarded-For $remote_addr;
    proxy_set_header   Host $http_host;
    proxy_pass         "http://127.0.0.1:4200";
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
}

How to detect a remote side socket close?

The isConnected method won't help, it will return true even if the remote side has closed the socket. Try this:

public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}

Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.

The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException (broken pipe) will be thrown) on the associated Input/OutputStreams.

Java sending and receiving file (byte[]) over sockets

Adding up on EJP's answer; use this for more fluidity. Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:

int count;
byte[] bytes = new byte[4096];
try {
    while ((count = is.read(bytes)) > 0) {
        System.out.println(count);
        bos.write(bytes, 0, count);
    }
} catch ( Exception e )
{
    //It will land here....
}
// Then continue from here

EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!

Hope this post solves any of your issues

How to check if a socket is connected/disconnected in C#?

As Alexander Logger pointed out in zendars answer, you have to send something to be completely sure. In case your connected partner does not read on this socket at all, you can use the following code.

bool SocketConnected(Socket s)
{
  // Exit if socket is null
  if (s == null)
    return false;
  bool part1 = s.Poll(1000, SelectMode.SelectRead);
  bool part2 = (s.Available == 0);
  if (part1 && part2)
    return false;
  else
  {
    try
    {
      int sentBytesCount = s.Send(new byte[1], 1, 0);
      return sentBytesCount == 1;
    }
    catch
    {
      return false;
    }
  }
}

But even then it might take a few seconds until a broken network cable or something similar is detected.

Python: Binding Socket: "Address already in use"

socket.socket() should run before socket.bind() and use REUSEADDR as said

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

I/O error(socket error): [Errno 111] Connection refused

Use a packet sniffer like Wireshark to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.

If you only see the first packet and the error message comes after several seconds of waiting, the other side is not answering at all (like in: unplugged cable, overloaded server, misguided packet was discarded) and your local network stack aborts the connection attempt. If you see RST packets, the host actually denies the connection. If you see "ICMP Port unreachable" or host unreachable packets, a firewall or the target host inform you of the port actually being closed.

Of course you cannot expect the service to be available at all times (consider all the points of failure in between you and the data), so you should try again later.

Chrome hangs after certain amount of data transfered - waiting for available socket

The message:

Waiting for available socket...

is shown, because you've reached a limit on the ssl_socket_pool either per Host, Proxy or Group.

Here are the maximum number of HTTP connections which you can make with a Chrome browser:

  • The maximum number of connections per proxy is 32 connections. This can be changed in Policy List.
  • Maximum per Host: 6 connections.

    This is likely hardcoded in the source code of the web browser, so you can't change it.

  • Total 256 HTTP connections pooled per browser.

Source: Enterprise networking for Chrome devices

The above limits can be checked or flushed at chrome://net-internals/#sockets (or in real-time at chrome://net-internals/#events&q=type:SOCKET%20is:active).


Your issue with audio can be related to Chrome bug 162627 where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).

Much older issue related to HTML5 video request stay pending, then it's probably related to Issue #234779 which has been fixed 2014. And related to SPDY which can be found in Issue 324653: SPDY issue: waiting for available sockets, but this was already fixed in 2014, so probably it's not related.

Other related issue now marked as duplicate can be found in Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+ which was related to the problem with the media player code leaving a bunch of paused requests hanging around.


This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like Sophos or Kaspersky), so check for Network activity in DevTools.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.

We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.

We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.

When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.

Client on Node.js: Uncaught ReferenceError: require is not defined

ES6: In HTML, include the main JavaScript file using attribute type="module" (browser support):

<script type="module" src="script.js"></script>

And in the script.js file, include another file like this:

import { hello } from './module.js';
...
// alert(hello());

Inside the included file (module.js), you must export the function/class that you will import:

export function hello() {
    return "Hello World";
}

A working example is here. More information is here.

TCP: can two different sockets share a port?

A server socket listens on a single port. All established client connections on that server are associated with that same listening port on the server side of the connection. An established connection is uniquely identified by the combination of client-side and server-side IP/Port pairs. Multiple connections on the same server can share the same server-side IP/Port pair as long as they are associated with different client-side IP/Port pairs, and the server would be able to handle as many clients as available system resources allow it to.

On the client-side, it is common practice for new outbound connections to use a random client-side port, in which case it is possible to run out of available ports if you make a lot of connections in a short amount of time.

Listen to port via a Java socket

You need to use a ServerSocket. You can find an explanation here.

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

What is the difference between AF_INET and PF_INET in socket programming?

Beej's famous network programming guide gives a nice explanation:

In some documentation, you'll see mention of a mystical "PF_INET". This is a weird etherial beast that is rarely seen in nature, but I might as well clarify it a bit here. Once a long time ago, it was thought that maybe a address family (what the "AF" in "AF_INET" stands for) might support several protocols that were referenced by their protocol family (what the "PF" in "PF_INET" stands for).
That didn't happen. Oh well. So the correct thing to do is to use AF_INET in your struct sockaddr_in and PF_INET in your call to socket(). But practically speaking, you can use AF_INET everywhere. And, since that's what W. Richard Stevens does in his book, that's what I'll do here.

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

Difference between socket and websocket?

Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:

Implementors should be aware that this specification is not stable.

Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.

How do I change a TCP socket to be non-blocking?

Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2), poll(2) or some other system calls available on your system.

See The C10K problem for the comparison of approaches to scalable IO multiplexing.

Sending string via socket (python)

client.py

import socket

s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
    str = raw_input("S: ")
    s.send(str.encode());
    if(str == "Bye" or str == "bye"):
        break
    print "N:",s.recv(1024).decode()
s.close()

server.py

import socket

s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
    rcvdData = c.recv(1024).decode()
    print "S:",rcvdData
    sendData = raw_input("N: ")
    c.send(sendData.encode())
    if(sendData == "Bye" or sendData == "bye"):
        break
c.close()

This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

centos: Another MySQL daemon already running with the same unix socket

It's just happen because of abnormal termination of mysql service. delete or take backup of /var/lib/mysql/mysql.sock file and restart mysql.

Please let me know if in case any issue..

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

Testing socket connection in Python

You should really post:

  1. The complete source code of your example
  2. The actual result of it, not a summary

Here is my code, which works:

import socket, sys

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

(family, socktype, proto, garbage, address) = \
         socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)

try:
    s.connect(address) 
except Exception, e:
    alert("Something's wrong with %s. Exception type is %s" % (address, e))

When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:

Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')

An attempt was made to access a socket in a way forbidden by its access permissions

Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.

Understanding INADDR_ANY for socket programming

INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")

Good tool for testing socket connections?

I would go with netcat too , but since you can't use it , here is an alternative : netcat :). You can find netcat implemented in three languages ( python/ruby/perl ) . All you need to do is install the interpreters for the language you choose . Surely , that won't be viewed as a hacking tool .

Here are the links :

Perl implementation

Python implementation

Ruby Implementation

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

IPC performance: Named Pipe vs Socket

Best results you'll get with Shared Memory solution.

Named pipes are only 16% better than TCP sockets.

Results are get with IPC benchmarking:

  • System: Linux (Linux ubuntu 4.4.0 x86_64 i7-6700K 4.00GHz)
  • Message: 128 bytes
  • Messages count: 1000000

Pipe benchmark:

Message size:       128
Message count:      1000000
Total duration:     27367.454 ms
Average duration:   27.319 us
Minimum duration:   5.888 us
Maximum duration:   15763.712 us
Standard deviation: 26.664 us
Message rate:       36539 msg/s

FIFOs (named pipes) benchmark:

Message size:       128
Message count:      1000000
Total duration:     38100.093 ms
Average duration:   38.025 us
Minimum duration:   6.656 us
Maximum duration:   27415.040 us
Standard deviation: 91.614 us
Message rate:       26246 msg/s

Message Queue benchmark:

Message size:       128
Message count:      1000000
Total duration:     14723.159 ms
Average duration:   14.675 us
Minimum duration:   3.840 us
Maximum duration:   17437.184 us
Standard deviation: 53.615 us
Message rate:       67920 msg/s

Shared Memory benchmark:

Message size:       128
Message count:      1000000
Total duration:     261.650 ms
Average duration:   0.238 us
Minimum duration:   0.000 us
Maximum duration:   10092.032 us
Standard deviation: 22.095 us
Message rate:       3821893 msg/s

TCP sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     44477.257 ms
Average duration:   44.391 us
Minimum duration:   11.520 us
Maximum duration:   15863.296 us
Standard deviation: 44.905 us
Message rate:       22483 msg/s

Unix domain sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     24579.846 ms
Average duration:   24.531 us
Minimum duration:   2.560 us
Maximum duration:   15932.928 us
Standard deviation: 37.854 us
Message rate:       40683 msg/s

ZeroMQ benchmark:

Message size:       128
Message count:      1000000
Total duration:     64872.327 ms
Average duration:   64.808 us
Minimum duration:   23.552 us
Maximum duration:   16443.392 us
Standard deviation: 133.483 us
Message rate:       15414 msg/s

How to set timeout on python's socket recv method?

You could set timeout before receiving the response and after having received the response set it back to None:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.settimeout(5.0)
data = sock.recv(1024)
sock.settimeout(None)

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I know this post was posted 5 years ago, but I had this problem recently. It may be cause by corporate network limitations. So my solution is letting WebClient go through proxy server to make the call. Here is the code which worked for me. Hope it helps.

        using (WebClient client = new WebClient())
        {
            client.Encoding = Encoding.UTF8;
            WebProxy proxy = new WebProxy("your proxy host IP", port);
            client.Proxy = proxy;
            string sourceUrl = "xxxxxx";
            try
            {
                using (Stream stream = client.OpenRead(new Uri(noaaSourceUrl)))
                {
                    //......
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

htons() function in socket programing

It has to do with the order in which bytes are stored in memory. The decimal number 5001 is 0x1389 in hexadecimal, so the bytes involved are 0x13 and 0x89. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001 will be stored as

0x89 0x13

The htons() function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order

0x13 0x89

On a little-endian machine, the number with the swapped bytes is 0x8913 in hexadecimal, which is 35091 in decimal notation. Note that if you were working on a big-endian machine, the htons() function would not need to do any swapping since the number would already be stored in the right way in memory.

The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.

Sending a file over TCP sockets in Python

you may change your loop condition according to following code, when length of l is smaller than buffer size it means that it reached end of file

while (True):
    print "Receiving..."
    l = c.recv(1024)        
    f.write(l)
    if len(l) < 1024:
        break

Python send UDP packet

Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.

#!/usr/bin/python

import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))
    fp.close()

main(sys.argv)

The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

$ python send-udp 192.168.1.2 30088

TypeError: 'module' object is not callable

socket is a module, containing the class socket.

You need to do socket.socket(...) or from socket import socket:

>>> import socket
>>> socket
<module 'socket' from 'C:\Python27\lib\socket.pyc'>
>>> socket.socket
<class 'socket._socketobject'>
>>>
>>> from socket import socket
>>> socket
<class 'socket._socketobject'>

This is what the error message means:
It says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it.

Here is a way to logically break down this sort of error:

  • "module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?"
  • "The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?`
  • I should print out what socket is and check print socket

how to create Socket connection in Android?

Simple socket server app example

I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.

This example app runs a server that returns a ROT-1 cypher of the input.

You would then need to add an Exit button + some sleep delays, but this should get you started.

To play with it:

Android sockets are the same as Java's, except we have to deal with some permission issues.

src/com/cirosantilli/android_cheat/socket/Main.java

package com.cirosantilli.android_cheat.socket;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main extends Activity {
    static final String TAG = "AndroidCheatSocket";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(Main.TAG, "onCreate");
        Main.this.startService(new Intent(Main.this, MyService.class));
    }

    public static class MyService extends IntentService {
        public MyService() {
            super("MyService");
        }
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(Main.TAG, "onHandleIntent");
            final int port = 12345;
            ServerSocket listener = null;
            try {
                listener = new ServerSocket(port);
                Log.d(Main.TAG, String.format("listening on port = %d", port));
                while (true) {
                    Log.d(Main.TAG, "waiting for client");
                    Socket socket = listener.accept();
                    Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    for (String inputLine; (inputLine = in.readLine()) != null;) {
                        Log.d(Main.TAG, "received");
                        Log.d(Main.TAG, inputLine);
                        StringBuilder outputStringBuilder = new StringBuilder("");
                        char inputLineChars[] = inputLine.toCharArray();
                        for (char c : inputLineChars)
                            outputStringBuilder.append(Character.toChars(c + 1));
                        out.println(outputStringBuilder);
                    }
                }
            } catch(IOException e) {
                Log.d(Main.TAG, e.toString());
            }
        }
    }
}

We need a Service or other background method or else: How do I fix android.os.NetworkOnMainThreadException?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cirosantilli.android_cheat.socket"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="22" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="AndroidCheatsocket">
        <activity android:name="Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Main$MyService" />
    </application>
</manifest>

We must add: <uses-permission android:name="android.permission.INTERNET" /> or else: Java socket IOException - permission denied

On GitHub with a build.xml: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket

The I/O operation has been aborted because of either a thread exit or an application request

I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).

To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()

Like this :

Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
    ar.AsyncWaitHandle.WaitOne();

Most of the time, ar.IsCompleted will be true.

Sockets: Discover port availability using Java

If you're not too concerned with performance, you could always try listening on a port using the ServerSocket class. If it throws an exception odds are it's being used.

public static boolean isAvailable(int portNr) {
  boolean portFree;
  try (var ignored = new ServerSocket(portNr)) {
      portFree = true;
  } catch (IOException e) {
      portFree = false;
  }
  return portFree;
}

EDIT: If all you're trying to do is select a free port then new ServerSocket(0) will find one for you.

Where does one get the "sys/socket.h" header/source file?

I would like just to add that if you want to use windows socket library you have to :

  • at the beginning : call WSAStartup()

  • at the end : call WSACleanup()

Regards;

Does a TCP socket connection have a "keep alive"?

TCP sockets remain open till they are closed.

That said, it's very difficult to detect a broken connection (broken, as in a router died, etc, as opposed to closed) without actually sending data, so most applications do some sort of ping/pong reaction every so often just to make sure the connection is still actually alive.

How do I find the current machine's full hostname in C (hostname and domain information)?

My solution:

#ifdef WIN32
    #include <Windows.h>
    #include <tchar.h>
#else
    #include <unistd.h>
#endif

void GetMachineName(char machineName[150])
{
    char Name[150];
    int i=0;

    #ifdef WIN32
        TCHAR infoBuf[150];
        DWORD bufCharCount = 150;
        memset(Name, 0, 150);
        if( GetComputerName( infoBuf, &bufCharCount ) )
        {
            for(i=0; i<150; i++)
            {
                Name[i] = infoBuf[i];
            }
        }
        else
        {
            strcpy(Name, "Unknown_Host_Name");
        }
    #else
        memset(Name, 0, 150);
        gethostname(Name, 150);
    #endif
    strncpy(machineName,Name, 150);
}

An existing connection was forcibly closed by the remote host

I've got this exception because of circular reference in entity.In entity that look like

public class Catalog
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public Catalog Parent { get; set; }
    public ICollection<Catalog> ChildCatalogs { get; set; }
}

I added [IgnoreDataMemberAttribute] to the Parent property. And that solved the problem.

Cannot find mysql.sock

I'm getting the same error on Mac OS X 10.11.6:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

After a lot of agonizing and digging through advice here and in related questions, none of which seemed to fix the problem, I went back and deleted the installed folders, and just did brew install mysql.

Still getting the same error with most commands, but this works:

/usr/local/bin/mysqld

and returns:

/usr/local/bin/mysqld: ready for connections.

Version: '5.7.12' socket: '/tmp/mysql.sock' port: 3306 Homebrew

How many socket connections possible?

This depends not only on the operating system in question, but also on configuration, potentially real-time configuration.

For Linux:

cat /proc/sys/fs/file-max

will show the current maximum number of file descriptors total allowed to be opened simultaneously. Check out http://www.cs.uwaterloo.ca/~brecht/servers/openfiles.html

How to convert php array to utf8?

You can send the array to this function:

function utf8_converter($array){
    array_walk_recursive($array, function(&$item, $key){
        if(!mb_detect_encoding($item, 'utf-8', true)){
            $item = utf8_encode($item);
        }
    }); 
    return $array;
}

It works for me.

How to set date format in HTML date input tag?

For Formatting in mm-dd-yyyy

aa=date.split("-")

date=aa[1]+'-'+aa[2]+'-'+aa[0]

Select row with most recent date per user

Query:

SQLFIDDLEExample

SELECT t1.*
FROM lms_attendance t1
WHERE t1.time = (SELECT MAX(t2.time)
                 FROM lms_attendance t2
                 WHERE t2.user = t1.user)

Result:

| ID | USER |       TIME |  IO |
--------------------------------
|  2 |    9 | 1370931664 | out |
|  3 |    6 | 1370932128 | out |
|  5 |   12 | 1370933037 |  in |

Solution which gonna work everytime:

SQLFIDDLEExample

SELECT t1.*
FROM lms_attendance t1
WHERE t1.id = (SELECT t2.id
                 FROM lms_attendance t2
                 WHERE t2.user = t1.user            
                 ORDER BY t2.id DESC
                 LIMIT 1)

How Do I Uninstall Yarn

Try this, it works well on macOS:

$ brew uninstall --force yarn
$ npm uninstall -g yarn
$ yarn -v

v0.24.5 (or your current version)

$ which yarn

/usr/local/bin/yarn

$ rm -rf /usr/local/bin/yarn
$ rm -rf /usr/local/bin/yarnpkg
$ which yarn

yarn not found

$ brew install yarn 
$ brew link yarn
$ yarn -v

v1.17.3 (latest version)

Reading Data From Database and storing in Array List object

Try creating new instance of customer every time e.g.

         while (rs.next()) {

        Customer customer = new Customer();
        customer.setId(rs.getInt("id"));
        customer.setName(rs.getString("name"));

        customer.setAddress(rs.getString("address"));
        customer.setPhone(rs.getString("phone"));
        customer.setEmail(rs.getString("email"));
        customer.setBountPoints(rs.getInt("bonuspoint"));
        customer.setTotalsale(rs.getInt("totalsale"));

        customers.add(customer);


    }

Deleting elements from std::set while iterating

If you run your program through valgrind, you'll see a bunch of read errors. In other words, yes, the iterators are being invalidated, but you're getting lucky in your example (or really unlucky, as you're not seeing the negative effects of undefined behavior). One solution to this is to create a temporary iterator, increment the temp, delete the target iterator, then set the target to the temp. For example, re-write your loop as follows:

std::set<int>::iterator it = numbers.begin();                               
std::set<int>::iterator tmp;                                                

// iterate through the set and erase all even numbers                       
for ( ; it != numbers.end(); )                                              
{                                                                           
    int n = *it;                                                            
    if (n % 2 == 0)                                                         
    {                                                                       
        tmp = it;                                                           
        ++tmp;                                                              
        numbers.erase(it);                                                  
        it = tmp;                                                           
    }                                                                       
    else                                                                    
    {                                                                       
        ++it;                                                               
    }                                                                       
} 

SQL Server : SUM() of multiple rows including where clauses

you mean getiing sum(Amount of all types) for each property where EndDate is null:

SELECT propertyId, SUM(Amount) as TOTAL_COSTS
  FROM MyTable
 WHERE EndDate IS NULL
GROUP BY propertyId

PHP Fatal error: Call to undefined function json_decode()

The same issue with 7.1

apt-get install php7.1-json sudo nano /etc/php/7.1/mods-available/json.ini

  • Add json.so to the new file
  • Add the appropriate sym link under conf.d
  • Restart apache2 service (if needed)

LEFT JOIN only first row

If you can assume that artist IDs increment over time, then the MIN(artist_id) will be the earliest.

So try something like this (untested...)

SELECT *
  FROM feeds f
  LEFT JOIN artists a ON a.artist_id = (
    SELECT
      MIN(fa.artist_id) a_id
    FROM feeds_artists fa 
    WHERE fa.feed_id = f.feed_id
  ) a

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

You can use the fromstring() method for this:

arr = np.array([1, 2, 3, 4, 5, 6])
ts = arr.tostring()
print(np.fromstring(ts, dtype=int))

>>> [1 2 3 4 5 6]

Sorry for the short answer, not enough points for commenting. Remember to state the data types or you'll end up in a world of pain.

Note on fromstring from numpy 1.14 onwards:

sep : str, optional

The string separating numbers in the data; extra whitespace between elements is also ignored.

Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.

Why does DEBUG=False setting make my django Static Files Access fail?

In urls.py I added this line:

from django.views.static import serve 

add those two urls in urlpatterns:

url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), 
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), 

and both static and media files were accesible when DEBUG=FALSE.
Hope it helps :)

MySQL: #126 - Incorrect key file for table

I got this message when writing to a table after reducing the ft_min_word_len (full text min word length). To solve it, re-create the index by repairing the table.

How do I do a HTTP GET in Java?

The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

What's the regular expression that matches a square bracket?

If you want to match an expression starting with [ and ending with ], use \[[^\]]*\].

Importing a GitHub project into Eclipse

When the local git projects are cloned in eclipse and are viewable in git perspective but not in package explorer (workspace), the following steps worked for me:

  • Select the repository in git perspective
  • Right click and select import projects

T-SQL split string based on delimiter

The examples above work fine when there is only one delimiter, but it doesn't scale well for multiple delimiters. Note that this will only work for SQL Server 2016 and above.

/*Some Sample Data*/
DECLARE @mytable TABLE ([id] VARCHAR(10), [name] VARCHAR(1000));
INSERT INTO @mytable
VALUES ('1','John/Smith'),('2','Jane/Doe'), ('3','Steve'), ('4','Bob/Johnson')


/*Split based on delimeter*/
SELECT P.id, [1] 'FirstName', [2] 'LastName', [3] 'Col3', [4] 'Col4'
FROM(
    SELECT A.id, X1.VALUE, ROW_NUMBER() OVER (PARTITION BY A.id ORDER BY A.id) RN
    FROM @mytable A
    CROSS APPLY STRING_SPLIT(A.name, '/') X1
    ) A
PIVOT (MAX(A.[VALUE]) FOR A.RN IN ([1],[2],[3],[4],[5])) P

How to handle screen orientation change when progress dialog and background thread active?

Seems far too 'quick and dirty' to be true so please point out the flaws but what I found worked was...

Within the onPostExecute method of my AsyncTask, I simply wrapped the '.dismiss' for the progress dialog in a try/catch block (with an empty catch) and then simply ignored the exception that was raised. Seems wrong to do but appears there are no ill effects (at least for what I am doing subsequently which is to start another activity passing in the result of my long running query as an Extra)

SQL Server Configuration Manager not found

From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I faced this problem when I copied my images (no matter JPEG or PNG) into the drawable folder manually. There might be different kinds of temporary solutions to this problem, but one best eternal way is to use the Drawable importer plugin for Android studio.

Install it by going to: menu File ? Settings ? Plugins ? Browse Repositories ? search "Drawable". You'll find Drawable importer as the first option. Click install on the right panel.

Use it by right clicking on the Drawable resource folder and then new. Now you can see four new options added to the bottom of the list, and among those you will find your appropriate option. In this case the "Batch drawable import" would do the trick.

BitBucket - download source as ZIP

In case you want to download the repo from your shell/terminal it should work like this:

wget https://user:[email protected]/user-name/repo-name/get/master.tar.bz2

or whatever download URL you might have.

Please make sure the user:password are both URL-encoded. So for instance if your username contains the @ symbol then replace it with %40.

How to make function decorators and chain them together?

Python decorators add extra functionality to another function

An italics decorator could be like

def makeitalic(fn):
    def newFunc():
        return "<i>" + fn() + "</i>"
    return newFunc

Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class

class foo:
    def bar(self):
        print "hi"
    def foobar(self):
        print "hi again"

Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator

def addDashes(fn): # notice it takes a function as an argument
    def newFunction(self): # define a new function
        print "---"
        fn(self) # call the original function
        print "---"
    return newFunction
    # Return the newly defined function - it will "replace" the original

So now I can change my class to

class foo:
    @addDashes
    def bar(self):
        print "hi"

    @addDashes
    def foobar(self):
        print "hi again"

For more on decorators, check http://www.ibm.com/developerworks/linux/library/l-cpdecor.html

Average of multiple columns

You could simply do:

Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID

Right?

I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

Set the text in a span

Give an ID to your span and then change the text of target span.

$("#StatusTitle").text("Info");
$("#StatusTitleIcon").removeClass("fa-exclamation").addClass("fa-info-circle"); 

<i id="StatusTitleIcon" class="fa fa-exclamation fa-fw"></i>
<span id="StatusTitle">Error</span>

Here "Error" text will become "Info" and their fontawesome icons will be changed as well.

How to install a specific JDK on Mac OS X?

Compiling with -source 1.5 -target 1.5 (in a JDK 6 environment) will honor only language elements that were in 1.5 and prior. Great. But there were no language changes in 6 anyway. Problem with this approach (on Mac with 1.6) is that using classes that came AFTER 1.5 will still compile because they exist in the rt.jar. So one could run in a 1.5 env and get a class not found exception with no prior warning when compiling. I found this out the hard way with javax.swing.event.RowSorterEvent/Listener. Both entered "Since 1.6" but are not caught with -source 1.5

MongoDB Show all contents from all collections

This will do:

db.getCollectionNames().forEach(c => {
    db[c].find().forEach(d => {
        print(c); 
        printjson(d)
    })
})

Enable/Disable Anchor Tags using AngularJS

You can create a custom directive that is somehow similar to ng-disabled and disable a specific set of elements by:

  1. watching the property changes of the custom directive, e.g. my-disabled.
  2. clone the current element without the added event handlers.
  3. add css properties to the cloned element and other attributes or event handlers that will provide the disabled state of an element.
  4. when changes are detected on the watched property, replace the current element with the cloned element.

HTML

   <a my-disabled="disableCreate" href="#" ng-click="disableEdit = true">CREATE</a><br/>
   <a my-disabled="disableEdit" href="#" ng-click="disableCreate = true">EDIT</a><br/>
   <a my-disabled="disableCreate || disableEdit" href="#">DELETE</a><br/>
   <a href="#" ng-click="disableEdit = false; disableCreate = false;">RESET</a>

JAVASCRIPT

directive('myDisabled', function() {
  return {

    link: function(scope, elem, attr) {
      var color = elem.css('color'),
          textDecoration = elem.css('text-decoration'),
          cursor = elem.css('cursor'),
          // double negation for non-boolean attributes e.g. undefined
          currentValue = !!scope.$eval(attr.myDisabled),

          current = elem[0],
          next = elem[0].cloneNode(true);

      var nextElem = angular.element(next);

      nextElem.on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
      });

      nextElem.css('color', 'gray');
      nextElem.css('text-decoration', 'line-through');
      nextElem.css('cursor', 'not-allowed');
      nextElem.attr('tabindex', -1);

      scope.$watch(attr.myDisabled, function(value) {
        // double negation for non-boolean attributes e.g. undefined
        value = !!value;

        if(currentValue != value) {
          currentValue = value;
          current.parentNode.replaceChild(next, current);
          var temp = current;
          current = next;
          next = temp;
        }

      })
    }
  }
});

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

Best way to detect when a user leaves a web page?

One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.

Of course this won't work if the user simply closes the browser window or types in a new URL.

To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).

Determine the line of code that causes a segmentation fault?

All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.

If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.

It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)

iOS: present view controller programmatically

your code :

 AddTaskViewController *add = [[AddTaskViewController alloc] init];
 [self presentViewController:add animated:YES completion:nil];

this code can goes to the other controller , but you get a new viewController , not the controller of your storyboard, you can do like this :

AddTaskViewController *add = [self.storyboard instantiateViewControllerWithIdentifier:@"YourStoryboardID"];
[self presentViewController:add animated:YES completion:nil];

Are arrays passed by value or passed by reference in Java?

No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

How to create directory automatically on SD card

Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)

not allowed characters in file/folder names

" * / : < > ? \ |

U may find this code helpful in such a case.

The below code removes all ":" and replaces them with "-"

//actualFileName = "qwerty:asdfg:zxcvb" say...

    String[] tempFileNames;
    String tempFileName ="";
    String delimiter = ":";
    tempFileNames = actualFileName.split(delimiter);
    tempFileName = tempFileNames[0];
    for (int j = 1; j < tempFileNames.length; j++){
        tempFileName = tempFileName+" - "+tempFileNames[j];
    }
    File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
    if (!file.exists()) {
        if (!file.mkdirs()) {
        Log.e("TravellerLog :: ", "Problem creating Image folder");
        }
    }

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

invalid new-expression of abstract class type

Another possible cause for future Googlers

I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue) as a parameter, but the Queue class is abstract. I solved that by using a QueuePtr(myQueue) constructor like so:

using QueuePtr = std::unique_ptr<Queue>;

and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue when you make a std::unique_ptr of its type, which can't happen.

Bootstrap 4: Multilevel Dropdown Inside Navigation

Updated 2018

Here is another variation on the Bootstrap 4.1 Navbar with multi-level dropdown. This one uses minimal CSS for the submenu, and can be re-positioned as desired:

enter image description here

https://www.codeply.com/go/nG6iMAmI2X

.dropdown-submenu {
  position: relative;
}

.dropdown-submenu .dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -1px;
}

jQuery to control display of submenus:

$('.dropdown-submenu > a').on("click", function(e) {
    var submenu = $(this);
    $('.dropdown-submenu .dropdown-menu').removeClass('show');
    submenu.next('.dropdown-menu').addClass('show');
    e.stopPropagation();
});

$('.dropdown').on("hidden.bs.dropdown", function() {
    // hide any open menus when parent closes
    $('.dropdown-menu.show').removeClass('show');
});

See this answer for activating the Bootstrap 4 submenus on hover

how to display employee names starting with a and then b in sql

To get employee names starting with A or B listed in order...

select employee_name 
from employees
where employee_name LIKE 'A%' OR employee_name LIKE 'B%'
order by employee_name

If you are using Microsoft SQL Server you could use

....
where employee_name  LIKE '[A-B]%'
order by employee_name

This is not standard SQL though it just gets translated to the following which is.

WHERE  employee_name >= 'A'
       AND employee_name < 'C' 

For all variants you would need to consider whether you want to include accented variants such as Á and test whether the queries above do what you want with these on your RDBMS and collation options.

What is 0x10 in decimal?

0xNNNN (not necessarily four digits) represents, in C at least, a hexadecimal (base-16 because 'hex' is 6 and 'dec' is 10 in Latin-derived languages) number, where N is one of the digits 0 through 9 or A through F (or their lower case equivalents, either representing 10 through 15), and there may be 1 or more of those digits in the number. The other way of representing it is NNNN16.

It's very useful in the computer world as a single hex digit represents four bits (binary digits). That's because four bits, each with two possible values, gives you a total of 2 x 2 x 2 x 2 or 16 (24) values. In other words:

  _____________________________________bits____________________________________
 /                                                                             \
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| bF | bE | bD | bC | bB | bA | b9 | b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 | b0 |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
 \_________________/ \_________________/ \_________________/ \_________________/ 
      Hex digit           Hex digit           Hex digit           Hex digit

A base-X number is a number where each position represents a multiple of a power of X.


In base 10, which we humans are used to, the digits used are 0 through 9, and the number 730410 is:

  • (7 x 103) = 700010 ; plus
  • (3 x 102) = 30010 ; plus
  • (0 x 101) = 010 ; plus
  • (4 x 100) = 410 ; equals 7304.

In octal, where the digits are 0 through 7. the number 7548 is:

  • (7 x 82) = 44810 ; plus
  • (5 x 81) = 4010 ; plus
  • (4 x 80) = 410 ; equals 49210.

Octal numbers in C are preceded by the character 0 so 0123 is not 123 but is instead (1 * 64) + (2 * 8) + 3, or 83.


In binary, where the digits are 0 and 1. the number 10112 is:

  • (1 x 23) = 810 ; plus
  • (0 x 22) = 010 ; plus
  • (1 x 21) = 210 ; plus
  • (1 x 20) = 110 ; equals 1110.

In hexadecimal, where the digits are 0 through 9 and A through F (which represent the "digits" 10 through 15). the number 7F2416 is:

  • (7 x 163) = 2867210 ; plus
  • (F x 162) = 384010 ; plus
  • (2 x 161) = 3210 ; plus
  • (4 x 160) = 410 ; equals 3254810.

Your relatively simple number 0x10, which is the way C represents 1016, is simply:

  • (1 x 161) = 1610 ; plus
  • (0 x 160) = 010 ; equals 1610.

As an aside, the different bases of numbers are used for many things.

  • base 10 is used, as previously mentioned, by we humans with 10 digits on our hands.
  • base 2 is used by computers due to the relative ease of representing the two binary states with electrical circuits.
  • base 8 is used almost exclusively in UNIX file permissions so that each octal digit represents a 3-tuple of binary permissions (read/write/execute). It's also used in C-based languages and UNIX utilities to inject binary characters into an otherwise printable-character-only data stream.
  • base 16 is a convenient way to represent four bits to a digit, especially as most architectures nowadays have a word size which is a multiple of four bits.
  • base 64 is used in encoding mail so that binary files may be sent using only printable characters. Each digit represents six binary digits so you can pack three eight-bit characters into four six-bit digits (25% increased file size but guaranteed to get through the mail gateways untouched).
  • as a semi-useful snippet, base 60 comes from some very old civilisation (Babylon, Sumeria, Mesopotamia or something like that) and is the source of 60 seconds/minutes in the minute/hour, 360 degrees in a circle, 60 minutes (of arc) in a degree and so on [not really related to the computer industry, but interesting nonetheless].
  • as an even less-useful snippet, the ultimate question and answer in The Hitchhikers Guide To The Galaxy was "What do you get when you multiply 6 by 9?" and "42". Whilst same say this is because the Earth computer was faulty, others see it as proof that the creator has 13 fingers :-)

Proper Linq where clauses

Looking under the hood, the two statements will be transformed into different query representations. Depending on the QueryProvider of Collection, this might be optimized away or not.

When this is a linq-to-object call, multiple where clauses will lead to a chain of IEnumerables that read from each other. Using the single-clause form will help performance here.

When the underlying provider translates it into a SQL statement, the chances are good that both variants will create the same statement.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

I was running into a similar error in pywikipediabot. The .decode method is a step in the right direction but for me it didn't work without adding 'ignore':

ignore_encoding = lambda s: s.decode('utf8', 'ignore')

Ignoring encoding errors can lead to data loss or produce incorrect output. But if you just want to get it done and the details aren't very important this can be a good way to move faster.

How to create a label inside an <input> element?

Please use PlaceHolder.JS its works in all browsers and very easy for non html5 compliant browsers http://jamesallardice.github.io/Placeholders.js/

How do I get the HTML code of a web page in PHP?

$output = file("http://www.example.com"); didn't work until I enabled: allow_url_fopen, allow_url_include, and file_uploads in php.ini for PHP7

How to determine if a number is odd in JavaScript

Use the bitwise AND operator.

_x000D_
_x000D_
function oddOrEven(x) {_x000D_
  return ( x & 1 ) ? "odd" : "even";_x000D_
}_x000D_
_x000D_
function checkNumber(argNumber) {_x000D_
  document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);_x000D_
}_x000D_
 _x000D_
checkNumber(17);
_x000D_
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>
_x000D_
_x000D_
_x000D_

If you don't want a string return value, but rather a boolean one, use this:

var isOdd = function(x) { return x & 1; };
var isEven  = function(x) { return !( x & 1 ); };

Python re.sub replace with matched content

Use \1 instead of $1.

\number Matches the contents of the group of the same number.

http://docs.python.org/library/re.html#regular-expression-syntax

SQL Server Restore Error - Access is Denied

The backup creator had MSSql version 10 installed, so when he took the backup it also stores the original file path (to be able to restore it in same location), but I had version 11, so it could not find the destination directory.

So I changed the output file directory to C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\, and it was able to restore the database successfully.

Source

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

Double value to round up in Java

You could try defining a new DecimalFormat and using it as a Double result to a new double variable.

Example given to make you understand what I just said.

double decimalnumber = 100.2397;
DecimalFormat dnf = new DecimalFormat( "#,###,###,##0.00" );
double roundednumber = new Double(dnf.format(decimalnumber)).doubleValue();

Import CSV file into SQL Server

I know this is not the exact solution to the question above, but for me, it was a nightmare when I was trying to Copy data from one database located at a separate server to my local.

I was trying to do that by first export data from the Server to CSV/txt and then import it to my local table.

Both solutions: with writing down the query to import CSV or using the SSMS Import Data wizard was always producing errors (errors were very general, saying that there is parsing problem). And although I wasn't doing anything special, just export to CSV and then trying to import CSV to the local DB, the errors were always there.

I was trying to look at the mapping section and the data preview, but there was always a big mess. And I know the main problem was comming from one of the table columns, which was containing JSON and SQL parser was treating that wrongly.

So eventually, I came up with a different solution and want to share it in case if someone else will have a similar problem.


What I did is that I've used the Exporting Wizard on the external Server.

Here are the steps to repeat the same process:
1) Right click on the database and select Tasks -> Export Data...

2) When Wizard will open, choose Next and in the place of "Data Source:" choose "SQL Server Native Client".

enter image description here

In case of external Server you will most probably have to choose "Use SQL Server Authentication" for the "Authentication Mode:".

3) After hitting Next, you have to select the Destionation.
For that, select again "SQL Server Native Client".
This time you can provide your local (or some other external DB) DB.

enter image description here

4) After hitting the Next button, you have two options either to copy the entire table from one DB to another or write down the query to specify the exact data to be copied. In my case, I didn't need the entire table (it was too large), but just some part of it, so I've chosen "Write a query to specify the data to transfer".

enter image description here

I would suggest writing down and testing the query on a separate query editor before moving to Wizard.

5) And finally, you need to specify the destination table where the data will be selected.

enter image description here

I suggest to leave it as [dbo].[Query] or some custom Table name in case if you will have errors exporting the data or if you are not sure about the data and want further analyze it before moving to the exact table you want.

And now go straight to the end of the Wizard by hitting Next/Finish buttons.

Check if event exists on element

use jquery event filter

you can use it like this

$("a:Event(click)")

Get a worksheet name using Excel VBA

Sub FnGetSheetsName()

    Dim mainworkBook As Workbook

    Set mainworkBook = ActiveWorkbook

    For i = 1 To mainworkBook.Sheets.Count

    'Either we can put all names in an array , here we are printing all the names in Sheet 2

    mainworkBook.Sheets("Sheet2").Range("A" & i) = mainworkBook.Sheets(i).Name

    Next i

End Sub

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is the standard environment variable that some servers and other java apps append to the call that executes the java command.

For example in tomcat if you define JAVA_OPTS='-Xmx1024m', the startup script will execute java org.apache.tomcat.Servert -Xmx1024m

If you are running in Linux/OSX, you can set the JAVA_OPTS, right before you call the startup script by doing

JAVA_OPTS='-Djava.awt.headless=true'

This will only last as long as the console is open. To make it more permanent you can add it to your ~/.profile or ~/.bashrc file.

Css transition from display none to display block, navigation with subnav

As you know the display property cannot be animated BUT just by having it in your CSS it overrides the visibility and opacity transitions.

The solution...just removed the display properties.

_x000D_
_x000D_
nav.main ul ul {_x000D_
  position: absolute;_x000D_
  list-style: none;_x000D_
  opacity: 0;_x000D_
  visibility: hidden;_x000D_
  padding: 10px;_x000D_
  background-color: rgba(92, 91, 87, 0.9);_x000D_
  -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
  transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
  <ul>_x000D_
    <li>_x000D_
      <a href="">Lorem</a>_x000D_
      <ul>_x000D_
        <li><a href="">Ipsum</a>_x000D_
        </li>_x000D_
        <li><a href="">Dolor</a>_x000D_
        </li>_x000D_
        <li><a href="">Sit</a>_x000D_
        </li>_x000D_
        <li><a href="">Amet</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

how to use jQuery ajax calls with node.js

I suppose your html page is hosted on a different port. Same origin policy requires in most browsers that the loaded file be on the same port than the loading file.

Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

Delete ActionLink with confirm dialog

those are routes you're passing in

<%= Html.ActionLink("Delete", "Delete",
    new { id = item.storyId }, 
    new { onclick = "return confirm('Are you sure you wish to delete this article?');" })     %>

The overloaded method you're looking for is this one:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    Object routeValues,
    Object htmlAttributes
)

http://msdn.microsoft.com/en-us/library/dd492124.aspx

How can you sort an array without mutating the original array?

You can use slice with no arguments to copy an array:

var foo,
    bar;
foo = [3,1,2];
bar = foo.slice().sort();

How to embed PDF file with responsive width

<object data="resume.pdf" type="application/pdf" width="100%" height="800px"> 
   <p>It appears you don't have a PDF plugin for this browser.
       No biggie... you can <a href="resume.pdf">click here to
       download the PDF file.</a>
  </p>  
</object>

What does jQuery.fn mean?

jQuery.fn is defined shorthand for jQuery.prototype. From the source code:

jQuery.fn = jQuery.prototype = {
    // ...
}

That means jQuery.fn.jquery is an alias for jQuery.prototype.jquery, which returns the current jQuery version. Again from the source code:

// The current version of jQuery being used
jquery: "@VERSION",

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

Conditional statement in a one line lambda function in python?

By the time you say rate = lambda whatever... you've defeated the point of lambda and should just define a function. But, if you want a lambda, you can use 'and' and 'or'

lambda(T): (T>200) and (200*exp(-T)) or (400*exp(-T))

How do I force files to open in the browser instead of downloading (PDF)?

This is for ASP.NET MVC

In your cshtml page:

<section>
    <h4><a href="@Url.Action("Download", "Document", new { id = @Model.GUID })"><i class="fa fa-download"></i> @Model.Name</a></h4>
    <object data="@Url.Action("View", "Document", new { id = @Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
        <h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
    </object>
</section>

In your controller:

public ActionResult Download(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        return File(model.FilePath, "application/pdf", model.FileName);
    }

public FileStreamResult View(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);

        return File(fs, "application/pdf");
    }

In javascript, how do you search an array for a substring match

People here are making this waaay too difficult. Just do the following...

myArray.findIndex(element => element.includes("substring"))

findIndex() is an ES6 higher order method that iterates through the elements of an array and returns the index of the first element that matches some criteria (provided as a function). In this case I used ES6 syntax to declare the higher order function. element is the parameter of the function (which could be any name) and the fat arrow declares what follows as an anonymous function (which does not need to be wrapped in curly braces unless it takes up more than one line).

Within findIndex() I used the very simple includes() method to check if the current element includes the substring that you want.

Open Google Chrome from VBA/Excel

The answer given by @ray above works perfectly, but make sure you are using the right path to open up the file. If you right click on your icon and click properties, you should see where the actual path is, just copy past that and it should work.

Properties

C# binary literals

Update

C# 7.0 now has binary literals, which is awesome.

[Flags]
enum Days
{
    None = 0,
    Sunday    = 0b0000001,
    Monday    = 0b0000010,   // 2
    Tuesday   = 0b0000100,   // 4
    Wednesday = 0b0001000,   // 8
    Thursday  = 0b0010000,   // 16
    Friday    = 0b0100000,   // etc.
    Saturday  = 0b1000000,
    Weekend = Saturday | Sunday,
    Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}

Original Post

Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (<<) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums.

[Flags]
enum Days
{
    None        = 0,
    Sunday      = 1,
    Monday      = 1 << 1,   // 2
    Tuesday     = 1 << 2,   // 4
    Wednesday   = 1 << 3,   // 8
    Thursday    = 1 << 4,   // 16
    Friday      = 1 << 5,   // etc.
    Saturday    = 1 << 6,
    Weekend     = Saturday | Sunday,
    Weekdays    = Monday | Tuesday | Wednesday | Thursday | Friday
}

How to fix 'sudo: no tty present and no askpass program specified' error?

I was able to get this done but please make sure to follow the steps properly. This is for the anyone who is getting import errors.

Step1: Check if files and folders have got execute permission issue. Linux user use:

chmod 777 filename

Step2: Check which user has the permission to execute it.

Step3: open terminal type this command.

sudo visudo

add this lines to the code below

www-data ALL=(ALL) NOPASSWD:ALL
nobody ALL=(ALL) NOPASSWD:/ALL

this is to grant permission to execute the script and allow it to use all the libraries. The user generally is 'nobody' or 'www-data'.

now edit your code as

echo shell_exec('sudo -u the_user_of_the_file python your_file_name.py 2>&1');

go to terminal to check if the process is running type this there...

ps aux | grep python

this will output all the process running in python.

Add Ons: use the below code to check the users in your system

cut -d: -f1 /etc/passwd

Thank You!

How can I change the class of an element with jQuery>

Use jQuery's

$(this).addClass('showhideExtra_up_hover');

and

$(this).addClass('showhideExtra_down_hover');

Which are more performant, CTE or temporary tables?

Late to the party, but...

The environment I work in is highly constrained, supporting some vendor products and providing "value-added" services like reporting. Due to policy and contract limitations, I am not usually allowed the luxury of separate table/data space and/or the ability to create permanent code [it gets a little better, depending upon the application].

IOW, I can't usually develop a stored procedure or UDFs or temp tables, etc. I pretty much have to do everything through MY application interface (Crystal Reports - add/link tables, set where clauses from w/in CR, etc.). One SMALL saving grace is that Crystal allows me to use COMMANDS (as well as SQL Expressions). Some things that aren't efficient through the regular add/link tables capability can be done by defining a SQL Command. I use CTEs through that and have gotten very good results "remotely". CTEs also help w/ report maintenance, not requiring that code be developed, handed to a DBA to compile, encrypt, transfer, install, and then require multiple-level testing. I can do CTEs through the local interface.

The down side of using CTEs w/ CR is, each report is separate. Each CTE must be maintained for each report. Where I can do SPs and UDFs, I can develop something that can be used by multiple reports, requiring only linking to the SP and passing parameters as if you were working on a regular table. CR is not really good at handling parameters into SQL Commands, so that aspect of the CR/CTE aspect can be lacking. In those cases, I usually try to define the CTE to return enough data (but not ALL data), and then use the record selection capabilities in CR to slice and dice that.

So... my vote is for CTEs (until I get my data space).

How to make a form close when pressing the escape key?

You can set a property on the form to do this for you if you have a button on the form that closes the form already.

Set the CancelButton property of the form to that button.

Gets or sets the button control that is clicked when the user presses the Esc key.

If you don't have a cancel button then you'll need to add a KeyDown handler and check for the Esc key in that:

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}

You will also have to set the KeyPreview property to true.

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the ProcessDialogKey method as follows:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

Get model's fields in Django

Now there is special method - get_fields()

    >>> from django.contrib.auth.models import User
    >>> User._meta.get_fields()

It accepts two parameters that can be used to control which fields are returned:

  • include_parents

    True by default. Recursively includes fields defined on parent classes. If set to False, get_fields() will only search for fields declared directly on the current model. Fields from models that directly inherit from abstract models or proxy classes are considered to be local, not on the parent.

  • include_hidden

    False by default. If set to True, get_fields() will include fields that are used to back other field’s functionality. This will also include any fields that have a related_name (such as ManyToManyField, or ForeignKey) that start with a “+”

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

String compare in Perl with "eq" vs "=="

First, eq is for comparing strings; == is for comparing numbers.

Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.

I think your problem is that your variables don't contain what you think they do. I think your $str1 or $str2 contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";.

The trailing newline can be removed with the chomp($str1); function.

flow 2 columns of text automatically with CSS

This solution will split into two columns and divide the content half in one line half in the other. This comes in handy if you are working with data that gets loaded into the first column, and want it to flow evenly every time. :). You can play with the amount that gets put into the first col. This will work with lists as well.

Enjoy.

<html>
<head>
<title>great script for dividing things into cols</title>



    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script>
$(document).ready(function(){

var count=$('.firstcol span').length;
var selectedIndex =$('.firstcol span').eq(count/2-1);
var selectIndexafter=selectedIndex.nextAll();


if (count>1)
{
selectIndexafter.appendTo('.secondcol');
}

 });

</script>
<style>
body{font-family:arial;}
.firstcol{float:left;padding-left:100px;}
.secondcol{float:left;color:blue;position:relative;top:-20;px;padding-left:100px;}
.secondcol h3 {font-size:18px;font-weight:normal;color:grey}
span{}
</style>

</head>
<body>

<div class="firstcol">

<span>1</span><br />
<span>2</span><br />
<span>3</span><br />
<span>4</span><br />
<span>5</span><br />
<span>6</span><br />
<span>7</span><br />
<span>8</span><br />
<span>9</span><br />
<span>10</span><br />
<!--<span>11</span><br />
<span>12</span><br />
<span>13</span><br />
<span>14</span><br />
<span>15</span><br />
<span>16</span><br />
<span>17</span><br />
<span>18</span><br />
<span>19</span><br />
<span>20</span><br />
<span>21</span><br />
<span>22</span><br />
<span>23</span><br />
<span>24</span><br />
<span>25</span><br />-->
</div>


<div class="secondcol">


</div>


</body>

</html>

How to build a query string for a URL in C#?

Here's a fluent/lambda-ish way as an extension method (combining concepts in previous posts) that supports multiple values for the same key. My personal preference is extensions over wrappers for discover-ability by other team members for stuff like this. Note that there's controversy around encoding methods, plenty of posts about it on Stack Overflow (one such post) and MSDN bloggers (like this one).

public static string ToQueryString(this NameValueCollection source)
{
    return String.Join("&", source.AllKeys
        .SelectMany(key => source.GetValues(key)
            .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))))
        .ToArray());
}

edit: with null support, though you'll probably need to adapt it for your particular situation

public static string ToQueryString(this NameValueCollection source, bool removeEmptyEntries)
{
    return source != null ? String.Join("&", source.AllKeys
        .Where(key => !removeEmptyEntries || source.GetValues(key)
            .Where(value => !String.IsNullOrEmpty(value))
            .Any())
        .SelectMany(key => source.GetValues(key)
            .Where(value => !removeEmptyEntries || !String.IsNullOrEmpty(value))
            .Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
        .ToArray())
        : string.Empty;
}

Simple pthread! C++

You should declare the thread main as:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it

HTML 5 video or audio playlist

You can add an event listener with 'ended' as the first param

Like this :

https://stackoverflow.com/a/2880950/6839331

Format the date using Ruby on Rails

Easiest is to use strftime (docs).

If it's for use on the view side, better to wrap it in a helper, though.

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

What is the most elegant way to check if all values in a boolean array are true?

In Java 8+, you can create an IntStream in the range of 0 to myArray.length and check that all values are true in the corresponding (primitive) array with something like,

return IntStream.range(0, myArray.length).allMatch(i -> myArray[i]);

View tabular file such as CSV from command line

Tabview is really good. Worked with 200+MB files that displayed nicely which were buggy with LibreOffice as well as csv plugin in gvim.

The Anaconda version is available here: https://anaconda.org/bioconda/tabview

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

you can delete the corresponding failed artifact directory in you local repository. And also you can simply use the -U in the goal. It will do the work. This works with maven 3. So no need to downgrade to maven 2.

Move an item inside a list?

I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:

+---------------------------------+
¦ 14.4usec ¦ x[i:i]=x.pop(j),     ¦
¦ 14.5usec ¦ x[i:i]=[x.pop(j)]    ¦
¦ 15.2usec ¦ x.insert(i,x.pop(j)) ¦
+---------------------------------+

and here the ones to use if j<=i:

+--------------------------------------+
¦ 14.4usec ¦ x[i:i]=x[j],;del x[j]     ¦
¦ 14.4usec ¦ x[i:i]=[x[j]];del x[j]    ¦
¦ 15.4usec ¦ x.insert(i,x[j]);del x[j] ¦
+--------------------------------------+

Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.

Private properties in JavaScript ES6 classes

In fact it is possible using Symbols and Proxies. You use the symbols in the class scope and set two traps in a proxy: one for the class prototype so that the Reflect.ownKeys(instance) or Object.getOwnPropertySymbols doesn't give your symbols away, the other one is for the constructor itself so when new ClassName(attrs) is called, the instance returned will be intercepted and have the own properties symbols blocked. Here's the code:

_x000D_
_x000D_
const Human = (function() {_x000D_
  const pet = Symbol();_x000D_
  const greet = Symbol();_x000D_
_x000D_
  const Human = privatizeSymbolsInFn(function(name) {_x000D_
    this.name = name; // public_x000D_
    this[pet] = 'dog'; // private _x000D_
  });_x000D_
_x000D_
  Human.prototype = privatizeSymbolsInObj({_x000D_
    [greet]() { // private_x000D_
      return 'Hi there!';_x000D_
    },_x000D_
    revealSecrets() {_x000D_
      console.log(this[greet]() + ` The pet is a ${this[pet]}`);_x000D_
    }_x000D_
  });_x000D_
_x000D_
  return Human;_x000D_
})();_x000D_
_x000D_
const bob = new Human('Bob');_x000D_
_x000D_
console.assert(bob instanceof Human);_x000D_
console.assert(Reflect.ownKeys(bob).length === 1) // only ['name']_x000D_
console.assert(Reflect.ownKeys(Human.prototype).length === 1 ) // only ['revealSecrets']_x000D_
_x000D_
_x000D_
// Setting up the traps inside proxies:_x000D_
function privatizeSymbolsInObj(target) { _x000D_
  return new Proxy(target, { ownKeys: Object.getOwnPropertyNames });_x000D_
}_x000D_
_x000D_
function privatizeSymbolsInFn(Class) {_x000D_
  function construct(TargetClass, argsList) {_x000D_
    const instance = new TargetClass(...argsList);_x000D_
    return privatizeSymbolsInObj(instance);_x000D_
  }_x000D_
  return new Proxy(Class, { construct });_x000D_
}
_x000D_
_x000D_
_x000D_

Reflect.ownKeys() works like so: Object.getOwnPropertyNames(myObj).concat(Object.getOwnPropertySymbols(myObj)) that's why we need a trap for these objects.

undefined reference to WinMain@16 (codeblocks)

Open the project you want to add it.

Right click on the name. Then select, add in the active project. Then the cpp file will get its link to cbp.

Xcode 7.2 no matching provisioning profiles found

For me nothing above worked with XCode 7.3.1 because I had nothing in provisioning profiles (expired). I had to connect my iPhone to Mac and then click on Fix provisioning profile which created another profile expires in a week.

Convert data.frame column to a vector?

a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)
avector <- as.vector(aframe['a2'])

avector<-unlist(avector)
#this will return a vector of type "integer"

Correct way to import lodash

Import specific methods inside of curly brackets

import { map, tail, times, uniq } from 'lodash';

Pros:

  • Only one import line(for a decent amount of functions)
  • More readable usage: map() instead of _.map() later in the javascript code.

Cons:

  • Every time we want to use a new function or stop using another - it needs to be maintained and managed

Copied from:The Correct Way to Import Lodash Libraries - A Benchmark article written by Alexander Chertkov.

How to get the seconds since epoch from the time + date output of gmtime()?

Note that time.gmtime maps timestamp 0 to 1970-1-1 00:00:00.

In [61]: import time       
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

time.mktime(time.gmtime(0)) gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.

In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0

The inverse of time.gmtime is calendar.timegm:

In [62]: import calendar    
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0

Where can I find documentation on formatting a date in JavaScript?

The correct way to format a date to return "2012-12-29" is with the script from JavaScript Date Format:

var d1 = new Date();
return d1.format("dd-m-yy");

This code does NOT work:

var d1 = new Date();
d1.toString('yyyy-MM-dd');      

How do I scroll the UIScrollView when the keyboard appears?

I used this answer supplied by Sudheer Palchuri https://stackoverflow.com/users/2873919/sudheer-palchuri https://stackoverflow.com/a/32583809/6193496

In ViewDidLoad, register the notifications:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetailsViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetailsViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil)

Add below observer methods which does the automatic scrolling when keyboard appears.

func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

func keyboardWillShow(notification:NSNotification){

var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)

var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
self.scrollView.contentInset = contentInset
}

func keyboardWillHide(notification:NSNotification){

var contentInset:UIEdgeInsets = UIEdgeInsetsZero
self.scrollView.contentInset = contentInset
}

How to see what privileges are granted to schema of another user

Use example with from the post of Szilágyi Donát.

I use two querys, one to know what roles I have, excluding connect grant:

SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema

Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:

SELECT * FROM ALL_TAB_PRIVS WHERE GRANTEE='ROLE_OPS_CUSTOMERS'; -- Objects granted at role.

The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).

Regards.

How to print a double with two decimals in Android?

Before you use DecimalFormat you need to use the following import or your code will not work:

import java.text.DecimalFormat;

The code for formatting is:

DecimalFormat precision = new DecimalFormat("0.00"); 
// dblVariable is a number variable and not a String in this case
txtTextField.setText(precision.format(dblVariable));

Python logging: use milliseconds in time format

If you are using arrow or if you don't mind using arrow. You can substitute python's time formatting for arrow's one.

import logging

from arrow.arrow import Arrow


class ArrowTimeFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)


logger = logging.getLogger(__name__)

default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
    fmt='%(asctime)s',
    datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))

logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)

Now you can use all of arrow's time formatting in datefmt attribute.

How to Convert Int to Unsigned Byte and Back

The Integer.toString(size) call converts into the char representation of your integer, i.e. the char '5'. The ASCII representation of that character is the value 65.

You need to parse the string back to an integer value first, e.g. by using Integer.parseInt, to get back the original int value.

As a bottom line, for a signed/unsigned conversion, it is best to leave String out of the picture and use bit manipulation as @JB suggests.

S3 Static Website Hosting Route All Paths to Index.html

It's tangential, but here's a tip for those using Rackt's React Router library with (HTML5) browser history who want to host on S3.

Suppose a user visits /foo/bear at your S3-hosted static web site. Given David's earlier suggestion, redirect rules will send them to /#/foo/bear. If your application's built using browser history, this won't do much good. However your application is loaded at this point and it can now manipulate history.

Including Rackt history in our project (see also Using Custom Histories from the React Router project), you can add a listener that's aware of hash history paths and replace the path as appropriate, as illustrated in this example:

import ReactDOM from 'react-dom';

/* Application-specific details. */
const route = {};

import { Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';

const history = useRouterHistory(createHistory)();

history.listen(function (location) {
  const path = (/#(\/.*)$/.exec(location.hash) || [])[1];
  if (path) history.replace(path);
});

ReactDOM.render(
  <Router history={history} routes={route}/>,
  document.body.appendChild(document.createElement('div'))
);

To recap:

  1. David's S3 redirect rule will direct /foo/bear to /#/foo/bear.
  2. Your application will load.
  3. The history listener will detect the #/foo/bear history notation.
  4. And replace history with the correct path.

Link tags will work as expected, as will all other browser history functions. The only downside I've noticed is the interstitial redirect that occurs on initial request.

This was inspired by a solution for AngularJS, and I suspect could be easily adapted to any application.

Why does the 'int' object is not callable error occur when using the sum() function?

You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.

To fix this, restart your interpreter.

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168

If you shadow the sum builtin, you can get the error you are seeing

>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Also, note that sum will work fine on the set there is no need to convert it to a list

Combine two ActiveRecord::Relation objects

There is a gem called active_record_union that might be what you are looking for.

It's example usages is the following:

current_user.posts.union(Post.published)
current_user.posts.union(Post.published).where(id: [6, 7])
current_user.posts.union("published_at < ?", Time.now)
user_1.posts.union(user_2.posts).union(Post.published)
user_1.posts.union_all(user_2.posts)

How to group an array of objects by key

Prototype version using ES6 as well. Basically this uses the reduce function to pass in an accumulator and current item, which then uses this to build your "grouped" arrays based on the passed in key. the inner part of the reduce may look complicated but essentially it is testing to see if the key of the passed in object exists and if it doesn't then create an empty array and append the current item to that newly created array otherwise using the spread operator pass in all the objects of the current key array and append current item. Hope this helps someone!.

Array.prototype.groupBy = function(k) {
  return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
};

const projs = [
  {
    project: "A",
    timeTake: 2,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 4,
    desc: "this is a description"
  },
  {
    project: "A",
    timeTake: 12,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 45,
    desc: "this is a description"
  }
];

console.log(projs.groupBy("project"));

How to use double or single brackets, parentheses, curly braces

Brackets

if [ CONDITION ]    Test construct  
if [[ CONDITION ]]  Extended test construct  
Array[1]=element1   Array initialization  
[a-z]               Range of characters within a Regular Expression
$[ expression ]     A non-standard & obsolete version of $(( expression )) [1]

[1] http://wiki.bash-hackers.org/scripting/obsolete

Curly Braces

${variable}                             Parameter substitution  
${!variable}                            Indirect variable reference  
{ command1; command2; . . . commandN; } Block of code  
{string1,string2,string3,...}           Brace expansion  
{a..z}                                  Extended brace expansion  
{}                                      Text replacement, after find and xargs

Parentheses

( command1; command2 )             Command group executed within a subshell  
Array=(element1 element2 element3) Array initialization  
result=$(COMMAND)                  Command substitution, new style  
>(COMMAND)                         Process substitution  
<(COMMAND)                         Process substitution 

Double Parentheses

(( var = 78 ))            Integer arithmetic   
var=$(( 20 + 5 ))         Integer arithmetic, with variable assignment   
(( var++ ))               C-style variable increment   
(( var-- ))               C-style variable decrement   
(( var0 = var1<98?9:21 )) C-style ternary operation

String replacement in java, similar to a velocity template

My preferred way is String.format() because its a oneliner and doesn't require third party libraries:

String message = String.format("Hello! My name is %s, I'm %s.", name, age); 

I use this regularly, e.g. in exception messages like:

throw new Exception(String.format("Unable to login with email: %s", email));

Hint: You can put in as many variables as you like because format() uses Varargs

new DateTime() vs default(DateTime)

The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified.

Therefore it may be better to do the following:

DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);

The myDate.Kind property is readonly, so it cannot be changed after the constructor is called.

Convert String to int array in java

    final String[] strings = {"1", "2"};
    final int[] ints = new int[strings.length];
    for (int i=0; i < strings.length; i++) {
        ints[i] = Integer.parseInt(strings[i]);
    }

What is the Maximum Size that an Array can hold?

System.Int32.MaxValue

Assuming you mean System.Array, ie. any normally defined array (int[], etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.

This limit is enforced because System.Array uses an Int32 as it's indexer, hence only valid values for an Int32 can be used. On top of this, only positive values (ie, >= 0) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32, which is available in Int32.MaxValue and is equivalent to 2^31, or roughly 2 billion.

On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T> instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T> or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.

The other collection of note is Dictionary<int, T> which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:

Dictionary<int, string> foo = new Dictionary<int, string>();
foo[1000] = "Hello world!";
Console.WriteLine(foo[1000]);

Using Dictionary also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>, which will provide more potential elements than you could possible think about.

What is the difference between canonical name, simple name and class name in Java Class?

I've been confused by the wide range of different naming schemes as well, and was just about to ask and answer my own question on this when I found this question here. I think my findings fit it well enough, and complement what's already here. My focus is looking for documentation on the various terms, and adding some more related terms that might crop up in other places.

Consider the following example:

package a.b;
class C {
  static class D extends C {
  }
  D d;
  D[] ds;
}
  • The simple name of D is D. That's just the part you wrote when declaring the class. Anonymous classes have no simple name. Class.getSimpleName() returns this name or the empty string. It is possible for the simple name to contain a $ if you write it like this, since $ is a valid part of an identifier as per JLS section 3.8 (even if it is somewhat discouraged).

  • According to the JLS section 6.7, both a.b.C.D and a.b.C.D.D.D would be fully qualified names, but only a.b.C.D would be the canonical name of D. So every canonical name is a fully qualified name, but the converse is not always true. Class.getCanonicalName() will return the canonical name or null.

  • Class.getName() is documented to return the binary name, as specified in JLS section 13.1. In this case it returns a.b.C$D for D and [La.b.C$D; for D[].

  • This answer demonstrates that it is possible for two classes loaded by the same class loader to have the same canonical name but distinct binary names. Neither name is sufficient to reliably deduce the other: if you have the canonical name, you don't know which parts of the name are packages and which are containing classes. If you have the binary name, you don't know which $ were introduced as separators and which were part of some simple name. (The class file stores the binary name of the class itself and its enclosing class, which allows the runtime to make this distinction.)

  • Anonymous classes and local classes have no fully qualified names but still have a binary name. The same holds for classes nested inside such classes. Every class has a binary name.

  • Running javap -v -private on a/b/C.class shows that the bytecode refers to the type of d as La/b/C$D; and that of the array ds as [La/b/C$D;. These are called descriptors, and they are specified in JVMS section 4.3.

  • The class name a/b/C$D used in both of these descriptors is what you get by replacing . by / in the binary name. The JVM spec apparently calls this the internal form of the binary name. JVMS section 4.2.1 describes it, and states that the difference from the binary name were for historical reasons.

  • The file name of a class in one of the typical filename-based class loaders is what you get if you interpret the / in the internal form of the binary name as a directory separator, and append the file name extension .class to it. It's resolved relative to the class path used by the class loader in question.

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You can do it like this:

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian

Vue 2 - Mutating props vue-warn

do not change the props directly in components.if you need change it set a new property like this:

data () {
    return () {
        listClone: this.list
    }
}

And change the value of listClone.

How to navigate back to the last cursor position in Visual Studio Code?

The answer for your question:

  1. Mac:
    (Alt+?) For backward and (Alt+?) For forward navigation
  2. Windows:
    (Ctrl+-) For backward and (Ctrl+Shift+-) For forward navigation
  3. Linux:
    (Ctrl+Alt+-) For backward and (Ctrl+Shift+-) For forward navigation


You can find out the current key-bindings following this link

You can even edit the key-binding as per your preference.

How to simulate a real mouse click using java?

You could create a simple AutoIt Script that does the job for you, compile it as an executable and perform a system call there.

in au3 Script:

; how to use: MouseClick ( "button" [, x, y [, clicks = 1 [, speed = 10]]] )
MouseClick ( "left" , $CmdLine[1], $CmdLine[1] )

Now find aut2exe in your au3 Folder or find 'Compile Script to .exe' in your Start Menu and create an executable.

in your Java class call:

Runtime.getRuntime().exec(
    new String[]{
        "yourscript.exe", 
        String.valueOf(mypoint.x),
        String.valueOf(mypoint.y)}
);

AutoIt will behave as if it was a human and won't be detected as a machine.

Find AutoIt here: https://www.autoitscript.com/

UIAlertController custom font, size, color

You can change the button color by applying a tint color to an UIAlertController.

On iOS 9, if the window tint color was set to a custom color, you have to apply the tint color right after presenting the alert. Otherwise the tint color will be reset to your custom window tint color.

// In your AppDelegate for example:
window?.tintColor = UIColor.redColor()

// Elsewhere in the App:
let alertVC = UIAlertController(title: "Title", message: "message", preferredStyle: .Alert)
alertVC.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alertVC.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))

// Works on iOS 8, but not on iOS 9
// On iOS 9 the button color will be red
alertVC.view.tintColor = UIColor.greenColor()

self.presentViewController(alert, animated: true, completion: nil)

// Necessary to apply tint on iOS 9
alertVC.view.tintColor = UIColor.greenColor()

Passing a String by Reference in Java?

java.lang.String is immutable.

I hate pasting URLs but https://docs.oracle.com/javase/10/docs/api/java/lang/String.html is essential for you to read and understand if you're in java-land.

Is it possible to make input fields read-only through CSS?

No behaviors can be set by CSS. The only way to disable something in CSS is to make it invisible by either setting display:none or simply putting div with transparent img all over it and changing their z-orders to disable user focusing on it with mouse. Even though, user will still be able to focus with tab from another field.

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Get program path in VB.NET?

Try this: My.Application.Info.DirectoryPath [MSDN]

This is using the My feature of VB.NET. This particular property is available for all non-web project types, since .NET Framework 2.0, including Console Apps as you require.

As long as you trust Microsoft to continue to keep this working correctly for all the above project types, this is simpler to use than accessing the other "more direct" solutions.

Dim appPath As String = My.Application.Info.DirectoryPath

Is it possible to make desktop GUI application in .NET Core?

You were not missing anything. Microsoft shipped no reasonable way to create GUI applications directly using .NET Core until .NET Core 3, though UWP (Universal Windows Platform) is partially built on top of .NET Core.

.NET Core 3.0 includes support for Windows Forms and WPF, though it is Windows-only.

.NET 6 will include .NET MAUI, which will support Windows and macOS desktop applications and mobile applications, with Linux desktop applications supported by the community (not MS). .NET 5 will include a preview version of .NET MAUI.

For third-party cross platform options, see other answers.

Check status of one port on remote host

You seem to be looking for a port scanner such as nmap or netcat, both of which are available for Windows, Linux, and Mac OS X.

For example, check for telnet on a known ip:

nmap -A 192.168.0.5/32 -p 23

For example, look for open ports from 20 to 30 on host.example.com:

nc -z host.example.com 20-30

How do I configure HikariCP in my Spring Boot app in my application.properties files?

This works for my boot application in case it helps. This class tells you what properties the config object is looking for:

https://github.com/brettwooldridge/HikariCP/blob/2.3.x/hikaricp-common/src/main/java/com/zaxxer/hikari/AbstractHikariConfig.java

I think multiple datasources could be supporting by adding datasource_whatever to the property keys in the source config file. Cheers!

@Configuration
class DataSourceConfig {

   @Value('${spring.datasource.username}')
   private String user;

   @Value('${spring.datasource.password}')
   private String password;

   @Value('${spring.datasource.url}')
   private String dataSourceUrl;

   @Value('${spring.datasource.dataSourceClassName}')
   private String dataSourceClassName;

   @Value('${spring.datasource.connectionTimeout}')
   private int connectionTimeout;

   @Value('${spring.datasource.maxLifetime}')
   private int maxLifetime;

   @Bean
   public DataSource primaryDataSource() {
      Properties dsProps = [url: dataSourceUrl, user: user, password: password]
      Properties configProps = [
            connectionTestQuery: 'select 1 from dual',
            connectionTimeout: connectionTimeout,
            dataSourceClassName: dataSourceClassName,
            dataSourceProperties: dsProps,
            maxLifetime: maxLifetime
      ]

      // A default max pool size of 10 seems reasonable for now, so no need to configure for now.
      HikariConfig hc = new HikariConfig(configProps)
      HikariDataSource ds = new HikariDataSource(hc)
      ds
   }
}

How to select the rows with maximum values in each group with dplyr?

You can use top_n

df %>% group_by(A, B) %>% top_n(n=1)

This will rank by the last column (value) and return the top n=1 rows.

Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)

SQL query to find record with ID not in another table

Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:

SELECT t1.ID, t1.Name 
FROM   Table1 t1
WHERE  NOT EXISTS (
    SELECT TOP 1 NULL
    FROM Table2 t2
    WHERE t1.ID = t2.ID
)

Return datetime object of previous month

For most use cases, what about

from datetime import date

current_date =date.today()
current_month = current_date.month
last_month = current_month - 1 if current_month != 1 else 12  
today_a_month_ago = date(current_date.year, last_month, current_date.day)

That seems the simplest to me.

Note: I've added the second to last line so that it would work if the current month is January as per @Nick's comment

Note 2: In most cases, if the current date is the 31st of a given month the result will be an invalid date as the previous month would not have 31 days (Except for July & August), as noted by @OneCricketeer

How to cast from List<Double> to double[] in Java?

You can use the ArrayUtils class from commons-lang to obtain a double[] from a Double[].

Double[] ds = frameList.toArray(new Double[frameList.size()]);
...
double[] d = ArrayUtils.toPrimitive(ds);

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

cd into directory without having permission

If it is a directory you own, grant yourself access to it:

chmod u+rx,go-w openfire

That grants you permission to use the directory and the files in it (x) and to list the files that are in it (r); it also denies group and others write permission on the directory, which is usually correct (though sometimes you may want to allow group to create files in your directory - but consider using the sticky bit on the directory if you do).

If it is someone else's directory, you'll probably need some help from the owner to change the permissions so that you can access it (or you'll need help from root to change the permissions for you).

C++ calling base class constructors

When objects are constructed, it is always first construct base class subobject, therefore, base class constructor is called first, then call derived class constructors. The reason is that derived class objects contain subobjects inherited from base class. You always need to call the base class constructor to initialze base class subobjects. We usually call the base class constructor on derived class's member initialization list. If you do not call base class constructor explicitly, the compile will call the default constructor of base class to initialize base class subobject. However, implicit call on default constructor does not necessary work at all times (for example, if base class defines a constructor that could not be called without arguments).

When objects are out of scope, it will first call destructor of derived class,then call destructor of base class.

MYSQL order by both Ascending and Descending sorting

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC

Have a look at ORDER BY Optimization

Is it possible to overwrite a function in PHP

short answer is no, you can't overwrite a function once its in the PHP function scope.

your best of using anonymous functions like so

$ihatefooexamples = function()
{
  return "boo-foo!";
}

//...
unset($ihatefooexamples);
$ihatefooexamples = function()
{
   return "really boo-foo";
}

http://php.net/manual/en/functions.anonymous.php

What is a magic number, and why is it bad?

@eed3si9n: I'd even suggest that '1' is a magic number. :-)

A principle that's related to magic numbers is that every fact your code deals with should be declared exactly once. If you use magic numbers in your code (such as the password length example that @marcio gave, you can easily end up duplicating that fact, and when your understand of that fact changes you've got a maintenance problem.

How do you stylize a font in Swift?

You can set custom font in two ways : design time and run-time.

  1. First you need to download required font (.ttf file format). Then, double click on the file to install it.

  2. This will show a pop-up. Click on 'install font' button.

Screenshot 1

  1. This will install the font and will appear in 'Fonts' window.

Screenshot 2

  1. Now, the font is installed successfully. Drag and drop the custom font in your project. While doing this make sure that 'Add to targets' is checked.

Screenshot 3

  1. You need to make sure that this file is also added into 'Copy Bundle Resources' present in Build Phases of Targets of your project.

Screenshot 4

  1. After this you need to add this font in Info.plist of your project. Create a new key with 'Font Provided by application' with type as Array. Add a the font as an element with type String in Array.

Screenshot 5

A. Design mode :

  1. Select the label from Storyboard file. Goto Font attribute present in Attribute inspector of Utilities.

Screenshot 6

  1. Click on Font and select 'Custom font'

Screenshot 7

  1. From Family section select the custom font you have installed.

Screenshot 8

  1. Now you can see that font of label is set to custom font.

Screenshot 9

B. Run-time mode :

 self.lblWelcome.font = UIFont(name: "BananaYeti-Extrabold Trial", size: 16)

It seems that run-time mode doesn't work for dynamically formed string like

self.lblWelcome.text = "Welcome, " + fullname + "!"

Note that in above case only design-time approach worked correctly for me.

Why can't Visual Studio find my DLL?

To add to Oleg's answer:

I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath) to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!

* I actually don't know if the $(ExecutablePath) macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.

Using JSON POST Request

Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).

Otherwise, you might want to go with another JS library like jQuery or Mootools.

javascript: get a function's variable's value within another function

you need a return statement in your first function.

function first(){
    var nameContent = document.getElementById('full_name').value;
    return nameContent;
}

and then in your second function can be:

function second(){
    alert(first());
}

Redirect to a page/URL after alert button is pressed

<head>
<script>
    function myFunction() {
        var x;
        var r = confirm("Do you want to clear data?");
        if (r == true) {
            x = "Your Data is Cleared";
            window.location.href = "firstpage.php";
        }
        else {
            x = "You pressed Cancel!";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>

<p id="demo"></p>
</body>
</html>

This will redirect to new php page.

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

Error in file(file, "rt") : cannot open the connection

This error also occurs when you try to use the result of getwd() directly in the path. The problem is the missingness of the "/" at the end. Try the following code:

projectFolder <- paste(getwd(), "/", sep = '')

The paste() is to concatenate the forward slash at the end.

sorting integers in order lowest to highest java

if array.sort doesn't have what your looking for you can try this:

package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
    ArrayList<AffineTransform> affs;
    ListIterator<AffineTransform> li;
    Integer count, count2;
    /**
     * @param args
     */
    public static void main(String[] args) {
        new QuicksortAlgorithm();
    }
    public QuicksortAlgorithm(){
        count = new Integer(0);
        count2 = new Integer(1);
        affs = new ArrayList<AffineTransform>();
        for (int i = 0; i <= 128; i++){
            affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
        }
        affs = arrangeNumbers(affs);
        printNumbers();
    }
    public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
        while (list.size() > 1 && count != list.size() - 1){
            if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
                list.add(count, list.get(count2));
                list.remove(count2 + 1);
            }
            if (count2 == list.size() - 1){
                count++;
                count2 = count + 1;
            }
            else{
            count2++;
            }
        }
        return list;
    }
    public void printNumbers(){
        li = affs.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
    }
}

Lock screen orientation (Android)

I had a similar problem.

When I entered

<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>

In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.

What is "406-Not Acceptable Response" in HTTP?

In my case, I added:

Content-Type: application/x-www-form-urlencoded

solved my problem completely.

Input and Output binary streams using JERSEY?

This example shows how to publish log files in JBoss through a rest resource. Note the get method uses the StreamingOutput interface to stream the content of the log file.

@Path("/logs/")
@RequestScoped
public class LogResource {

private static final Logger logger = Logger.getLogger(LogResource.class.getName());
@Context
private UriInfo uriInfo;
private static final String LOG_PATH = "jboss.server.log.dir";

public void pipe(InputStream is, OutputStream os) throws IOException {
    int n;
    byte[] buffer = new byte[1024];
    while ((n = is.read(buffer)) > -1) {
        os.write(buffer, 0, n);   // Don't allow any extra bytes to creep in, final write
    }
    os.close();
}

@GET
@Path("{logFile}")
@Produces("text/plain")
public Response getLogFile(@PathParam("logFile") String logFile) throws URISyntaxException {
    String logDirPath = System.getProperty(LOG_PATH);
    try {
        File f = new File(logDirPath + "/" + logFile);
        final FileInputStream fStream = new FileInputStream(f);
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                try {
                    pipe(fStream, output);
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return Response.ok(stream).build();
    } catch (Exception e) {
        return Response.status(Response.Status.CONFLICT).build();
    }
}

@POST
@Path("{logFile}")
public Response flushLogFile(@PathParam("logFile") String logFile) throws URISyntaxException {
    String logDirPath = System.getProperty(LOG_PATH);
    try {
        File file = new File(logDirPath + "/" + logFile);
        PrintWriter writer = new PrintWriter(file);
        writer.print("");
        writer.close();
        return Response.ok().build();
    } catch (Exception e) {
        return Response.status(Response.Status.CONFLICT).build();
    }
}    

}

How does autowiring work in Spring?

@Autowired is an annotation introduced in Spring 2.5, and it's used only for injection.

For example:

class A {

    private int id;

    // With setter and getter method
}

class B {

    private String name;

    @Autowired // Here we are injecting instance of Class A into class B so that you can use 'a' for accessing A's instance variables and methods.
    A a;

    // With setter and getter method

    public void showDetail() {
        System.out.println("Value of id form A class" + a.getId(););
    }
}

Compare string with all values in list

I assume you mean list and not array? There is such a thing as an array in Python, but more often than not you want a list instead of an array.

The way to check if a list contains a value is to use in:

if paid[j] in d:
    # ...

Windows batch files: .bat vs .cmd?

a difference:

.cmd files are loaded into memory before being executed. .bat files execute a line, read the next line, execute that line...

you can come across this when you execute a script file and then edit it before it's done executing. bat files will be messed up by this, but cmd files won't.

Remove Null Value from String array in java

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

    List<String> list = new ArrayList<String>();

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

    }
}

New lines (\r\n) are not working in email body

You need to use a <br> because your Content-Type is text/html.

It works without the Content-Type header because then your e-mail will be interpreted as plain text. If you really want to use \n you should use Content-Type: text/plain but then you'll lose any markup.

Also check out similar question here.

How to use "like" and "not like" in SQL MSAccess for the same field?

Not sure if this is still extant but I'm guessing you need something like

((field Like "AA*") AND (field Not Like "BB*"))

JSON Java 8 LocalDateTime format in Spring Boot

@JsonDeserialize(using= LocalDateDeserializer.class) does not work for me with the below dependency.

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version> 2.9.6</version>
</dependency>

I have used the below code converter to deserialize the date into a java.sql.Date.

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;


@SuppressWarnings("UnusedDeclaration")
@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<java.time.LocalDate, java.sql.Date> {


    @Override
    public java.sql.Date convertToDatabaseColumn(java.time.LocalDate attribute) {

        return attribute == null ? null : java.sql.Date.valueOf(attribute);
    }

    @Override
    public java.time.LocalDate convertToEntityAttribute(java.sql.Date dbData) {

        return dbData == null ? null : dbData.toLocalDate();
    }
}

Pyspark: Exception: Java gateway process exited before sending the driver its port number

Had same issue, after installing java using below lines solved the issue !

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

JavaScript file upload size validation

Yes, you can use the File API for this.

Here's a complete example (see comments):

_x000D_
_x000D_
document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
    // (Can't use `typeof FileReader === "function"` because apparently it
    // comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal
        console.log("The file API isn't supported on this browser yet.");
        return;
    }

    var input = document.getElementById('fileinput');
    if (!input.files) { // This is VERY unlikely, browser support is near-universal
        console.error("This browser doesn't seem to support the `files` property of file inputs.");
    } else if (!input.files[0]) {
        addPara("Please select a file before clicking 'Load'");
    } else {
        var file = input.files[0];
        addPara("File " + file.name + " is " + file.size + " bytes in size");
    }
});

function addPara(text) {
    var p = document.createElement("p");
    p.textContent = text;
    document.body.appendChild(p);
}
_x000D_
body {
    font-family: sans-serif;
}
_x000D_
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load'>
</form>
_x000D_
_x000D_
_x000D_


Slightly off-topic, but: Note that client-side validation is no substitute for server-side validation. Client-side validation is purely to make it possible to provide a nicer user experience. For instance, if you don't allow uploading a file more than 5MB, you could use client-side validation to check that the file the user has chosen isn't more than 5MB in size and give them a nice friendly message if it is (so they don't spend all that time uploading only to get the result thrown away at the server), but you must also enforce that limit at the server, as all client-side limits (and other validations) can be circumvented.

top nav bar blocking top content of the page

In my project derived from the MVC 5 tutorial I found that changing the body padding had no effect. The following worked for me:

@media screen and (min-width:768px) and (max-width:991px) {
    body {
        margin-top:100px;
    }
}
@media screen and (min-width:992px) and (max-width:1199px) {
    body {
        margin-top:50px;
    }
}

It resolves the cases where the navbar folds into 2 or 3 lines. This can be inserted into bootstrap.css anywhere after the lines body { margin: 0; }

How do I send an HTML Form in an Email .. not just MAILTO

I actually use ASP C# to send my emails now, with something that looks like :

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form.Count > 0)
    {
        string formEmail = "";
        string fromEmail = "[email protected]";
        string defaultEmail = "[email protected]";

        string sendTo1 = "";

        int x = 0;

        for (int i = 0; i < Request.Form.Keys.Count; i++)
        {
            formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
            formEmail += ": " + Request.Form[i] + "<br/>";
            if (Request.Form.Keys[i] == "Email")
            {
                if (Request.Form[i].ToString() != string.Empty)
                {
                    fromEmail = Request.Form[i].ToString();
                }
                formEmail += "<br/>";
            }

        }
        System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
        SmtpClient smtpClient = new SmtpClient();

        try
        {
            myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
            myMsg.IsBodyHtml = true;
            myMsg.Body = formEmail;
            myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
            myMsg.Subject = "Sent using Gmail Smtp";
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pward");

            smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);

        }
        catch (Exception ee)
        {
            debug.Text += ee.Message;
        }
    }
}

This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

This worked for me:

[XmlInclude(typeof(BankPayment))]
[Serializable]
public abstract class Payment { }    

[Serializable]
public class BankPayment : Payment {} 

[Serializable]
public class Payments : List<Payment>{}

XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)});

How to determine a Python variable's type?

Use the type() builtin function:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

To check if a variable is of a given type, use isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

Note that Python doesn't have the same types as C/C++, which appears to be your question.

How to uninstall a windows service and delete its files without rebooting

sc delete "service name"

will delete a service. I find that the sc utility is much easier to locate than digging around for installutil. Remember to stop the service if you have not already.

Get all inherited classes of an abstract class

typeof(AbstractDataExport).Assembly tells you an assembly your types are located in (assuming all are in the same).

assembly.GetTypes() gives you all types in that assembly or assembly.GetExportedTypes() gives you types that are public.

Iterating through the types and using type.IsAssignableFrom() gives you whether the type is derived.

Create a simple 10 second countdown

_x000D_
_x000D_
var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');
    var total_timers = seconds_inputs.length;
    for ( var i = 0; i < total_timers; i++){
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
        var cal_seconds = seconds_inputs[i].getAttribute('value');

        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
    }
    function timer() {
        for ( var i = 0; i < total_timers; i++) {
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');

            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
            var hours = Math.floor(hoursLeft / 3600);
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
            var minutes = Math.floor(minutesLeft / 60);
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;

            function pad(n) {
                return (n < 10 ? "0" + n : n);
            }
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);

            if (eval('seconds_'+ seconds_prod_id) == 0) {
                clearInterval(countdownTimer);
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
            } else {
                var value = eval('seconds_'+seconds_prod_id);
                value--;
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');
            }
        }
    }

    var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
    <div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>
_x000D_
_x000D_
_x000D_

ActionController::InvalidAuthenticityToken

There are several causes for this error, (relating to Rails 4).

1. Check <%= csrf_meta_tags %> present in page layout

2. check authenticity token is being sent with AJAX calls if using form_for helper with remote: true option.If not you can include the line <%= hidden_field_tag :authenticity_token, form_authenticity_token %> withing the form block.

3. If request is being sent from cached page, use fragment caching to exclude part of page that sends request e.g. button_to etc. otherwise token will be stale/invalid.

I would be reluctant to nullify csrf protection...

Retrieving subfolders names in S3 bucket from boto3

It took me a lot of time to figure out, but finally here is a simple way to list contents of a subfolder in S3 bucket using boto3. Hope it helps

prefix = "folderone/foldertwo/"
s3 = boto3.resource('s3')
bucket = s3.Bucket(name="bucket_name_here")
FilesNotFound = True
for obj in bucket.objects.filter(Prefix=prefix):
     print('{0}:{1}'.format(bucket.name, obj.key))
     FilesNotFound = False
if FilesNotFound:
     print("ALERT", "No file in {0}/{1}".format(bucket, prefix))

What is the difference between git clone and checkout?

git clone is to fetch your repositories from the remote git server.

git checkout is to checkout your desired status of your repository (like branches or particular files).

E.g., you are currently on master branch and you want to switch into develop branch.

git checkout develop_branch

E.g., you want to checkout to a particular status of a particular file

git checkout commit_point_A -- <filename>

Here is a good reference for you to learn Git, lets you understand much more easily.

Windows 7 - Add Path

I think you are editing something in the windows registry but that has no effect on the path.

Try this:

How to Add, Remove or Edit Environment variables in Windows 7

the variable of interest is the PATH

also you can type on the command line:

Set PATH=%PATH%;(your new path);

Detect if a page has a vertical scrollbar?

Oddly none of these solutions tell you if a page has a vertical scrollbar.

window.innerWidth - document.body.clientWidth will give you the width of the scrollbar. This should work in anything IE9+ (not tested in the lesser browsers). (Or to strictly answer the question, !!(window.innerWidth - document.body.clientWidth)

Why? Let's say you have a page where the content is taller than the window height and the user can scroll up/down. If you're using Chrome on a Mac with no mouse plugged in, the user will not see a scrollbar. Plug a mouse in and a scrollbar will appear. (Note this behaviour can be overridden, but that's the default AFAIK).

How do I create 7-Zip archives with .NET?

If you can guarantee the 7-zip app will be installed (and in the path) on all target machines, you can offload by calling the command line app 7z. Not the most elegant solution but it is the least work.

Import and insert sql.gz file into database with putty

Login into your server using a shell program like putty.

Type in the following command on the command line

zcat DB_File_Name.sql.gz | mysql -u username -p Target_DB_Name

where

DB_File_Name.sql.gz = full path of the sql.gz file to be imported

username = your mysql username

Target_DB_Name = database name where you want to import the database

When you hit enter in the command line, it will prompt for password. Enter your MySQL password.

You are done!

Generating random integer from a range

Let's split the problem into two parts:

  • Generate a random number n in the range 0 through (max-min).
  • Add min to that number

The first part is obviously the hardest. Let's assume that the return value of rand() is perfectly uniform. Using modulo will add bias to the first (RAND_MAX + 1) % (max-min+1) numbers. So if we could magically change RAND_MAX to RAND_MAX - (RAND_MAX + 1) % (max-min+1), there would no longer be any bias.

It turns out that we can use this intuition if we are willing to allow pseudo-nondeterminism into the running time of our algorithm. Whenever rand() returns a number which is too large, we simply ask for another random number until we get one which is small enough.

The running time is now geometrically distributed, with expected value 1/p where p is the probability of getting a small enough number on the first try. Since RAND_MAX - (RAND_MAX + 1) % (max-min+1) is always less than (RAND_MAX + 1) / 2, we know that p > 1/2, so the expected number of iterations will always be less than two for any range. It should be possible to generate tens of millions of random numbers in less than a second on a standard CPU with this technique.

EDIT:

Although the above is technically correct, DSimon's answer is probably more useful in practice. You shouldn't implement this stuff yourself. I have seen a lot of implementations of rejection sampling and it is often very difficult to see if it's correct or not.

How to pass a parameter like title, summary and image in a Facebook sharer URL

I've used the below before, and it has worked. It isn't very pretty, but you can alter it to suit your needs.

The following JavaScript function grabs the location.href & document.title for the sharer, and you can ultimately change these.

function fbs_click() {
        u=location.href;
        t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
                'sharer',
                'toolbar=0,status=0,width=626,height=436');

            return false;
        }

Usage:

<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">
    Share on Facebook
</a>

It looks like this is what you could possibly be looking for: Facebook sharer title / desc....

Share application "link" in Android

Call this method:

public static void shareApp(Context context)
{
    final String appPackageName = context.getPackageName();
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
    sendIntent.setType("text/plain");
    context.startActivity(sendIntent);
}

Uploading files to file server using webclient class

when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

How do I resize an image using PIL and maintain its aspect ratio?

The following script creates nice thumbnails of all JPEG images preserving aspect ratios with 128x128 max resolution.

from PIL import Image
img = Image.open("D:\\Pictures\\John.jpg")
img.thumbnail((680,680))
img.save("D:\\Pictures\\John_resize.jpg")

How to work with string fields in a C struct?

I think this solution uses less code and is easy to understand even for newbie.

For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.

Define definition of struct:

typedef struct {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} Patient;

Initialize variable with type of that struct:

Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";

It is that simple. Hope this answer helps many developers.

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

I copied a master.mdf und mastlog.ldf from another Computer (luckily, we have a lot of Clients with the same configuration, otherwise template data would be perhaps necessary). I backed up the damaged master.mdf and mastlog.mdf. After that I replaced the bad ones with the ones from another Computer. And it worked. I needed to start the MSSQLSERVER Service of course. But, after that I had Problem that the user was already existing but orphaned (error code 15023), I executed the query

USE Database_name EXEC sp_change_users_login 'Auto_Fix', 'username'

after that, everything was working smoothly. Hope this helps you and many thanks for this thread, saved me :)

What's the difference between a null pointer and a void pointer?

A null pointer is guaranteed to not compare equal to a pointer to any object. It's actual value is system dependent and may vary depending on the type. To get a null int pointer you would do

int* p = 0;

A null pointer will be returned by malloc on failure.

We can test if a pointer is null, i.e. if malloc or some other function failed simply by testing its boolean value:

if (p) {
    /* Pointer is not null */
} else {
    /* Pointer is null */
}

A void pointer can point to any type and it is up to you to handle how much memory the referenced objects consume for the purpose of dereferencing and pointer arithmetic.

Generating all permutations of a given string

Here are two c# versions (just for reference): 1. Prints all permuations 2. returns all permutations

Basic gist of the algorithm is (probably below code is more intuitive - nevertheless, here is some explanation of what below code does): - from the current index to for the rest of the collection, swap the element at current index - get the permutations for the remaining elements from next index recursively - restore the order, by re-swapping

Note: the above recursive function will be invoked from the start index.

private void PrintAllPermutations(int[] a, int index, ref int count)
        {
            if (index == (a.Length - 1))
            {
                count++;
                var s = string.Format("{0}: {1}", count, string.Join(",", a));
                Debug.WriteLine(s);
            }
            for (int i = index; i < a.Length; i++)
            {
                Utilities.swap(ref a[i], ref a[index]);
                this.PrintAllPermutations(a, index + 1, ref count);
                Utilities.swap(ref a[i], ref a[index]);
            }
        }
        private int PrintAllPermutations(int[] a)
        {
            a.ThrowIfNull("a");
            int count = 0;
            this.PrintAllPermutations(a, index:0, count: ref count);
            return count;
        }

version 2 (same as above - but returns the permutations in lieu of printing)

private int[][] GetAllPermutations(int[] a, int index)
        {
            List<int[]> permutations = new List<int[]>();
            if (index == (a.Length - 1))
            {
                permutations.Add(a.ToArray());
            }

            for (int i = index; i < a.Length; i++)
            {
                Utilities.swap(ref a[i], ref a[index]);
                var r = this.GetAllPermutations(a, index + 1);
                permutations.AddRange(r);
                Utilities.swap(ref a[i], ref a[index]);
            }
            return permutations.ToArray();
        }
        private int[][] GetAllPermutations(int[] p)
        {
            p.ThrowIfNull("p");
            return this.GetAllPermutations(p, 0);
        }

Unit Tests

[TestMethod]
        public void PermutationsTests()
        {
            List<int> input = new List<int>();
            int[] output = { 0, 1, 2, 6, 24, 120 };
            for (int i = 0; i <= 5; i++)
            {
                if (i != 0)
                {
                    input.Add(i);
                }
                Debug.WriteLine("================PrintAllPermutations===================");
                int count = this.PrintAllPermutations(input.ToArray());
                Assert.IsTrue(count == output[i]);
                Debug.WriteLine("=====================GetAllPermutations=================");
                var r = this.GetAllPermutations(input.ToArray());
                Assert.IsTrue(count == r.Length);
                for (int j = 1; j <= r.Length;j++ )
                {
                    string s = string.Format("{0}: {1}", j,
                        string.Join(",", r[j - 1]));
                    Debug.WriteLine(s);
                }
                Debug.WriteLine("No.OfElements: {0}, TotalPerms: {1}", i, count);
            }
        }

How to make a ssh connection with python?

Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/

The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.

Setting Up a Custom SSH Server

The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.

You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.

How Do I Do That? Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.

Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.

To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.

Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.

Example 10-1. sshserver.py

from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os

class SSHDemoProtocol(recvline.HistoricRecvLine):
    def __init__(self, user):
        self.user = user

    def connectionMade(self) : 
     recvline.HistoricRecvLine.connectionMade(self)
        self.terminal.write("Welcome to my test SSH server.")
        self.terminal.nextLine() 
        self.do_help()
        self.showPrompt()

    def showPrompt(self): 
        self.terminal.write("$ ")

    def getCommandFunc(self, cmd):
        return getattr(self, ‘do_’ + cmd, None)

    def lineReceived(self, line):
        line = line.strip()
        if line: 
            cmdAndArgs = line.split()
            cmd = cmdAndArgs[0]
            args = cmdAndArgs[1:]
            func = self.getCommandFunc(cmd)
            if func: 
               try:
                   func(*args)
               except Exception, e: 
                   self.terminal.write("Error: %s" % e)
                   self.terminal.nextLine()
            else:
               self.terminal.write("No such command.")
               self.terminal.nextLine()
        self.showPrompt()

    def do_help(self, cmd=”):
        "Get help on a command. Usage: help command"
        if cmd: 
            func = self.getCommandFunc(cmd)
            if func:
                self.terminal.write(func.__doc__)
                self.terminal.nextLine()
                return

        publicMethods = filter(
            lambda funcname: funcname.startswith(‘do_’), dir(self)) 
        commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods] 
        self.terminal.write("Commands: " + " ".join(commands))
        self.terminal.nextLine()

    def do_echo(self, *args):
        "Echo a string. Usage: echo my line of text"
        self.terminal.write(" ".join(args)) 
        self.terminal.nextLine()

    def do_whoami(self):
        "Prints your user name. Usage: whoami"
        self.terminal.write(self.user.username)
        self.terminal.nextLine()

    def do_quit(self):
        "Ends your session. Usage: quit" 
        self.terminal.write("Thanks for playing!")
        self.terminal.nextLine() 
        self.terminal.loseConnection()

    def do_clear(self):
        "Clears the screen. Usage: clear" 
        self.terminal.reset()

class SSHDemoAvatar(avatar.ConchUser): 
    implements(conchinterfaces.ISession)

    def __init__(self, username): 
        avatar.ConchUser.__init__(self) 
        self.username = username 
        self.channelLookup.update({‘session’:session.SSHSession})

    def openShell(self, protocol): 
        serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
        serverProtocol.makeConnection(protocol)
        protocol.makeConnection(session.wrapProtocol(serverProtocol))

    def getPty(self, terminal, windowSize, attrs):
        return None

    def execCommand(self, protocol, cmd): 
        raise NotImplementedError

    def closed(self):
        pass

class SSHDemoRealm:
    implements(portal.IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if conchinterfaces.IConchUser in interfaces:
            return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
        else:
            raise Exception, "No supported interfaces found."

def getRSAKeys():
    if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
        # generate a RSA keypair
        print "Generating RSA keypair…" 
        from Crypto.PublicKey import RSA 
        KEY_LENGTH = 1024
        rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
        publicKeyString = keys.makePublicKeyString(rsaKey) 
        privateKeyString = keys.makePrivateKeyString(rsaKey)
        # save keys for next time
        file(‘public.key’, ‘w+b’).write(publicKeyString)
        file(‘private.key’, ‘w+b’).write(privateKeyString)
        print "done."
    else:
        publicKeyString = file(‘public.key’).read()
        privateKeyString = file(‘private.key’).read() 
    return publicKeyString, privateKeyString

if __name__ == "__main__":
    sshFactory = factory.SSHFactory() 
    sshFactory.portal = portal.Portal(SSHDemoRealm())
    users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
    sshFactory.portal.registerChecker(
 checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))

    pubKeyString, privKeyString =
getRSAKeys()
    sshFactory.publicKeys = {
        ‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
    sshFactory.privateKeys = {
        ‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}

    from twisted.internet import reactor 
    reactor.listenTCP(2222, sshFactory) 
    reactor.run()

{mospagebreak title=Setting Up a Custom SSH Server continued}

sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:

$ ssh admin@localhost -p 2222 
admin@localhost’s password: aaa

>>> Welcome to my test SSH server.  
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit

Connection to localhost closed.

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

Make sure the required dlls are exported (or copied manually) to the bin folder when building your application.

How do I see the current encoding of a file in Sublime Text?

Another option in case you don't wanna use a plugin:

Ctrl+` or

View -> Show Console

type on the console the following command:

view.encoding()

In case you want to something more intrusive, there's a option to create an shortcut that executes the following command:

sublime.message_dialog(view.encoding())

Index all *except* one item in python

Use np.delete ! It does not actually delete anything inplace

Example:

import numpy as np
a = np.array([[1,4],[5,7],[3,1]])                                       

# a: array([[1, 4],
#           [5, 7],
#           [3, 1]])

ind = np.array([0,1])                                                   

# ind: array([0, 1])

# a[ind]: array([[1, 4],
#                [5, 7]])

all_except_index = np.delete(a, ind, axis=0)                                              
# all_except_index: array([[3, 1]])

# a: (still the same): array([[1, 4],
#                             [5, 7],
#                             [3, 1]])

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

To pull a remote branch locally, I do the following:

git checkout -b branchname // creates a local branch with the same name and checks out on it

git pull origin branchname // pulls the remote one onto your local one

The only time I did this and it didn't work, I deleted the repo, cloned it again and repeated the above 2 steps; it worked.

Angular 4 checkbox change value

This works for me, angular 9:

component.html file:

<mat-checkbox (change)="checkValue($event)">text</mat-checkbox>

component.ts file:

checkValue(e){console.log(e.target.checked)}

Wireshark vs Firebug vs Fiddler - pros and cons?

None of the above, if you are on a Mac. Use Charles Proxy. It's the best network/request information collecter that I have ever come across. You can view and edit all outgoing requests, and see the responses from those requests in several forms, depending on the type of the response. It costs 50 dollars for a license, but you can download the trial version and see what you think.

If your on Windows, then I would just stay with Fiddler.

Getting windbg without the whole WDK?

WinDbg is now available separately via MS Store. It's called "Preview" but I tested it to analyse some memory dumps and it works fine.

If you're on Windows 10 - launch MS Store, type "WinDbg" in the search box and voi-la - you have it. The download is approx. 100mb. It will downlaod required symbols automatically.

Android Studio-No Module

If you have imported the project, you may have to re-import it the proper way.
Steps :

  1. Close Android Studio. Take backup of the project from C:\Users\UserName\AndroidStudioProjects\YourProject to some other folder . Now delete the project.
  2. Launch Android Studio and click "Import Non-AndroidStudio Project (even if the project to be imported is an AndroidStudio project).
  3. Select only the root folder of the project to be imported. Set the destination directory. Keep all the options checked. AndroidStudio will prompt to make some changes, click Ok for all prompts.
  4. Now you can see the Module pre-defined at the top and you can launch the app to the emulator.

Tested on AndroidStudio version 1.0.1

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I was looking for a solution to this problem myself with no luck, so I had to roll my own which I would like to share here with you. (Please excuse my bad English) (It's a little crazy to answer another Czech guy in English :-) )

The first thing I tried was to use a good old PopupWindow. It's quite easy - one only has to listen to the OnMarkerClickListener and then show a custom PopupWindow above the marker. Some other guys here on StackOverflow suggested this solution and it actually looks quite good at first glance. But the problem with this solution shows up when you start to move the map around. You have to move the PopupWindow somehow yourself which is possible (by listening to some onTouch events) but IMHO you can't make it look good enough, especially on some slow devices. If you do it the simple way it "jumps" around from one spot to another. You could also use some animations to polish those jumps but this way the PopupWindow will always be "a step behind" where it should be on the map which I just don't like.

At this point, I was thinking about some other solution. I realized that I actually don't really need that much freedom - to show my custom views with all the possibilities that come with it (like animated progress bars etc.). I think there is a good reason why even the google engineers don't do it this way in the Google Maps app. All I need is a button or two on the InfoWindow that will show a pressed state and trigger some actions when clicked. So I came up with another solution which splits up into two parts:

First part:
The first part is to be able to catch the clicks on the buttons to trigger some action. My idea is as follows:

  1. Keep a reference to the custom infoWindow created in the InfoWindowAdapter.
  2. Wrap the MapFragment (or MapView) inside a custom ViewGroup (mine is called MapWrapperLayout)
  3. Override the MapWrapperLayout's dispatchTouchEvent and (if the InfoWindow is currently shown) first route the MotionEvents to the previously created InfoWindow. If it doesn't consume the MotionEvents (like because you didn't click on any clickable area inside InfoWindow etc.) then (and only then) let the events go down to the MapWrapperLayout's superclass so it will eventually be delivered to the map.

Here is the MapWrapperLayout's source code:

package com.circlegate.tt.cg.an.lib.map;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;

import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

public class MapWrapperLayout extends RelativeLayout {
    /**
     * Reference to a GoogleMap object 
     */
    private GoogleMap map;

    /**
     * Vertical offset in pixels between the bottom edge of our InfoWindow 
     * and the marker position (by default it's bottom edge too).
     * It's a good idea to use custom markers and also the InfoWindow frame, 
     * because we probably can't rely on the sizes of the default marker and frame. 
     */
    private int bottomOffsetPixels;

    /**
     * A currently selected marker 
     */
    private Marker marker;

    /**
     * Our custom view which is returned from either the InfoWindowAdapter.getInfoContents 
     * or InfoWindowAdapter.getInfoWindow
     */
    private View infoWindow;    

    public MapWrapperLayout(Context context) {
        super(context);
    }

    public MapWrapperLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MapWrapperLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Must be called before we can route the touch events
     */
    public void init(GoogleMap map, int bottomOffsetPixels) {
        this.map = map;
        this.bottomOffsetPixels = bottomOffsetPixels;
    }

    /**
     * Best to be called from either the InfoWindowAdapter.getInfoContents 
     * or InfoWindowAdapter.getInfoWindow. 
     */
    public void setMarkerWithInfoWindow(Marker marker, View infoWindow) {
        this.marker = marker;
        this.infoWindow = infoWindow;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean ret = false;
        // Make sure that the infoWindow is shown and we have all the needed references
        if (marker != null && marker.isInfoWindowShown() && map != null && infoWindow != null) {
            // Get a marker position on the screen
            Point point = map.getProjection().toScreenLocation(marker.getPosition());

            // Make a copy of the MotionEvent and adjust it's location
            // so it is relative to the infoWindow left top corner
            MotionEvent copyEv = MotionEvent.obtain(ev);
            copyEv.offsetLocation(
                -point.x + (infoWindow.getWidth() / 2), 
                -point.y + infoWindow.getHeight() + bottomOffsetPixels);

            // Dispatch the adjusted MotionEvent to the infoWindow
            ret = infoWindow.dispatchTouchEvent(copyEv);
        }
        // If the infoWindow consumed the touch event, then just return true.
        // Otherwise pass this event to the super class and return it's result
        return ret || super.dispatchTouchEvent(ev);
    }
}

All this will make the views inside the InfoView "live" again - the OnClickListeners will start triggering etc.

Second part: The remaining problem is, that obviously, you can't see any UI changes of your InfoWindow on screen. To do that you have to manually call Marker.showInfoWindow. Now, if you perform some permanent change in your InfoWindow (like changing the label of your button to something else), this is good enough.

But showing a button pressed state or something of that nature is more complicated. The first problem is, that (at least) I wasn't able to make the InfoWindow show normal button's pressed state. Even if I pressed the button for a long time, it just remained unpressed on the screen. I believe this is something that is handled by the map framework itself which probably makes sure not to show any transient state in the info windows. But I could be wrong, I didn't try to find this out.

What I did is another nasty hack - I attached an OnTouchListener to the button and manually switched it's background when the button was pressed or released to two custom drawables - one with a button in a normal state and the other one in a pressed state. This is not very nice, but it works :). Now I was able to see the button switching between normal to pressed states on the screen.

There is still one last glitch - if you click the button too fast, it doesn't show the pressed state - it just remains in its normal state (although the click itself is fired so the button "works"). At least this is how it shows up on my Galaxy Nexus. So the last thing I did is that I delayed the button in it's pressed state a little. This is also quite ugly and I'm not sure how would it work on some older, slow devices but I suspect that even the map framework itself does something like this. You can try it yourself - when you click the whole InfoWindow, it remains in a pressed state a little longer, then normal buttons do (again - at least on my phone). And this is actually how it works even on the original Google Maps app.

Anyway, I wrote myself a custom class which handles the buttons state changes and all the other things I mentioned, so here is the code:

package com.circlegate.tt.cg.an.lib.map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.google.android.gms.maps.model.Marker;

public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
    private final View view;
    private final Drawable bgDrawableNormal;
    private final Drawable bgDrawablePressed;
    private final Handler handler = new Handler();

    private Marker marker;
    private boolean pressed = false;

    public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed) {
        this.view = view;
        this.bgDrawableNormal = bgDrawableNormal;
        this.bgDrawablePressed = bgDrawablePressed;
    }

    public void setMarker(Marker marker) {
        this.marker = marker;
    }

    @Override
    public boolean onTouch(View vv, MotionEvent event) {
        if (0 <= event.getX() && event.getX() <= view.getWidth() &&
            0 <= event.getY() && event.getY() <= view.getHeight())
        {
            switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: startPress(); break;

            // We need to delay releasing of the view a little so it shows the pressed state on the screen
            case MotionEvent.ACTION_UP: handler.postDelayed(confirmClickRunnable, 150); break;

            case MotionEvent.ACTION_CANCEL: endPress(); break;
            default: break;
            }
        }
        else {
            // If the touch goes outside of the view's area
            // (like when moving finger out of the pressed button)
            // just release the press
            endPress();
        }
        return false;
    }

    private void startPress() {
        if (!pressed) {
            pressed = true;
            handler.removeCallbacks(confirmClickRunnable);
            view.setBackground(bgDrawablePressed);
            if (marker != null) 
                marker.showInfoWindow();
        }
    }

    private boolean endPress() {
        if (pressed) {
            this.pressed = false;
            handler.removeCallbacks(confirmClickRunnable);
            view.setBackground(bgDrawableNormal);
            if (marker != null) 
                marker.showInfoWindow();
            return true;
        }
        else
            return false;
    }

    private final Runnable confirmClickRunnable = new Runnable() {
        public void run() {
            if (endPress()) {
                onClickConfirmed(view, marker);
            }
        }
    };

    /**
     * This is called after a successful click 
     */
    protected abstract void onClickConfirmed(View v, Marker marker);
}

Here is a custom InfoWindow layout file that I used:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginRight="10dp" >

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="Title" />

        <TextView
            android:id="@+id/snippet"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="snippet" />

    </LinearLayout>

    <Button
        android:id="@+id/button" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

Test activity layout file (MapFragment being inside the MapWrapperLayout):

<com.circlegate.tt.cg.an.lib.map.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map_relative_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</com.circlegate.tt.cg.an.lib.map.MapWrapperLayout>

And finally source code of a test activity, which glues all this together:

package com.circlegate.testapp;

import com.circlegate.tt.cg.an.lib.map.MapWrapperLayout;
import com.circlegate.tt.cg.an.lib.map.OnInfoWindowElemTouchListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {    
    private ViewGroup infoWindow;
    private TextView infoTitle;
    private TextView infoSnippet;
    private Button infoButton;
    private OnInfoWindowElemTouchListener infoButtonListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
        final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
        final GoogleMap map = mapFragment.getMap();

        // MapWrapperLayout initialization
        // 39 - default marker height
        // 20 - offset between the default InfoWindow bottom edge and it's content bottom edge 
        mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20)); 

        // We want to reuse the info window for all the markers, 
        // so let's create only one class member instance
        this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
        this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
        this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
        this.infoButton = (Button)infoWindow.findViewById(R.id.button);

        // Setting custom OnTouchListener which deals with the pressed state
        // so it shows up 
        this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
                getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
                getResources().getDrawable(R.drawable.btn_default_pressed_holo_light)) 
        {
            @Override
            protected void onClickConfirmed(View v, Marker marker) {
                // Here we can perform some action triggered after clicking the button
                Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
            }
        }; 
        this.infoButton.setOnTouchListener(infoButtonListener);


        map.setInfoWindowAdapter(new InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                // Setting up the infoWindow with current's marker info
                infoTitle.setText(marker.getTitle());
                infoSnippet.setText(marker.getSnippet());
                infoButtonListener.setMarker(marker);

                // We must call this to set the current marker and infoWindow references
                // to the MapWrapperLayout
                mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
                return infoWindow;
            }
        });

        // Let's add a couple of markers
        map.addMarker(new MarkerOptions()
            .title("Prague")
            .snippet("Czech Republic")
            .position(new LatLng(50.08, 14.43)));

        map.addMarker(new MarkerOptions()
            .title("Paris")
            .snippet("France")
            .position(new LatLng(48.86,2.33)));

        map.addMarker(new MarkerOptions()
            .title("London")
            .snippet("United Kingdom")
            .position(new LatLng(51.51,-0.1)));
    }

    public static int getPixelsFromDp(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dp * scale + 0.5f);
    }
}

That's it. So far I only tested this on my Galaxy Nexus (4.2.1) and Nexus 7 (also 4.2.1), I will try it on some Gingerbread phone when I have a chance. A limitation I found so far is that you can't drag the map from where is your button on the screen and move the map around. It could probably be overcome somehow but for now, I can live with that.

I know this is an ugly hack but I just didn't find anything better and I need this design pattern so badly that this would really be a reason to go back to the map v1 framework (which btw. I would really really like to avoid for a new app with fragments etc.). I just don't understand why Google doesn't offer developers some official way to have a button on InfoWindows. It's such a common design pattern, moreover this pattern is used even in the official Google Maps app :). I understand the reasons why they can't just make your views "live" in the InfoWindows - this would probably kill performance when moving and scrolling map around. But there should be some way how to achieve this effect without using views.

Compare two dates with JavaScript

All the above-given answers only solved one thing: compare two dates.

Indeed, they seem to be the answers to the question, but a big part is missing:

What if I want to check whether a person is fully 18 years old?

Unfortunately, NONE of the above-given answers would be able to answer that question.

For example, the current time (around the time when I started to type these words) is Fri Jan 31 2020 10:41:04 GMT-0600 (Central Standard Time), while a customer enters his Date of Birth as "01/31/2002".

If we use "365 days/year", which is "31536000000" milliseconds, we would get the following result:

       let currentTime = new Date();
       let customerTime = new Date(2002, 1, 31);
       let age = (currentTime.getTime() - customerTime.getTime()) / 31536000000
       console.log("age: ", age);

with the following print-out:

       age: 17.92724710838407

But LEGALLY, that customer is already 18 years old. Even he enters "01/30/2002", the result would still be

       age: 17.930039743467784

which is less than 18. The system would report the "under age" error.

And this would just keep going for "01/29/2002", "01/28/2002", "01/27/2002" ... "01/05/2002", UNTIL "01/04/2002".

A system like that would just kill all the customers who were born between 18 years 0 days and 18 years 26 days ago, because they are legally 18 years old, while the system shows "under age".

The following is an answer to a question like that:

invalidBirthDate: 'Invalid date. YEAR cannot be before 1900.',
invalidAge: 'Invalid age. AGE cannot be less than 18.',

public static birthDateValidator(control: any): any {
    const val = control.value;
    if (val != null) {
        const slashSplit = val.split('-');
        if (slashSplit.length === 3) {
            const customerYear = parseInt(slashSplit[0], 10);
            const customerMonth = parseInt(slashSplit[1], 10);
            const customerDate = parseInt(slashSplit[2], 10);
            if (customerYear < 1900) {
                return { invalidBirthDate: true };
            } else {
                const currentTime = new Date();
                const currentYear = currentTime.getFullYear();
                const currentMonth = currentTime.getMonth() + 1;
                const currentDate = currentTime.getDate();
                if (currentYear - customerYear < 18) {
                    return { invalidAge: true };
                } else if (
                    currentYear - customerYear === 18 &&
                    currentMonth - customerMonth < 0) {
                    return { invalidAge: true };
                } else if (
                    currentYear - customerYear === 18 &&
                    currentMonth - customerMonth === 0 &&
                    currentDate - customerDate < 0) {
                    return { invalidAge: true };
                } else {
                    return null;
                }
            }
        }
    }
}

Optimal way to Read an Excel file (.xls/.xlsx)

Read from excel, modify and write back

 /// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
    var _xl = new Excel.Application();
    var wb = _xl.Workbooks.Open(filename);
    var sheets = wb.Sheets;
    DataSet dataSet = null;
    if (sheets != null && sheets.Count != 0)
    {
        dataSet = new DataSet();
        foreach (var item in sheets)
        {
            var sheet = (Excel.Worksheet)item;
            DataTable dt = null;
            if (sheet != null)
            {
                dt = new DataTable();
                var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
                var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;

                for (int j = 0; j < ColumnCount; j++)
                {
                    var cell = (Excel.Range)sheet.Cells[1, j + 1];
                    var column = new DataColumn(headers ? cell.Value : string.Empty);
                    dt.Columns.Add(column);
                }

                for (int i = 0; i < rowCount; i++)
                {
                    var r = dt.NewRow();
                    for (int j = 0; j < ColumnCount; j++)
                    {
                        var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
                        r[j] = cell.Value;
                    }
                    dt.Rows.Add(r);
                }

            }
            dataSet.Tables.Add(dt);
        }
    }
    _xl.Quit();
    return dataSet;
}



 public string Export(DataTable dt, bool headers = false)
    {
        var wb = _xl.Workbooks.Add();
        var sheet = (Excel.Worksheet)wb.ActiveSheet;
        //process columns
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            var col = dt.Columns[i];
            //added columns to the top of sheet
            var currentCell = (Excel.Range)sheet.Cells[1, i + 1];
            currentCell.Value = col.ToString();
            currentCell.Font.Bold = true;
            //process rows
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                var row = dt.Rows[j];
                //added rows to sheet
                var cell = (Excel.Range)sheet.Cells[j + 1 + 1, i + 1];
                cell.Value = row[i];
            }
            currentCell.EntireColumn.AutoFit();
        }
        var fileName="{somepath/somefile.xlsx}";
        wb.SaveCopyAs(fileName);
        _xl.Quit();
        return fileName;
    }

Unresponsive KeyListener for JFrame

Deion (and anyone else asking a similar question), you could use Peter's code above but instead of printing to standard output, you test for the key code PRESSED, RELEASED, or TYPED.

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    if (e.getID() == KeyEvent.KEY_PRESSED) {
        if (e.getKeyCode() == KeyEvent.VK_F4) {
            dispose();
        }
    } else if (e.getID() == KeyEvent.KEY_RELEASED) {
        if (e.getKeyCode() == KeyEvent.VK_F4) {
            dispose();
        }
    } else if (e.getID() == KeyEvent.KEY_TYPED) {
        if (e.getKeyCode() == KeyEvent.VK_F4) {
            dispose();
        }
    }
    return false;
}

How to iterate through LinkedHashMap with lists as values

In Java 8:

Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
    System.out.println(key + " -> " + value);
});

Create SQL script that create database and tables

Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.

For unordered scripts generated by SSMS you can go following

a) Execute script (some objects will be inserted some wont, there will be some errors)

b) Remove all objects from the script that have been added to database

c) Go back to a) until everything is eventually executed

Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).

All of these will take care of the dependencies for you and save you even more time.

Center a button in a Linear layout

If you want to center an item in the middle of the screen don't use a LinearLayout as these are meant for displaying a number of items in a row.

Use a RelativeLayout instead.

So replace:

android:layout_gravity="center_vertical|center_horizontal"

for the relevant RelativeLayout option:

android:layout_centerInParent="true"

So your layout file will look like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageButton android:id="@+id/btnFindMe" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/findme"></ImageButton>

</RelativeLayout>

How to identify platform/compiler from preprocessor macros?

See: http://predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #defines for many operating systems, compilers, language and platform standards, and standard libraries.

Mapping a JDBC ResultSet to an object

Use Statement Fetch Size , if you are retrieving more number of records. like this.

Statement statement = connection.createStatement();
statement.setFetchSize(1000); 

Apart from that i dont see an issue with the way you are doing in terms of performance

In terms of Neat. Always use seperate method delegate to map the resultset to POJO object. which can be reused later in the same class

like

private User mapResultSet(ResultSet rs){
     User user = new User();
     // Map Results
     return user;
}

If you have the same name for both columnName and object's fieldName , you could also write reflection utility to load the records back to POJO. and use MetaData to read the columnNames . but for small scale projects using reflection is not an problem. but as i said before there is nothing wrong with the way you are doing.

How to float a div over Google Maps?

absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!

How can I print each command before executing?

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

Solution using only javascript

function saveFile(fileName,urlFile){
    let a = document.createElement("a");
    a.style = "display: none";
    document.body.appendChild(a);
    a.href = urlFile;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);

What is the fastest way to transpose a matrix in C++?

I think that most fast way should not taking higher than O(n^2) also in this way you can use just O(1) space :
the way to do that is to swap in pairs because when you transpose a matrix then what you do is: M[i][j]=M[j][i] , so store M[i][j] in temp, then M[i][j]=M[j][i],and the last step : M[j][i]=temp. this could be done by one pass so it should take O(n^2)

Dictionary text file

For an English dictionary .txt file, you can use Custom Dictionary.

You can also generate a list aspell or wordlist with own settings.

Also you can take a look at http://wordlist.sourceforge.net/

Only english words: http://www.math.sjsu.edu/~foster/dictionary.txt

Using intents to pass data between activities

Main Activity

public class MainActivity extends Activity {

    EditText user, password;
    Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        user = (EditText) findViewById(R.id.username_edit);
        password = (EditText) findViewById(R.id.edit_password);
        login = (Button) findViewById(R.id.btnSubmit);
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Second.class);

                String uservalue = user.getText().toString();
                String name_value = password.getText().toString();
                String password_value = password.getText().toString();

                intent.putExtra("username", uservalue);
                intent.putExtra("password", password_value);
                startActivity(intent);
            }
        });
    }
}

Second Activity in which you want to receive Data

public class Second extends Activity{

    EditText name, pass;
    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        name = (EditText) findViewById(R.id.editText1);
        pass = (EditText) findViewById(R.id.editText2);

        String value = getIntent().getStringExtra("username");
        String pass_val = getIntent().getStringExtra("password");
        name.setText(value);
        pass.setText(pass_val);
    }
}

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

To add a little bit more information that confused me; I had always thought the same result could be achieved like so;

theDate.ToString("yyyy-MM-dd HH:mm:ss")

However, If your Current Culture doesn't use a colon(:) as the hour separator, and instead uses a full-stop(.) it could return as follow:

2009-06-15 13.45.30

Just wanted to add why the answer provided needs to be as it is;

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

:-)