Programs & Examples On #Network programming

Programming associated with creating and managing networks as well as adding network connectivity to a (set of) programs.

Sending and receiving data over a network using TcpClient

I have had luck using the socket object directly (rather than the TCP client). I create a Server object that looks something like this (I've edited some stuff such as exception handling out for brevity, but I hope that the idea comes across.)...

public class Server()
{
    private Socket sock;
    // You'll probably want to initialize the port and address in the
    // constructor, or via accessors, but to start your server listening
    // on port 8080 and on any IP address available on the machine...
    private int port = 8080;
    private IPAddress addr = IPAddress.Any;

    // This is the method that starts the server listening.
    public void Start()
    {
        // Create the new socket on which we'll be listening.
        this.sock = new Socket(
            addr.AddressFamily,
            SocketType.Stream,
            ProtocolType.Tcp);
        // Bind the socket to the address and port.
        sock.Bind(new IPEndPoint(this.addr, this.port));
        // Start listening.
        this.sock.Listen(this.backlog);
        // Set up the callback to be notified when somebody requests
        // a new connection.
        this.sock.BeginAccept(this.OnConnectRequest, sock);
    }

    // This is the method that is called when the socket recives a request
    // for a new connection.
    private void OnConnectRequest(IAsyncResult result)
    {
        // Get the socket (which should be this listener's socket) from
        // the argument.
        Socket sock = (Socket)result.AsyncState;
        // Create a new client connection, using the primary socket to
        // spawn a new socket.
        Connection newConn = new Connection(sock.EndAccept(result));
        // Tell the listener socket to start listening again.
        sock.BeginAccept(this.OnConnectRequest, sock);
    }
}

Then, I use a separate Connection class to manage the individual connection with the remote host. That looks something like this...

public class Connection()
{
    private Socket sock;
    // Pick whatever encoding works best for you.  Just make sure the remote 
    // host is using the same encoding.
    private Encoding encoding = Encoding.UTF8;

    public Connection(Socket s)
    {
        this.sock = s;
        // Start listening for incoming data.  (If you want a multi-
        // threaded service, you can start this method up in a separate
        // thread.)
        this.BeginReceive();
    }

    // Call this method to set this connection's socket up to receive data.
    private void BeginReceive()
    {
        this.sock.BeginReceive(
                this.dataRcvBuf, 0,
                this.dataRcvBuf.Length,
                SocketFlags.None,
                new AsyncCallback(this.OnBytesReceived),
                this);
    }

    // This is the method that is called whenever the socket receives
    // incoming bytes.
    protected void OnBytesReceived(IAsyncResult result)
    {
        // End the data receiving that the socket has done and get
        // the number of bytes read.
        int nBytesRec = this.sock.EndReceive(result);
        // If no bytes were received, the connection is closed (at
        // least as far as we're concerned).
        if (nBytesRec <= 0)
        {
            this.sock.Close();
            return;
        }
        // Convert the data we have to a string.
        string strReceived = this.encoding.GetString(
            this.dataRcvBuf, 0, nBytesRec);

        // ...Now, do whatever works best with the string data.
        // You could, for example, look at each character in the string
        // one-at-a-time and check for characters like the "end of text"
        // character ('\u0003') from a client indicating that they've finished
        // sending the current message.  It's totally up to you how you want
        // the protocol to work.

        // Whenever you decide the connection should be closed, call 
        // sock.Close() and don't call sock.BeginReceive() again.  But as long 
        // as you want to keep processing incoming data...

        // Set up again to get the next chunk of data.
        this.sock.BeginReceive(
            this.dataRcvBuf, 0,
            this.dataRcvBuf.Length,
            SocketFlags.None,
            new AsyncCallback(this.OnBytesReceived),
            this);

    }
}

You can use your Connection object to send data by calling its Socket directly, like so...

this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));

As I said, I've tried to edit the code here for posting, so I apologize if there are any errors in it.

trace a particular IP and port

it can be done by using this command: tcptraceroute -p destination port destination IP. like: tcptraceroute -p 9100 10.0.0.50 but don't forget to install tcptraceroute package on your system. tcpdump and nc by default installed on the system. regards

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.

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Artificially create a connection timeout error

Depending on what firewall software you have installed/available, you should be able to block the outgoing port and depending on how your firewall is setup it should just drop the connection request packet. No connection request, no connection, timeout ensues. This would probably work better if it was implemented at a router level (they tend to drop packets instead of sending resets, or whatever the equivalent is for the situation) but there's bound to be a software package that'd do the trick too.

What is the Difference Between read() and recv() , and Between send() and write()?

The difference is that recv()/send() work only on socket descriptors and let you specify certain options for the actual operation. Those functions are slightly more specialized (for instance, you can set a flag to ignore SIGPIPE, or to send out-of-band messages...).

Functions read()/write() are the universal file descriptor functions working on all descriptors.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

Ping a site in Python?

You may find Noah Gift's presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here

#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue

num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        ip = q.get()
        print "Thread %s: Pinging %s" % (i, ip)
        ret = subprocess.call("ping -c 1 %s" % ip,
            shell=True,
            stdout=open('/dev/null', 'w'),
            stderr=subprocess.STDOUT)
        if ret == 0:
            print "%s: is alive" % ip
        else:
            print "%s: did not respond" % ip
        q.task_done()
#Spawn thread pool
for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()
#Place work in queue
for ip in ips:
    queue.put(ip)
#Wait until worker threads are done to exit    
queue.join()

He is also author of: Python for Unix and Linux System Administration

http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

How to find the socket connection state in C?

you can use SS_ISCONNECTED macro in getsockopt() function. SS_ISCONNECTED is define in socketvar.h.

How many socket connections can a web server handle?

in case of the IPv4 protocol, the server with one IP address that listens on one port only can handle 2^32 IP addresses x 2^16 ports so 2^48 unique sockets. If you speak about a server as a physical machine, and you are able to utilize all 2^16 ports, then there could be maximum of 2^48 x 2^16 = 2^64 unique TCP/IP sockets for one IP address. Please note that some ports are reserved for the OS, so this number will be lower. To sum up:

1 IP and 1 port --> 2^48 sockets

1 IP and all ports --> 2^64 sockets

all unique IPv4 sockets in the universe --> 2^96 sockets

How is TeamViewer so fast?

It sounds indeed like video streaming more than image streaming, as someone suggested. JPEG/PNG compression isn't targeted for these types of speeds, so forget them.

Imagine having a recording codec on your system that can realtime record an incoming video stream (your screen). A bit like Fraps perhaps. Then imagine a video playback codec on the other side (the remote client). As HD recorders can do it (record live and even playback live from the same HD), so should you, in the end. The HD surely can't deliver images quicker than you can read your display, so that isn't the bottleneck. The bottleneck are the video codecs. You'll find the encoder much more of a problem than the decoder, as all decoders are mostly free.

I'm not saying it's simple; I myself have used DirectShow to encode a video file, and it's not realtime by far. But given the right codec I'm convinced it can work.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Recommended way to get hostname in Java

InetAddress.getLocalHost().getHostName() is better (as explained by Nick), but still not very good

One host can be known under many different hostnames. Usually you'll be looking for the hostname your host has in a specific context.

For example, in a web application, you might be looking for the hostname used by whoever issued the request you're currently handling. How to best find that one depends on which framework you're using for your web application.

In some kind of other internet-facing service, you'll want the hostname your service is available through from the 'outside'. Due to proxies, firewalls etc this might not even be a hostname on the machine your service is installed on - you might try to come up with a reasonable default, but you should definitely make this configurable for whoever installs this.

Difference between TCP and UDP?

This sentence is a UDP joke, but I'm not sure that you'll get it. The below conversation is a TCP/IP joke:

A: Do you want to hear a TCP/IP joke?
B: Yes, I want to hear a TCP/IP joke.
A: Ok, are you ready to hear a TCP/IP joke?
B: Yes, I'm ready to hear a TCP/IP joke.
A: Well, here is the TCP/IP joke.
A: Did you receive a TCP/IP joke?
B: Yes, I **did** receive a TCP/IP joke.

Asynchronous Function Call in PHP

This old question has a new answer. There are a few "async" solutions for PHP this days (which are equivalent to Python's multiprocess in the sense that they spawn new independent PHP processes rather than manage it at the framework level)

The two solutions I have seen are

Give them a try!

Difference between PACKETS and FRAMES

Packets and Frames are the names given to Protocol data units (PDUs) at different network layers

  • Segments/Datagrams are units of data in the Transport Layer.

    In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):

    Datagram

    A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.

  • Packets are units of data in the Network Layer (IP in case of the Internet)

  • Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).

enter image description here

Getting the 'external' IP address in Java

An alternative solution is to execute an external command, obviously, this solution limits the portability of the application.

For example, for an application that runs on Windows, a PowerShell command can be executed through jPowershell, as shown in the following code:

public String getMyPublicIp() {
    // PowerShell command
    String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
    String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();

    // Connection failed
    if (powerShellOut.contains("InvalidOperation")) {
        powerShellOut = null;
    }
    return powerShellOut;
}

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).

How to read all of Inputstream in Server Socket JAVA

The problem you have is related to TCP streaming nature.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

In client you need to write:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 Byte indicating type (For example, it could also be 2 or whatever).
  • 1 Byte (or whatever) for length of message
  • N Bytes for the value (N is indicated in length).

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

This is just a suggestion of a possible protocol. You could also get rid of "Type".

So it would be something like:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

socket connect() vs bind()

The one liner : bind() to own address, connect() to remote address.

Quoting from the man page of bind()

bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called "assigning a name to a socket".

and, from the same for connect()

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr.

To clarify,

  • bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.]
  • connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

TCP: can two different sockets share a port?

Theoretically, yes. Practice, not. Most kernels (incl. linux) doesn't allow you a second bind() to an already allocated port. It weren't a really big patch to make this allowed.

Conceptionally, we should differentiate between socket and port. Sockets are bidirectional communication endpoints, i.e. "things" where we can send and receive bytes. It is a conceptional thing, there is no such field in a packet header named "socket".

Port is an identifier which is capable to identify a socket. In case of the TCP, a port is a 16 bit integer, but there are other protocols as well (for example, on unix sockets, a "port" is essentially a string).

The main problem is the following: if an incoming packet arrives, the kernel can identify its socket by its destination port number. It is a most common way, but it is not the only possibility:

  • Sockets can be identified by the destination IP of the incoming packets. This is the case, for example, if we have a server using two IPs simultanously. Then we can run, for example, different webservers on the same ports, but on the different IPs.
  • Sockets can be identified by their source port and ip as well. This is the case in many load balancing configurations.

Because you are working on an application server, it will be able to do that.

Comparing HTTP and FTP for transferring files

I just benchmarked a file transfer over both FTP and HTTP :

  • over two very good server connections
  • using the same 1GB .zip file
  • under the same network conditions (tested one after the other)

The result:

  • using FTP: 6 minutes
  • using HTTP: 4 minutes
  • using a concurrent http downloader software (fdm): 1 minute

So, basically under a "real life" situation:

1) HTTP is faster than FTP when downloading one big file.

2) HTTP can use parallel chunk download which makes it 6x times faster than FTP depending on the network conditions.

C: socket connection timeout

Set the socket non-blocking, and use select() (which takes a timeout parameter). If a non-blocking socket is trying to connect, then select() will indicate that the socket is writeable when the connect() finishes (either successfully or unsuccessfully). You then use getsockopt() to determine the outcome of the connect():

int main(int argc, char **argv) {
    u_short port;                /* user specified port number */
    char *addr;                  /* will be a pointer to the address */
    struct sockaddr_in address;  /* the libc network address data structure */
    short int sock = -1;         /* file descriptor for the network socket */
    fd_set fdset;
    struct timeval tv;

    if (argc != 3) {
        fprintf(stderr, "Usage %s <port_num> <address>\n", argv[0]);
        return EXIT_FAILURE;
    }

    port = atoi(argv[1]);
    addr = argv[2];

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
    address.sin_port = htons(port);            /* translate int2port num */

    sock = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(sock, F_SETFL, O_NONBLOCK);

    connect(sock, (struct sockaddr *)&address, sizeof(address));

    FD_ZERO(&fdset);
    FD_SET(sock, &fdset);
    tv.tv_sec = 10;             /* 10 second timeout */
    tv.tv_usec = 0;

    if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
    {
        int so_error;
        socklen_t len = sizeof so_error;

        getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);

        if (so_error == 0) {
            printf("%s:%d is open\n", addr, port);
        }
    }

    close(sock);
    return 0;
}

Set width of a "Position: fixed" div relative to parent div

fixed position is a bit tricky (indeed impossible), but position: sticky is doing the trick beautifully:

<div class='container'>
  <header>This is the header</header>
  <section>
    ... long lorem ipsum
  </section>
</div>


body {
  text-align: center;  
}

.container {
  text-align: left;
  max-width: 30%;
  margin: 0 auto;
}


header {
  line-height: 2rem;
  outline: 1px solid red;
  background: #fff;
  padding: 1rem;

  position: sticky;
  top: 0;
}

see the codepen sample

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

SQL: How do I SELECT only the rows with a unique value on certain column?

Assuming your table of data is called ProjectInfo:

SELECT DISTINCT Contract, Activity
    FROM ProjectInfo
    WHERE Contract = (SELECT Contract
                          FROM (SELECT DISTINCT Contract, Activity
                                    FROM ProjectInfo) AS ContractActivities
                          GROUP BY Contract
                          HAVING COUNT(*) = 1);

The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.

Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem (or sessionStorage.setItem) is called.

One solution is to do a try/catch or Modernizr check in each instance of using setItem.

However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:

https://gist.github.com/philfreo/68ea3cd980d72383c951

// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
    try {
        localStorage.setItem('localStorage', 1);
        localStorage.removeItem('localStorage');
    } catch (e) {
        Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function() {};
        alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
    }
}

ASP MVC href to a controller/view

Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod

 <a href="~/Home/Download_Excel_File" />

Serving static web resources in Spring Boot & Spring Security application

Here is the ultimate solution, after 20+ hours of research.

Step 1. Add 'MvcConfig.java' to your project.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
    }
}

Step 2. Add configure(WebSecurity web) override to your SecurityConfig class

@Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**");
    }

Step 3. Place all static resources in webapp/resources/..

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

How can I convert a hex string to a byte array?

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

How can I return the current action in an ASP.NET MVC view?

Use the ViewContext and look at the RouteData collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers.

download file using an ajax request

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a spreadsheet file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.xlsx";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following link.

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

Auto logout with Angularjs based on idle user

I wrote a module called Ng-Idle that may be useful to you in this situation. Here is the page which contains instructions and a demo.

Basically, it has a service that starts a timer for your idle duration that can be disrupted by user activity (events, such as clicking, scrolling, typing). You can also manually interrupt the timeout by calling a method on the service. If the timeout is not disrupted, then it counts down a warning where you could alert the user they are going to be logged out. If they do not respond after the warning countdown reaches 0, an event is broadcasted that your application can respond to. In your case, it could issue a request to kill their session and redirect to a login page.

Additionally, it has a keep-alive service that can ping some URL at an interval. This can be used by your app to keep a user's session alive while they are active. The idle service by default integrates with the keep-alive service, suspending the pinging if they become idle, and resuming it when they return.

All the info you need to get started is on the site with more details in the wiki. However, here's a snippet of config showing how to sign them out when they time out.

angular.module('demo', ['ngIdle'])
// omitted for brevity
.config(function(IdleProvider, KeepaliveProvider) {
  IdleProvider.idle(10*60); // 10 minutes idle
  IdleProvider.timeout(30); // after 30 seconds idle, time the user out
  KeepaliveProvider.interval(5*60); // 5 minute keep-alive ping
})
.run(function($rootScope) {
    $rootScope.$on('IdleTimeout', function() {
        // end their session and redirect to login
    });
});

Concatenating two one-dimensional NumPy arrays

The first parameter to concatenate should itself be a sequence of arrays to concatenate:

numpy.concatenate((a,b)) # Note the extra parentheses.

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

Issue can also appeared when you use per example @EnableMongoRepositories(YOUR_MONGO_REPOSITORIES_PACKAGE) and later you renamed the package name or moved it in another place.

Very often faced it within a multi-module maven project and spring boot

jQuery click event not working in mobile browsers

I know this is a resolved old topic, but I just answered a similar question, and though my answer could help someone else as it covers other solution options:

Click events work a little differently on touch enabled devices. There is no mouse, so technically there is no click. According to this article - http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html - due to memory limitations, click events are only emulated and dispatched from anchor and input elements. Any other element could use touch events, or have click events manually initialized by adding a handler to the raw html element, for example, to force click events on list items:

$('li').each(function(){
    this.onclick = function() {}
});

Now click will be triggered by li, therefore can be listened by jQuery.


On your case, you could just change the listener to the anchor element as very well put by @mason81, or use a touch event on the li:

$('.menu').on('touchstart', '.publications', function(){
    $('#filter_wrapper').show();
});

Here is a fiddle with a few experiments - http://jsbin.com/ukalah/9/edit

How can I add a line to a file in a shell script?

sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just

echo "c1, c2, ... " >> file
cat testfile.csv >> file

?

PHP cURL HTTP CODE return 0

If you connect with the server, then you can get a return code from it, otherwise it will fail and you get a 0. So if you try to connect to "www.google.com/lksdfk" you will get a return code of 400, if you go directly to google.com, you will get 302 (and then 200 if you forward to the next page... well I do because it forwards to google.com.br, so you might not get that), and if you go to "googlecom" you will get a 0 (host no found), so with the last one, there is nobody to send a code back.

Tested using the code below.

<?php

$html_brand = "www.google.com";
$ch = curl_init();

$options = array(
    CURLOPT_URL            => $html_brand,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER         => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING       => "",
    CURLOPT_AUTOREFERER    => true,
    CURLOPT_CONNECTTIMEOUT => 120,
    CURLOPT_TIMEOUT        => 120,
    CURLOPT_MAXREDIRS      => 10,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch); 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ( $httpCode != 200 ){
    echo "Return code is {$httpCode} \n"
        .curl_error($ch);
} else {
    echo "<pre>".htmlspecialchars($response)."</pre>";
}

curl_close($ch);

How can I make a button redirect my page to another page?

try

<button onclick="window.location.href='b.php'">Click me</button>

How to use mongoose findOne

Use obj[0].nick and you will get desired result,

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

127 Return code from $?

Generally it means:

127 - command not found

but it can also mean that the command is found,
but a library that is required by the command is NOT found.

Java: Insert multiple rows into MySQL with PreparedStatement

In case you have auto increment in the table and need to access it.. you can use the following approach... Do test before using because getGeneratedKeys() in Statement because it depends on driver used. The below code is tested on Maria DB 10.0.12 and Maria JDBC driver 1.2

Remember that increasing batch size improves performance only to a certain extent... for my setup increasing batch size above 500 was actually degrading the performance.

public Connection getConnection(boolean autoCommit) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(autoCommit);
    return conn;
}

private void testBatchInsert(int count, int maxBatchSize) {
    String querySql = "insert into batch_test(keyword) values(?)";
    try {
        Connection connection = getConnection(false);
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean success = true;
        int[] executeResult = null;
        try {
            pstmt = connection.prepareStatement(querySql, Statement.RETURN_GENERATED_KEYS);
            for (int i = 0; i < count; i++) {
                pstmt.setString(1, UUID.randomUUID().toString());
                pstmt.addBatch();
                if ((i + 1) % maxBatchSize == 0 || (i + 1) == count) {
                    executeResult = pstmt.executeBatch();
                }
            }
            ResultSet ids = pstmt.getGeneratedKeys();
            for (int i = 0; i < executeResult.length; i++) {
                ids.next();
                if (executeResult[i] == 1) {
                    System.out.println("Execute Result: " + i + ", Update Count: " + executeResult[i] + ", id: "
                            + ids.getLong(1));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (connection != null) {
                if (success) {
                    connection.commit();
                } else {
                    connection.rollback();
                }
                connection.close();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

How to update Git clone

git pull origin master

this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.

Vue-router redirect on page not found (404)

This answer may come a bit late but I have found an acceptable solution. My approach is a bit similar to @Mani one but I think mine is a bit more easy to understand.

Putting it into global hook and into the component itself are not ideal, global hook checks every request so you will need to write a lot of conditions to check if it should be 404 and window.location.href in the component creation is too late as the request has gone into the component already and then you take it out.

What I did is to have a dedicated url for 404 pages and have a path * that for everything that not found.

{ path: '/:locale/404', name: 'notFound', component: () => import('pages/Error404.vue') },
{ path: '/:locale/*', 
  beforeEnter (to) {
    window.location = `/${to.params.locale}/404`
  }
}

You can ignore the :locale as my site is using i18n so that I can make sure the 404 page is using the right language.

On the side note, I want to make sure my 404 page is returning httpheader 404 status code instead of 200 when page is not found. The solution above would just send you to a 404 page but you are still getting 200 status code. To do this, I have my nginx rule to return 404 status code on location /:locale/404

server {
    listen                      80;
    server_name                 localhost;

    error_page  404 /index.html;
    location ~ ^/.*/404$ {
      root   /usr/share/nginx/html;
      internal;
    }

    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
      rewrite ^(.+)$ /index.html last;
    }

    location = /50x.html {
      root   /usr/share/nginx/html;
    }
}

Maven error :Perhaps you are running on a JRE rather than a JDK?

I faced the issue even though JAVA_HOME was pointing to JDK. It took time to figure out why it was throwing the exception.

The issue was I set JAVA_HOME as admin user on my window machine. You need to add JAVA_HOME environment variable pointing to right JDK to your user profile environment variable settings.

How to check if an object is a list or tuple (but not string)?

H = "Hello"

if type(H) is list or type(H) is tuple:
    ## Do Something.
else
    ## Do Something.

How do I URl encode something in Node.js?

The built-in module querystring is what you're looking for:

var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

Most efficient T-SQL way to pad a varchar on the left to a certain length?

select right(replicate(@padchar, @len) + @str, @len)

to call onChange event after pressing Enter key

pressing Enter when the focus in on a form control (input) normally triggers a submit (onSubmit) event on the form itself (not the input) so you could bind your this.handleInput to the form onSubmit.

Alternatively you could bind it to the blur (onBlur) event on the input which happens when the focus is removed (e.g. tabbing to the next element that can get focus)

How to keep a Python script output window open?

A simple hack to keep the window open:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

The counter is so the code won’t repeat itself.

How to read an entire file to a string using C#?

you can read a text from a text file in to string as follows also

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}

Laravel Check If Related Model Exists

In php 7.2+ you can't use count on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:

$model->relation()->exists()

generic solution working on all the relation types (pre php 7.2):

if (count($model->relation))
{
  // exists
}

This will work for every relation since dynamic properties return Model or Collection. Both implement ArrayAccess.

So it goes like this:

single relations: hasOne / belongsTo / morphTo / morphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

to-many relations: hasMany / belongsToMany / morphMany / morphToMany / morphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Here is my solution:

dependencies: Gmaps.js, jQuery

var Maps = function($) {
   var lost_addresses = [],
       geocode_count  = 0;

   var addMarker = function() { console.log('Marker Added!') };

   return {
     getGecodeFor: function(addresses) {
        var latlng;
        lost_addresses = [];
        for(i=0;i<addresses.length;i++) {
          GMaps.geocode({
            address: addresses[i],
            callback: function(response, status) {
              if(status == google.maps.GeocoderStatus.OK) {
                addMarker();
              } else if(status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                lost_addresses.push(addresses[i]);
              }

               geocode_count++;
               // notify listeners when the geocode is done
               if(geocode_count == addresses.length) {
                 $.event.trigger({ type: 'done:geocoder' });
               }
            }
          });
        }
     },
     processLostAddresses: function() {
       if(lost_addresses.length > 0) {
         this.getGeocodeFor(lost_addresses);
       }
     }
   };
}(jQuery);

Maps.getGeocodeFor(address);

// listen to done:geocode event and process the lost addresses after 1.5s
$(document).on('done:geocode', function() {
  setTimeout(function() {
    Maps.processLostAddresses();
  }, 1500);
});

Typescript Date Type?

The answer is super simple, the type is Date:

const d: Date = new Date(); // but the type can also be inferred from "new Date()" already

It is the same as with every other object instance :)

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

How to display binary data as image - extjs 4

Need to convert it in base64.

JS have btoa() function for it.

For example:

var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);

But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.

Update:

Need to write simple hex to base64 converter:

function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

And use it:

img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');

See working example with your hex data on jsfiddle

How to convert a currency string to a double with jQuery or Javascript?

For anyone looking for a solution in 2021 you can use Currency.js.

After much research this was the most reliable method I found for production, I didn't have any issues so far. In addition it's very active on Github.

currency(123);      // 123.00
currency(1.23);     // 1.23
currency("1.23")    // 1.23
currency("$12.30")  // 12.30

var value = currency("123.45");
currency(value);    // 123.45

Changing all files' extensions in a folder with one command on Windows

NOTE: not for Windows

Using ren-1.0 the correct form is:

"ren *.*" "#2.jpg"

From man ren

The replacement pattern is another filename with embedded wildcard indexes, each of which consists of the character # followed by a digit from 1 to 9. In the new name of a matching file, the wildcard indexes are replaced by the actual characters that matched the referenced wildcards in the original filename.

and

Note that the shell normally expands the wildcards * and ?, which in the case of ren is undesirable. Thus, in most cases it is necessary to enclose the search pattern in quotes.

Change one value based on another value in pandas

df['FirstName']=df['ID'].apply(lambda x: 'Matt' if x==103 else '')
df['LastName']=df['ID'].apply(lambda x: 'Jones' if x==103 else '')

How to check if a file exists from a url

You can use the function file_get_contents();

if(file_get_contents('https://example.com/example.txt')) {
    //File exists
}

MySQL Insert query doesn't work with WHERE clause

You use the WHERE clause for UPDATE queries. When you INSERT, you are assuming that the row doesn't exist.

The OP's statement would then become;

UPDATE Users SET weight = 160, desiredWeight = 45 where id = 1;

In MySQL, if you want to INSERT or UPDATE, you can use the REPLACE query with a WHERE clause. If the WHERE doesn't exist, it INSERTS, otherwise it UPDATES.

EDIT

I think that Bill Karwin's point is important enough to pull up out of the comments and make it very obvious. Thanks Bill, it has been too long since I have worked with MySQL, I remembered that I had issues with REPLACE, but I forgot what they were. I should have looked it up.

That's not how MySQL's REPLACE works. It does a DELETE (which may be a no-op if the row does not exist), followed by an INSERT. Think of the consequences vis. triggers and foreign key dependencies. Instead, use INSERT...ON DUPLICATE KEY UPDATE.

WAMP won't turn green. And the VCRUNTIME140.dll error

WAMP is not turning GREEN? Don`t panic

First of all check your windows update by searching "Windows Update"

or

Download updates from microsoft windows site (i had windows 7 x64 updated to service pack 1 full) windows 7 Service pack 1 download

Now there are some more downloads that support WAMP for installing time

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

VC9 Packages (Visual C++ 2008 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=5582 https://www.microsoft.com/en-us/download/details.aspx?id=2092

VC10 Packages (Visual C++ 2010 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=8328 https://www.microsoft.com/en-us/download/details.aspx?id=13523

VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679

VC13 Packages[/b] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe

VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=52685

VC Packages x64 (Visual C++ 2017)

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

How to access URL segment(s) in blade in Laravel 5?

Try this

{{ Request::segment(1) }}

How to create a folder with name as current date in batch (.bat) files

This works for me, try:

ECHO %DATE:~7,2%_%DATE:~4,2%_%DATE:~12,2%

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

Semantic Difference

According to HTML 5.2:

When specified on an element, [the hidden attribute] indicates that the element is not yet, or is no longer, directly relevant to the page’s current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user.

Examples include a tab list where some panels are not exposed, or a log-in screen that goes away after a user logs in. I like to call these things “temporally relevant” i.e. they are relevant based on timing.

On the other hand, ARIA 1.1 says:

[The aria-hidden state] indicates whether an element is exposed to the accessibility API.

In other words, elements with aria-hidden="true" are removed from the accessibility tree, which most assistive technology honors, and elements with aria-hidden="false" will definitely be exposed to the tree. Elements without the aria-hidden attribute are in the "undefined (default)" state, which means user agents should expose it to the tree based on its rendering. E.g. a user agent may decide to remove it if its text color matches its background color.

Now let’s compare semantics. It’s appropriate to use hidden, but not aria-hidden, for an element that is not yet “temporally relevant”, but that might become relevant in the future (in which case you would use dynamic scripts to remove the hidden attribute). Conversely, it’s appropriate to use aria-hidden, but not hidden, on an element that is always relevant, but with which you don’t want to clutter the accessibility API; such elements might include “visual flair”, like icons and/or imagery that are not essential for the user to consume.

Effective Difference

The semantics have predictable effects in browsers/user agents. The reason I make a distinction is that user agent behavior is recommended, but not required by the specifications.

The hidden attribute should hide an element from all presentations, including printers and screen readers (assuming these devices honor the HTML specs). If you want to remove an element from the accessibility tree as well as visual media, hidden would do the trick. However, do not use hidden just because you want this effect. Ask yourself if hidden is semantically correct first (see above). If hidden is not semantically correct, but you still want to visually hide the element, you can use other techniques such as CSS.

Elements with aria-hidden="true" are not exposed to the accessibility tree, so for example, screen readers won’t announce them. This technique should be used carefully, as it will provide different experiences to different users: accessible user agents won’t announce/render them, but they are still rendered on visual agents. This can be a good thing when done correctly, but it has the potential to be abused.

Syntactic Difference

Lastly, there is a difference in syntax between the two attributes.

hidden is a boolean attribute, meaning if the attribute is present it is true—regardless of whatever value it might have—and if the attribute is absent it is false. For the true case, the best practice is to either use no value at all (<div hidden>...</div>), or the empty string value (<div hidden="">...</div>). I would not recommend hidden="true" because someone reading/updating your code might infer that hidden="false" would have the opposite effect, which is simply incorrect.

aria-hidden, by contrast, is an enumerated attribute, allowing one of a finite list of values. If the aria-hidden attribute is present, its value must be either "true" or "false". If you want the "undefined (default)" state, remove the attribute altogether.


Further reading: https://github.com/chharvey/chharvey.github.io/wiki/Hidden-Content

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

If you have a date object:

_x000D_
_x000D_
let date = new Date()_x000D_
let result = date.toISOString().split`T`[0]_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

or

_x000D_
_x000D_
let date = new Date()_x000D_
let result = date.toISOString().slice(0, 10)_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Loop through an array php

Using foreach loop without key

foreach($array as $item) {
    echo $item['filename'];
    echo $item['filepath'];

    // to know what's in $item
    echo '<pre>'; var_dump($item);
}

Using foreach loop with key

foreach($array as $i => $item) {
    echo $item[$i]['filename'];
    echo $item[$i]['filepath'];

    // $array[$i] is same as $item
}

Using for loop

for ($i = 0; $i < count($array); $i++) {
    echo $array[$i]['filename'];
    echo $array[$i]['filepath'];
}

var_dump is a really useful function to get a snapshot of an array or object.

jQuery map vs. each

1: The arguments to the callback functions are reversed.

.each()'s, $.each()'s, and .map()'s callback function take the index first, and then the element

function (index, element) 

$.map()'s callback has the same arguments, but reversed

function (element, index)

2: .each(), $.each(), and .map() do something special with this

each() calls the function in such a way that this points to the current element. In most cases, you don't even need the two arguments in the callback function.

function shout() { alert(this + '!') }

result = $.each(['lions', 'tigers', 'bears'], shout)

// result == ['lions', 'tigers', 'bears']

For $.map() the this variable refers to the global window object.

3: map() does something special with the callback's return value

map() calls the function on each element, and stores the result in a new array, which it returns. You usually only need to use the first argument in the callback function.

function shout(el) { return el + '!' }

result = $.map(['lions', 'tigers', 'bears'], shout)

// result == ['lions!', 'tigers!', 'bears!']

How to execute a java .class from the command line

You have no valid main method... The signature should be: public static void main(String[] args);

Hence, in your case the code should look like this:

public class Echo {
    public static void main (String[] arg) {

            System.out.println(arg[0]);
    }
}

Edit: Please note that Oscar is also right in that you are missing . in your classpath, you would run into the problem I solve after you have dealt with that error.

Command output redirect to file and terminal

It is worth mentioning that 2>&1 means that standard error will be redirected too, together with standard output. So

someCommand | tee someFile

gives you just the standard output in the file, but not the standard error: standard error will appear in console only. To get standard error in the file too, you can use

someCommand 2>&1 | tee someFile

(source: In the shell, what is " 2>&1 "? ). Finally, both the above commands will truncate the file and start clear. If you use a sequence of commands, you may want to get output&error of all of them, one after another. In this case you can use -a flag to "tee" command:

someCommand 2>&1 | tee -a someFile

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

In the case you are on something else then windows and your boss is forcing you to use azure devops, and you don't want to use SSH, and you want to use to plain old way, do the following.

You have to enable 'Alternate credentials' (I know it's annoying) or you need to create an access token. Creating an access token in this case is more like a temporary random password. If you use the windows tooling it is done for you.

Any way, go to Security in the profile context menu in the right upper corner.

Security settings

Then if your boss/manager/dude that has the admin rights is favoring you the 'Alternate credentials' are enabled. Otherwise accept your fate and generate a 'Personal access token'.

Security settings

Why is lock(this) {...} bad?

There is very good article about it http://bytes.com/topic/c-sharp/answers/249277-dont-lock-type-objects by Rico Mariani, performance architect for the Microsoft® .NET runtime

Excerpt:

The basic problem here is that you don't own the type object, and you don't know who else could access it. In general, it's a very bad idea to rely on locking an object you didn't create and don't know who else might be accessing. Doing so invites deadlock. The safest way is to only lock private objects.

Gradle version 2.2 is required. Current version is 2.10

Based on https://developer.android.com/studio/releases/gradle-plugin.html ...

The following table lists which version of Gradle is required for each version of the Android plugin for Gradle. For the best performance, you should use the latest possible version of both Gradle and the Android plugin.

So, the Plugin version with Required Gradle version should be match.

enter image description here

Why does viewWillAppear not get called when an app comes back from the background?

Use Notification Center in the viewDidLoad: method of your ViewController to call a method and from there do what you were supposed to do in your viewWillAppear: method. Calling viewWillAppear: directly is not a good option.

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationIsActive:) 
        name:UIApplicationDidBecomeActiveNotification 
        object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationEnteredForeground:) 
        name:UIApplicationWillEnterForegroundNotification
        object:nil];
}

- (void)applicationIsActive:(NSNotification *)notification {
    NSLog(@"Application Did Become Active");
}

- (void)applicationEnteredForeground:(NSNotification *)notification {
    NSLog(@"Application Entered Foreground");
}

Is there a way to make numbers in an ordered list bold?

You also could put <span style="font-weight:normal"> around a,b,c and then bold the ul in the CSS.

Example

ul {
    font-weight: bold;
}

<ul><li><span style="font-weight:normal">a</span></li></ul>

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

Java HashMap performance optimization / alternative

One thing I notice in your hashCode() method is that the order of the elements in the arrays a[] and b[] don't matter. Thus (a[]={1,2,3}, b[]={99,100}) will hash to the same value as (a[]={3,1,2}, b[]={100,99}). Actually all keys k1 and k2 where sum(k1.a)==sum(k2.a) and sum(k1.b)=sum(k2.b) will result in collisions. I suggest assigning a weight to each position of the array:

hash = hash * 5381 + (c0*a[0] + c1*a[1]);
hash = hash * 5381 + (c0*b[0] + c1*b[1] + c3*b[2]);

where, c0, c1 and c3 are distinct constants (you can use different constants for b if necessary). That should even out things a bit more.

pull out p-values and r-squared from a linear regression

Use:

(summary(fit))$coefficients[***num***,4]

where num is a number which denotes the row of the coefficients matrix. It will depend on how many features you have in your model and which one you want to pull out the p-value for. For example, if you have only one variable there will be one p-value for the intercept which will be [1,4] and the next one for your actual variable which will be [2,4]. So your num will be 2.

Remove json element

try this

json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)

What does "javax.naming.NoInitialContextException" mean?

It basically means that the application wants to perform some "naming operations" (e.g. JNDI or LDAP lookups), and it didn't have sufficient information available to be able to create a connection to the directory server. As the docs for the exception state,

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

And if you dutifully have a look at the javadocs for InitialContext, they describe quite well how the initial context is constructed, and what your options are for supplying the address/credentials/etc.

If you have a go at creating the context and get stuck somewhere else, please post back explaining what you've done so far and where you're running aground.

Can you install and run apps built on the .NET framework on a Mac?

You can use a .Net environment Visual studio, Take a look at the differences with the PC version.

A lighter editor would be Visual Code

Alternatives :

  1. Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)

  2. Virtual machine (VMWare Fusion perhaps)

  3. Update your codebase to .Net Core, (before choosing this option take a look at this migration process)

    • .Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux

    • As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.

[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license

dataframe: how to groupBy/count then filter on count in Scala

So, is that a behavior to expect, a bug

Truth be told I am not sure. It looks like parser is interpreting count not as a column name but a function and expects following parentheses. Looks like a bug or at least a serious limitation of the parser.

is there a canonical way to go around?

Some options have been already mentioned by Herman and mattinbits so here more SQLish approach from me:

import org.apache.spark.sql.functions.count

df.groupBy("x").agg(count("*").alias("cnt")).where($"cnt"  > 2)

Java output formatting for Strings

EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though

Why not just generate a whitespace string dynamically to insert into the statement.

So if you want them all to start on the 50th character...

String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);

Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.

How to set the width of a RaisedButton in Flutter?

If the button is placed in a Flex widget (including Row & Column), you can wrap it using an Expanded Widget to fill the available space.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

setting an environment variable in virtualenv

In case you're using virtualenvwrapper (I highly recommend doing so), you can define different hooks (preactivate, postactivate, predeactivate, postdeactivate) using the scripts with the same names in $VIRTUAL_ENV/bin/. You need the postactivate hook.

$ workon myvenv

$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
export DJANGO_DEBUG=True
export S3_KEY=mykey
export S3_SECRET=mysecret

$ echo $DJANGO_DEBUG
True

If you want to keep this configuration in your project directory, simply create a symlink from your project directory to $VIRTUAL_ENV/bin/postactivate.

$ rm $VIRTUAL_ENV/bin/postactivate
$ ln -s .env/postactivate $VIRTUAL_ENV/bin/postactivate

You could even automate the creation of the symlinks each time you use mkvirtualenv.

Cleaning up on deactivate

Remember that this wont clean up after itself. When you deactivate the virtualenv, the environment variable will persist. To clean up symmetrically you can add to $VIRTUAL_ENV/bin/predeactivate.

$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
unset DJANGO_DEBUG

$ deactivate

$ echo $DJANGO_DEBUG

Remember that if using this for environment variables that might already be set in your environment then the unset will result in them being completely unset on leaving the virtualenv. So if that is at all probable you could record the previous value somewhere temporary then read it back in on deactivate.

Setup:

$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
if [[ -n $SOME_VAR ]]
then
    export SOME_VAR_BACKUP=$SOME_VAR
fi
export SOME_VAR=apple

$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
if [[ -n $SOME_VAR_BACKUP ]]
then
    export SOME_VAR=$SOME_VAR_BACKUP
    unset SOME_VAR_BACKUP
else
    unset SOME_VAR
fi

Test:

$ echo $SOME_VAR
banana

$ workon myenv

$ echo $SOME_VAR
apple

$ deactivate

$ echo $SOME_VAR
banana

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

Call a Class From another class

Simply create an instance of Class2 and call the desired method.

Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/

How to add Certificate Authority file in CentOS 7

copy your certificates inside

/etc/pki/ca-trust/source/anchors/

then run the following command

update-ca-trust

Where is the syntax for TypeScript comments documented?

You can use comments like in regular JavaScript:

1 Introduction

[...] TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax.

2 Basic Concepts

[...] This document describes the syntactic grammar added by TypeScript [...]

Source: TypeScript Language Specification


The only two mentions of the word "comments" in the spec are:

1 Introduction

[...] TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables.

11.1.1 Source Files Dependencies

[...] A comment of the form /// <reference path="..."/> adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.

How to remove a column from an existing table?

To add columns in existing table:

ALTER TABLE table_name
 ADD
 column_name DATATYPE NULL  

To delete columns in existing table:

ALTER TABLE table_name
DROP COLUMN column_name

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I don't know why but its happened when you submit a form inside a page to itself by the POST method.

So change the method="post" to method="get" or remove action="anyThings.any" from your <form> tag.

Basic calculator in Java

import java.util.Scanner; import javax.swing.JOptionPane;

public class javaCalculator {

public static void main(String[] args) 
{
    int num1;
    int num2;
    String operation;


    Scanner input = new Scanner(System.in);

    System.out.println("please enter the first number");
    num1 = input.nextInt();

    System.out.println("please enter the second number");
    num2 = input.nextInt();

    Scanner op = new Scanner(System.in);

    System.out.println("Please enter operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("your answer is" + (num1 + num2));
    }
   else if  (operation.equals("-"))
    {
        System.out.println("your answer is" + (num1 - num2));
    }

  else if (operation.equals("/"))
    {
        System.out.println("your answer is" + (num1 / num2));
    }
   else if (operation.equals("*"))
    {
        System.out.println("your answer is" + (num1 * num2));
    }
   else 
    {
       System.out.println("Wrong selection");
    }


}

}

Get button click inside UITableViewCell

@Mani answer is good, however tags of views inside cell's contentView often are used for other purposes. You can use cell's tag instead (or cell's contentView tag):

1) In your cellForRowAtIndexPath: method, assign cell's tag as index:

cell.tag = indexPath.row; // or cell.contentView.tag...

2) Add target and action for your button as below:

[cell.yourbutton addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

3) Create method that returns row of the sender (thanks @Stenio Ferreira):

- (NSInteger)rowOfSender:(id)sender
{
    UIView *superView = sender.superview;
    while (superView) {
        if ([superView isKindOfClass:[UITableViewCell class]])
            break;
        else
            superView = superView.superview;
    }

    return superView.tag;
}

4) Code actions based on index:

-(void)yourButtonClicked:(UIButton*)sender
{
     NSInteger index = [self rowOfSender:sender];
     // Your code here
}

Adding a background image to a <div> element

For the most part, the method is the same as setting the whole body

.divi{
    background-image: url('path');
}

</style>

<div class="divi"></div>

Changing the Git remote 'push to' default

To change which upstream remote is "wired" to your branch, use the git branch command with the upstream configuration flag.

Ensure the remote exists first:

git remote -vv

Set the preferred remote for the current (checked out) branch:

git branch --set-upstream-to <remote-name>

Validate the branch is setup with the correct upstream remote:

git branch -vv

Iterate over object keys in node.js

adjust his code:

Object.prototype.each = function(iterateFunc) {
        var counter = 0,
keys = Object.keys(this),
currentKey,
len = keys.length;
        var that = this;
        var next = function() {

            if (counter < len) {
                currentKey = keys[counter++];
                iterateFunc(currentKey, that[currentKey]);

                next();
            } else {
                that = counter = keys = currentKey = len = next = undefined;
            }
        };
        next();
    };

    ({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
        // do things
        console.log(key);
    });

How to make div fixed after you scroll to that div?

<script>
if($(window).width() >= 1200){
    (function($) {
        var element = $('.to_move_content'),
            originalY = element.offset().top;

        // Space between element and top of screen (when scrolling)
        var topMargin = 10;

        // Should probably be set in CSS; but here just for emphasis
        element.css('position', 'relative');

        $(window).on('scroll', function(event) {
            var scrollTop = $(window).scrollTop();

            element.stop(false, false).animate({
                top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
            }, 0);
        });
    })(jQuery);
}

Try this ! just add class .to_move_content to you div

Make the current Git branch a master branch

I found the answer I wanted in the blog post Replace the master branch with another branch in git:

git checkout feature_branch
git merge -s ours --no-commit master
git commit      # Add a message regarding the replacement that you just did
git checkout master
git merge feature_branch

It's essentially the same as Cascabel's answer. Except that the "option" he added below his solution is already embedded in my main code block.

It's easier to find this way.

I'm adding this as a new answer, because if I need this solution later, I want to have all the code I am going to use in one code block.

Otherwise, I may copy-paste, then read details below to see the line that I should have changed - after I already executed it.

What are the rules for casting pointers in C?

When thinking about pointers, it helps to draw diagrams. A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.

d in main is a pointer to c which is of type char. A char is one byte of memory, so when d is dereferenced, you get the value in that one byte of memory. In the diagram below, each cell represents one byte.

-+----+----+----+----+----+----+-
 |    | c  |    |    |    |    | 
-+----+----+----+----+----+----+-
       ^~~~
       | char
       d

When you cast d to int*, you're saying that d really points to an int value. On most systems today, an int occupies 4 bytes.

-+----+----+----+----+----+----+-
 |    | c  | ?1 | ?2 | ?3 |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       (int*)d

When you dereference (int*)d, you get a value that is determined from these four bytes of memory. The value you get depends on what is in these cells marked ?, and on how an int is represented in memory.

A PC is little-endian, which means that the value of an int is calculated this way (assuming that it spans 4 bytes): * ((int*)d) == c + ?1 * 28 + ?2 * 2¹6 + ?3 * 2²4. So you'll see that while the value is garbage, if you print in in hexadecimal (printf("%x\n", *n)), the last two digits will always be 35 (that's the value of the character '5').

Some other systems are big-endian and arrange the bytes in the other direction: * ((int*)d) == c * 2²4 + ?1 * 2¹6 + ?2 * 28 + ?3. On these systems, you'd find that the value always starts with 35 when printed in hexadecimal. Some systems have a size of int that's different from 4 bytes. A rare few systems arrange int in different ways but you're extremely unlikely to encounter them.

Depending on your compiler and operating system, you may find that the value is different every time you run the program, or that it's always the same but changes when you make even minor tweaks to the source code.

On some systems, an int value must be stored in an address that's a multiple of 4 (or 2, or 8). This is called an alignment requirement. Depending on whether the address of c happens to be properly aligned or not, the program may crash.

In contrast with your program, here's what happens when you have an int value and take a pointer to it.

int x = 42;
int *p = &x;
-+----+----+----+----+----+----+-
 |    |         x         |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       p

The pointer p points to an int value. The label on the arrow correctly describes what's in the memory cell, so there are no surprises when dereferencing it.

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

Use the phpinfo(); function to see the table of settings on your browser and look for the

Configuration File (php.ini) Path

and edit that file. Your computer can have multiple php.ini files, you want to edit the right one.

Also check display_errors = On, html_errors = On and error_reporting = E_ALL inside that file

Restart Apache.

How to have Android Service communicate with Activity

To follow up on @MrSnowflake answer with a code example. This is the XABBER now open source Application class. The Application class is centralising and coordinating Listeners and ManagerInterfaces and more. Managers of all sorts are dynamically loaded. Activity´s started in the Xabber will report in what type of Listener they are. And when a Service start it report in to the Application class as started. Now to send a message to an Activity all you have to do is make your Activity become a listener of what type you need. In the OnStart() OnPause() register/unreg. The Service can ask the Application class for just that listener it need to speak to and if it's there then the Activity is ready to receive.

Going through the Application class you'll see there's a loot more going on then this.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

Windows7 FireFox/Chrome:

    {
       "cmd":["F:\\Program Files\\Mozilla Firefox\\firefox.exe","$file"]
    }

just use your own path of firefox.exe or chrome.exe to replace mine.

Replace firefox.exe or chrome.exe with your own path.

Visual Studio: Relative Assembly References Paths

To expand upon Pavel Minaev's original comment - The GUI for Visual Studio supports relative references with the assumption that your .sln is the root of the relative reference. So if you have a solution C:\myProj\myProj.sln, any references you add in subfolders of C:\myProj\ are automatically added as relative references.

To add a relative reference in a separate directory, such as C:/myReferences/myDLL.dll, do the following:

  1. Add the reference in Visual Studio GUI by right-clicking the project in Solution Explorer and selecting Add Reference...
  2. Find the *.csproj where this reference exist and open it in a text editor
  3. Edit the < HintPath > to be equal to

    <HintPath>..\..\myReferences\myDLL.dll</HintPath>

This now references C:\myReferences\myDLL.dll.

Hope this helps.

Get changes from master into branch in Git

You should be able to just git merge origin/master when you are on your aq branch.

git checkout aq
git merge origin/master

'profile name is not valid' error when executing the sp_send_dbmail command

Did you enable the profile for SQL Server Agent? This a common step that is missed when creating Email profiles in DatabaseMail.

Steps:

  • Right-click on SQL Server Agent in Object Explorer (SSMS)
  • Click on Properties
  • Click on the Alert System tab in the left-hand navigation
  • Enable the mail profile
  • Set Mail System and Mail Profile
  • Click OK
  • Restart SQL Server Agent

How to download fetch response in react as file

I managed to download the file generated by the rest API URL much easier with this kind of code which worked just fine on my local:

    import React, {Component} from "react";
    import {saveAs} from "file-saver";

    class MyForm extends Component {

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(event) {
        event.preventDefault();
        const form = event.target;
        let queryParam = buildQueryParams(form.elements);

        let url = 'http://localhost:8080/...whatever?' + queryParam;

        fetch(url, {
            method: 'GET',
            headers: {
                // whatever
            },
        })
            .then(function (response) {
                    return response.blob();
                }
            )
            .then(function(blob) {
                saveAs(blob, "yourFilename.xlsx");
            })
            .catch(error => {
                //whatever
            })
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} id="whateverFormId">
                <table>
                    <tbody>
                    <tr>
                        <td>
                            <input type="text" key="myText" name="myText" id="myText"/>
                        </td>
                        <td><input key="startDate" name="from" id="startDate" type="date"/></td>
                        <td><input key="endDate" name="to" id="endDate" type="date"/></td>
                    </tr>
                    <tr>
                        <td colSpan="3" align="right">
                            <button>Export</button>
                        </td>
                    </tr>

                    </tbody>
                </table>
            </form>
        );
    }
}

function buildQueryParams(formElements) {
    let queryParam = "";

    //do code here
    
    return queryParam;
}

export default MyForm;

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

jQuery ajax call to REST service

I think there is no need to specify

'http://localhost:8080`" 

in the URI part.. because. if you specify it, You'll have to change it manually for every environment.

Only

"/restws/json/product/get" also works

How to see PL/SQL Stored Function body in Oracle

You can also use DBMS_METADATA:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN') 
from dual

How to vertically align text with icon font?

vertical-align can take a unit value so you can resort to that when needed:

{
  display:inline-block;
  vertical-align: 5px;
}

{
  display:inline-block;
  vertical-align: -5px;
}

how do I get eclipse to use a different compiler version for Java?

Just to clarify, do you have JAVA_HOME set as a system variable or set in Eclipse classpath variables? I'm pretty sure (but not totally sure!) that the system variable is used by the command line compiler (and Ant), but that Eclipse modifies this accroding to the JDK used

How to get the exact local time of client?

Nowadays you can get correct timezone of a user having just one line of code:

const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions

You can then use moment-timezone to parse timezone like:

const currentTime = moment().tz(timezone).format();

How can I profile C++ code running on Linux?

Also worth mentioning are

  1. HPCToolkit (http://hpctoolkit.org/) - Open-source, works for parallel programs and has a GUI with which to look at the results multiple ways
  2. Intel VTune (https://software.intel.com/en-us/vtune) - If you have intel compilers this is very good
  3. TAU (http://www.cs.uoregon.edu/research/tau/home.php)

I have used HPCToolkit and VTune and they are very effective at finding the long pole in the tent and do not need your code to be recompiled (except that you have to use -g -O or RelWithDebInfo type build in CMake to get meaningful output). I have heard TAU is similar in capabilities.

PHP sessions that have already been started

Yes, you can detect if the session is already running by checking isset($_SESSION). However the best answer is simply not to call session_start() more than once.

It should be called very early in your script, possibly even the first line, and then not called again.

If you have it in more than one place in your code then you're asking to get this kind of bug. Cut it down so it's only in one place and can only be called once.

How to receive JSON as an MVC 5 action method parameter

fwiw, this didn't work for me until I had this in the ajax call:

contentType: "application/json; charset=utf-8",

using Asp.Net MVC 4.

What is the maximum number of edges in a directed graph with n nodes?

Directed graph:

Question: What's the maximum number of edges in a directed graph with n vertices?

  • Assume there are no self-loops.
  • Assume there there is at most one edge from a given start vertex to a given end vertex.

Each edge is specified by its start vertex and end vertex. There are n choices for the start vertex. Since there are no self-loops, there are n-1 choices for the end vertex. Multiplying these together counts all possible choices.

Answer: n(n-1)

Undirected graph

Question: What's the maximum number of edges in an undirected graph with n vertices?

  • Assume there are no self-loops.
  • Assume there there is at most one edge from a given start vertex to a given end vertex.

In an undirected graph, each edge is specified by its two endpoints and order doesn't matter. The number of edges is therefore the number of subsets of size 2 chosen from the set of vertices. Since the set of vertices has size n, the number of such subsets is given by the binomial coefficient C(n,2) (also known as "n choose 2"). Using the formula for binomial coefficients, C(n,2) = n(n-1)/2.

Answer: (n*(n-1))/2

How do I overload the square-bracket operator in C#?

Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded, 
                                    but only as pairs.

&&, ||                  They can't be overloaded

() (Conversion operator)        They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be 
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!

Source of the information

For bracket:

public Object this[int index]
{

}

BUT

The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).

From MSDN

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.

Please check if you changed: compileSdkVersion --> implementationSdkVersion by mistake

Get textarea text with javascript or Jquery

READING the <textarea>'s content:

var text1 = document.getElementById('myTextArea').value;     // plain JavaScript
var text2 = $("#myTextArea").val();                          // jQuery

WRITING to the <textarea>':

document.getElementById('myTextArea').value = 'new value';   // plain JavaScript
$("#myTextArea").val('new value');                           // jQuery

See DEMO JSFiddle here.


Do not use .html() or .innerHTML!

jQuery's .html() and JavaScript's .innerHTML should not be used, as they do not pick up changes to the textarea's text.

When the user types on the textarea, the .html() won't return the typed value, but the original one -- check demo fiddle above for an example.

How to modify a text file?

Wrote a small class for doing this cleanly.

import tempfile

class FileModifierError(Exception):
    pass

class FileModifier(object):

    def __init__(self, fname):
        self.__write_dict = {}
        self.__filename = fname
        self.__tempfile = tempfile.TemporaryFile()
        with open(fname, 'rb') as fp:
            for line in fp:
                self.__tempfile.write(line)
        self.__tempfile.seek(0)

    def write(self, s, line_number = 'END'):
        if line_number != 'END' and not isinstance(line_number, (int, float)):
            raise FileModifierError("Line number %s is not a valid number" % line_number)
        try:
            self.__write_dict[line_number].append(s)
        except KeyError:
            self.__write_dict[line_number] = [s]

    def writeline(self, s, line_number = 'END'):
        self.write('%s\n' % s, line_number)

    def writelines(self, s, line_number = 'END'):
        for ln in s:
            self.writeline(s, line_number)

    def __popline(self, index, fp):
        try:
            ilines = self.__write_dict.pop(index)
            for line in ilines:
                fp.write(line)
        except KeyError:
            pass

    def close(self):
        self.__exit__(None, None, None)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        with open(self.__filename,'w') as fp:
            for index, line in enumerate(self.__tempfile.readlines()):
                self.__popline(index, fp)
                fp.write(line)
            for index in sorted(self.__write_dict):
                for line in self.__write_dict[index]:
                    fp.write(line)
        self.__tempfile.close()

Then you can use it this way:

with FileModifier(filename) as fp:
    fp.writeline("String 1", 0)
    fp.writeline("String 2", 20)
    fp.writeline("String 3")  # To write at the end of the file

How to add text to a WPF Label in code?

you can use TextBlock control and assign the text property.

Conversion failed when converting the varchar value 'simple, ' to data type int

If you are converting a varchar to int make sure you do not have decimal places.

For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.

CONVERT(int, replace(FIELD_NAME,'.0',''))

Select All as default value for Multivalue parameter

The accepted answer is correct, but not complete. In order for Select All to be the default option, the Available Values dataset must contain at least 2 columns: value and label. They can return the same data, but their names have to be different. The Default Values dataset will then use value column and then Select All will be the default value. If the dataset returns only 1 column, only the last record's value will be selected in the drop down of the parameter.

How to style a disabled checkbox?

Use the attribute selector in the css

input[disabled]{
  outline:1px solid red; // or whatever
}

for checkbox exclusively use

input[type=checkbox][disabled]{
  outline:1px solid red; // or whatever
}

_x000D_
_x000D_
$('button').click(function() {_x000D_
  const i = $('input');_x000D_
_x000D_
  if (i.is('[disabled]'))_x000D_
    i.attr('disabled', false)_x000D_
  else_x000D_
    i.attr('disabled', true);_x000D_
})
_x000D_
input[type=checkbox][disabled] {_x000D_
  outline: 2px solid red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" value="tasd" disabled />_x000D_
<input type="text" value="text" disabled />_x000D_
<button>disable/enable</button>
_x000D_
_x000D_
_x000D_

Updating property value in properties file without deleting other values

Open the output stream and store properties after you have closed the input stream.

FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();

FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();

ICommand MVVM implementation

@Carlo I really like your implementation of this, but I wanted to share my version and how to use it in my ViewModel

First implement ICommand

public class Command : ICommand
{
    public delegate void ICommandOnExecute();
    public delegate bool ICommandOnCanExecute();

    private ICommandOnExecute _execute;
    private ICommandOnCanExecute _canExecute;

    public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null)
    {
        _execute = onExecuteMethod;
        _canExecute = onCanExecuteMethod;
    }

    #region ICommand Members

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke() ?? true;
    }

    public void Execute(object parameter)
    {
        _execute?.Invoke();
    }

    #endregion
}

Notice I have removed the parameter from ICommandOnExecute and ICommandOnCanExecute and added a null to the constructor

Then to use in the ViewModel

public Command CommandToRun_WithCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        }, () =>
        {
            // Code to check to see if we can run 
            // Return true or false
        });
    }
}

public Command CommandToRun_NoCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        });
    }
}

I just find this way cleaner as I don't need to assign variables and then instantiate, it all done in one go.

How can I assign the output of a function to a variable using bash?

I think init_js should use declare instead of local!

function scan3() {
    declare -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}

How to get the difference between two arrays of objects in JavaScript

import differenceBy from 'lodash/differenceBy'

const myDifferences = differenceBy(Result1, Result2, 'value')

This will return the difference between two arrays of objects, using the key value to compare them. Note two things with the same value will not be returned, as the other keys are ignored.

This is a part of lodash.

Finding the average of a list

as a beginner, I just coded this:

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

total = 0

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

print average(L)

How to convert a char array back to a string?

No, that solution is absolutely correct and very minimal.

Note however, that this is a very unusual situation: Because String is handled specially in Java, even "foo" is actually a String. So the need for splitting a String into individual chars and join them back is not required in normal code.

Compare this to C/C++ where "foo" you have a bundle of chars terminated by a zero byte on one side and string on the other side and many conversions between them due do legacy methods.

Endless loop in C/C++

I would recommend while (1) { } or while (true) { }. It's what most programmers would write, and for readability reasons you should follow the common idioms.

(Ok, so there is an obvious "citation needed" for the claim about most programmers. But from the code I've seen, in C since 1984, I believe it is true.)

Any reasonable compiler would compile all of them to the same code, with an unconditional jump, but I wouldn't be surprised if there are some unreasonable compilers out there, for embedded or other specialized systems.

HTTP status code for update and delete?

Here are some Tips:

DELETE

  • 200 (if you want send some additional data in the Response) or 204 (recommended).

  • 202 Operation deleted has not been committed yet.

  • If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)

Other errors:

  • 400 Bad Request (Malformed syntax or a bad query is strange but possible).
  • 401 Unauthorized Authentication failure
  • 403 Forbidden: Authorization failure or invalid Application ID.
  • 405 Not Allowed. Sure.
  • 409 Resource Conflict can be possible in complex systems.
  • And 501, 502 in case of errors.

PUT

If you're updating an element of a collection

  • 200/204 with the same reasons as DELETE above.
  • 202 if the operation has not been commited yet.

The referenced element doesn't exists:

  • PUT can be 201 (if you created the element because that is your behaviour)

  • 404 If you don't want to create elements via PUT.

  • 400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).

  • 401 Unauthorized

  • 403 Forbidden: Authentication failure or invalid Application ID.

  • 405 Not Allowed. Sure.

  • 409 Resource Conflict can be possible in complex systems, as in DELETE.

  • 422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values

  • And 501, 502 in case of errors.

Fixed position but relative to container

With pure CSS you can't manage to do it; at least I haven't. However you can do it with jQuery very simply. I'll explain my problem, and with a little change you can use it.

So for a start, I wanted my element to have a fixed top (from top of the window), and a left component to inherit from the parent element (because the parent element is centered). To set the left component, just put your element into the parent and set position:relative for the parent element.

Then you need to know how much from the top your element is when the a scroll bar is on top (y zero scrolled); there are two options again. First is that is static (some number) or you have to read it from the parent element.

In my case it's 150 pixels from top static. So when you see 150 it's how much is the element from the top when we haven't scrolled.

CSS

#parent-element{position:relative;}
#promo{position:absolute;}

jQuery

$(document).ready(function() { //This check window scroll bar location on start
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');

});
$(window).scroll(function () { //This is when the window is scrolling
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');
});

Getting first value from map in C++

As simple as:

your_map.begin()->first // key
your_map.begin()->second // value

when exactly are we supposed to use "public static final String"?

Why do people use constants in classes instead of a variable?

readability and maintainability,

having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.

Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.

But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.

For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.

OnClick vs OnClientClick for an asp:CheckBox?

For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged

Which tool to build a simple web front-end to my database

I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.

How do I find out which DOM element has the focus?

I liked the approach used by Joel S, but I also love the simplicity of document.activeElement. I used jQuery and combined the two. Older browsers that don't support document.activeElement will use jQuery.data() to store the value of 'hasFocus'. Newer browsers will use document.activeElement. I assume that document.activeElement will have better performance.

(function($) {
var settings;
$.fn.focusTracker = function(options) {
    settings = $.extend({}, $.focusTracker.defaults, options);

    if (!document.activeElement) {
        this.each(function() {
            var $this = $(this).data('hasFocus', false);

            $this.focus(function(event) {
                $this.data('hasFocus', true);
            });
            $this.blur(function(event) {
                $this.data('hasFocus', false);
            });
        });
    }
    return this;
};

$.fn.hasFocus = function() {
    if (this.length === 0) { return false; }
    if (document.activeElement) {
        return this.get(0) === document.activeElement;
    }
    return this.data('hasFocus');
};

$.focusTracker = {
    defaults: {
        context: 'body'
    },
    focusedElement: function(context) {
        var focused;
        if (!context) { context = settings.context; }
        if (document.activeElement) {
            if ($(document.activeElement).closest(context).length > 0) {
                focused = document.activeElement;
            }
        } else {
            $(':visible:enabled', context).each(function() {
                if ($(this).data('hasFocus')) {
                    focused = this;
                    return false;
                }
            });
        }
        return $(focused);
    }
};
})(jQuery);

Clear and reset form input fields

You can also do it by targeting the current input, with anything.target.reset() . This is the most easiest way!

handleSubmit(e){
 e.preventDefault();
 e.target.reset();
}

<form onSubmit={this.handleSubmit}>
  ...
</form>

Clear History and Reload Page on Login/Logout Using Ionic Framework

Welcome to the framework! Actually the routing in Ionic is powered by ui-router. You should probably check out this previous SO question to find a couple of different ways to accomplish this.

If you just want to reload the state you can use:

$state.go($state.current, {}, {reload: true});

If you actually want to reload the page (as in, you want to re-bootstrap everything) then you can use:

$window.location.reload(true)

Good luck!

Generating an MD5 checksum of a file

I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:

I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit or /usr/bin/time result from each of several methods of checksumming a file of approx. 11MB:

$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f  /tmp/test.data.300k

real    0m0.043s
user    0m0.032s
sys     0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400

So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum function (md5sum_read in the above listing) is pretty similar to Omnifarious's:

import hashlib
def md5sum(filename, blocksize=65536):
    hash = hashlib.md5()
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            hash.update(block)
    return hash.hexdigest()

Granted, these are from single runs (the mmap ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize) after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum on the command line is not necessarily faster than a Python implementation...

EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32() call:

import zlib
def adler32sum(filename, blocksize=65536):
    checksum = zlib.adler32("")
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            checksum = zlib.adler32(block, checksum)
    return checksum & 0xffffffff

Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for "", which is 1 -- CRC can start with 0 instead. The AND-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Using jQuery Fancybox or Lightbox to display a contact form

Have a look at: Greybox

It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.

You will find many information on how to use Greybox and also some great examples. Cheers Kara

Are there best practices for (Java) package organization?

Short answer: One package per module/feature, possibly with sub-packages. Put closely related things together in the same package. Avoid circular dependencies between packages.

Long answer: I agree with most of this article

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Well what you can do is just open mysql.cfg file and you have to change Bind-address to this

bind-address = 127.0.0.1

and then Restart mysql and you will able to connect that server to this.

Look this you can have idea form that.

this is real sol

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

When should we use intern method of String on String literals

On a recent project, some huge data structures were set up with data that was read in from a database (and hence not String constants/literals) but with a huge amount of duplication. It was a banking application, and things like the names of a modest set (maybe 100 or 200) corporations appeared all over the place. The data structures were already large, and if all those corp names had been unique objects they would have overflowed memory. Instead, all the data structures had references to the same 100 or 200 String objects, thus saving lots of space.

Another small advantage of interned Strings is that == can be used (successfully!) to compare Strings if all involved strings are guaranteed to be interned. Apart from the leaner syntax, this is also a performance enhancement. But as others have pointed out, doing this harbors a great risk of introducing programming errors, so this should be done only as a desparate measure of last resort.

The downside is that interning a String takes more time than simply throwing it on the heap, and that the space for interned Strings may be limited, depending on the Java implementation. It's best done when you're dealing with a known reasonable number of Strings with many duplications.

How can I view live MySQL queries?

Run this convenient SQL query to see running MySQL queries. It can be run from any environment you like, whenever you like, without any code changes or overheads. It may require some MySQL permissions configuration, but for me it just runs without any special setup.

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep';

The only catch is that you often miss queries which execute very quickly, so it is most useful for longer-running queries or when the MySQL server has queries which are backing up - in my experience this is exactly the time when I want to view "live" queries.

You can also add conditions to make it more specific just any SQL query.

e.g. Shows all queries running for 5 seconds or more:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME >= 5;

e.g. Show all running UPDATEs:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND INFO LIKE '%UPDATE %';

For full details see: http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html

How do I print bytes as hexadecimal?

This is a modified version of the Nibble to Hex method

void hexArrayToStr(unsigned char* info, unsigned int infoLength, char **buffer) {
    const char* pszNibbleToHex = {"0123456789ABCDEF"};
    int nNibble, i;
    if (infoLength > 0) {
        if (info != NULL) {
            *buffer = (char *) malloc((infoLength * 2) + 1);
            buffer[0][(infoLength * 2)] = 0;
            for (i = 0; i < infoLength; i++) {
                nNibble = info[i] >> 4;
                buffer[0][2 * i] = pszNibbleToHex[nNibble];
                nNibble = info[i] & 0x0F;
                buffer[0][2 * i + 1] = pszNibbleToHex[nNibble];
            }
        } else {
            *buffer = NULL;
        }
    } else {
        *buffer = NULL;
    }
}

How to split csv whose columns may contain ,

You could split on all commas that do have an even number of quotes following them.

You would also like to view at the specf for CSV format about handling comma's.

Useful Link : C# Regex Split - commas outside quotes

Which versions of SSL/TLS does System.Net.WebRequest support?

This is an important question. The SSL 3 protocol (1996) is irreparably broken by the Poodle attack published 2014. The IETF have published "SSLv3 MUST NOT be used". Web browsers are ditching it. Mozilla Firefox and Google Chrome have already done so.

Two excellent tools for checking protocol support in browsers are SSL Lab's client test and https://www.howsmyssl.com/ . The latter does not require Javascript, so you can try it from .NET's HttpClient:

// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");

File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);

// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");

The result is damning:

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

That's concerning. It's comparable to 2006's Internet Explorer 7.

To list exactly which protocols a HTTP client supports, you can try the version-specific test servers below:

var test_servers = new Dictionary<string, string>();
test_servers["SSL 2"] = "https://www.ssllabs.com:10200";
test_servers["SSL 3"] = "https://www.ssllabs.com:10300";
test_servers["TLS 1.0"] = "https://www.ssllabs.com:10301";
test_servers["TLS 1.1"] = "https://www.ssllabs.com:10302";
test_servers["TLS 1.2"] = "https://www.ssllabs.com:10303";

var supported = new Func<string, bool>(url =>
{
    try { return new HttpClient().GetAsync(url).Result.IsSuccessStatusCode; }
    catch { return false; }
});

var supported_protocols = test_servers.Where(server => supported(server.Value));
Console.WriteLine(string.Join(", ", supported_protocols.Select(x => x.Key)));

I'm using .NET Framework 4.6.2. I found HttpClient supports only SSL 3 and TLS 1.0. That's concerning. This is comparable to 2006's Internet Explorer 7.


Update: It turns HttpClient does support TLS 1.1 and 1.2, but you have to turn them on manually at System.Net.ServicePointManager.SecurityProtocol. See https://stackoverflow.com/a/26392698/284795

I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?

Google Maps v2 - set both my location and zoom in

1.Add xml code in your layout for displaying maps.

2.Enable google maps api then get api key place that below.

<fragment
                   android:id="@+id/map"
               android:name="com.google.android.gms.maps.MapFragment"
                    android:layout_width="match_parent"
                    android:value="ADD-API-KEY"
                    android:layout_height="250dp"
                    tools:layout="@layout/newmaplayout" />
        <ImageView
            android:id="@+id/transparent_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@color/transparent" />

3.Add this code in oncreate.

 MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(UpadateProfile.this);

4.Add this code after oncreate. then access current location with marker placed in that

@Override
public void onMapReady(GoogleMap rmap) {
    DO WHATEVER YOU WANT WITH GOOGLEMAP
    map = rmap;
    setUpMap();
}
public void setUpMap() {
    map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
  map.setMyLocationEnabled(true);
    map.setTrafficEnabled(true);
    map.setIndoorEnabled(true);
    map.getCameraPosition();
    map.setBuildingsEnabled(true);
    map.getUiSettings().setZoomControlsEnabled(true);
    markerOptions = new MarkerOptions();
    markerOptions.title("Outlet Location");
    map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
            map.clear();
            markerOptions.position(point);
            map.animateCamera(CameraUpdateFactory.newLatLng(point));
            map.addMarker(markerOptions);
            String all_vals = String.valueOf(point);
            String[] separated = all_vals.split(":");
            String latlng[] = separated[1].split(",");
            MyLat = Double.parseDouble(latlng[0].trim().substring(1));
            MyLong = Double.parseDouble(latlng[1].substring(0,latlng[1].length()-1));
            markerOptions.title("Outlet Location");
            getLocation(MyLat,MyLong);
        }
    });
}
public void getLocation(double lat, double lng) {
    Geocoder geocoder = new Geocoder(UpadateProfile.this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
   } catch (IOException e) {
         TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
    }
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

You can specify the latest version of ruby by looking at https://www.ruby-lang.org/en/downloads/

  1. Fetch the latest version:

    curl -sSL https://get.rvm.io | bash -s stable --ruby

  2. Install it:

    rvm install 2.2

  3. Use it as default:

    rvm use 2.2 --default

Or run the latest command from ruby:

rvm install ruby --latest
rvm use 2.2 --default

Command to close an application of console?

So you didn't say you wanted the application to quit or exit abruptly, so as another option, perhaps just have the response loop end out elegantly. (I am assuming you have a while loop waiting for user instructions. This is some code from a project I just wrote today.

        Console.WriteLine("College File Processor");
        Console.WriteLine("*************************************");
        Console.WriteLine("(H)elp");
        Console.WriteLine("Process (W)orkouts");
        Console.WriteLine("Process (I)nterviews");
        Console.WriteLine("Process (P)ro Days");
        Console.WriteLine("(S)tart Processing");
        Console.WriteLine("E(x)it");
        Console.WriteLine("*************************************");

        string response = "";
        string videotype = "";
        bool starting = false;
        bool exiting = false;

        response = Console.ReadLine();

        while ( response != "" )
        {
            switch ( response  )
            {
                case "H":
                case "h":
                    DisplayHelp();
                    break;

                case "W":
                case "w":
                    Console.WriteLine("Video Type set to Workout");
                    videotype = "W";
                    break;

                case "I":
                case "i":
                    Console.WriteLine("Video Type set to Interview");
                    videotype = "I";
                    break;

                case "P":
                case "p":
                    Console.WriteLine("Video Type set to Pro Day");
                    videotype = "P";
                    break;

                case "S":
                case "s":
                    if ( videotype == "" )
                    {
                        Console.WriteLine("Please Select Video Type Before Starting");
                    }
                    else
                    {
                        Console.WriteLine("Starting...");
                        starting = true;
                    }
                    break;

                case "E":
                case "e":
                    Console.WriteLine("Good Bye!");
                    System.Threading.Thread.Sleep(100);
                    exiting = true;
                    break;
            }

            if ( starting || exiting)
            {
                break;
            }
            else
            {
                response = Console.ReadLine();
            }
        }

        if ( starting )
        {
            ProcessFiles();
        }

Can I call methods in constructor in Java?

The constructor is called only once, so you can safely do what you want, however the disadvantage of calling methods from within the constructor, rather than directly, is that you don't get direct feedback if the method fails. This gets more difficult the more methods you call.

One solution is to provide methods that you can call to query the 'health' of the object once it's been constructed. For example the method isConfigOK() can be used to see if the config read operation was OK.

Another solution is to throw exceptions in the constructor upon failure, but it really depends on how 'fatal' these failures are.

class A
{
    Map <String,String> config = null;
    public A()
    {
        readConfig();
    }

    protected boolean readConfig()
    {
        ...
    }

    public boolean isConfigOK()
    {
        // Check config here
        return true;
    }
};

How to access the last value in a vector?

If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck. The standard idiom is

x[length(x)]  

but it's easy enough to write a function to do this:

last <- function(x) { return( x[length(x)] ) }

This missing feature in R annoys me too!

How do I create executable Java program?

You could use GCJ to compile your Java program into native code.
At some time they even compiled Eclipse into a native version.

Angular update object in object array

You can try this also to replace existing object

toDoTaskList = [
                {id:'abcd', name:'test'},
                {id:'abcdc', name:'test'},
                {id:'abcdtr', name:'test'}
              ];

newRecordToUpdate = {id:'abcdc', name:'xyz'};
this.toDoTaskList.map((todo, i) => {
         if (todo.id == newRecordToUpdate .id){
            this.toDoTaskList[i] = updatedVal;
          }
        });

How do I get SUM function in MySQL to return '0' if no values are found?

if sum of column is 0 then display empty

select if(sum(column)>0,sum(column),'')
from table 

Enable the display of line numbers in Visual Studio

Visual studio 2015 enterprice

Tools -> Options -> Text Editor -> All Languages -> check Line Numbers

https://msdn.microsoft.com/en-us/library/ms165340.aspxenter image description here

Displaying the Error Messages in Laravel after being Redirected from controller

Laravel 4

When the validation fails return back with the validation errors.

if($validator->fails()) {
    return Redirect::back()->withErrors($validator);
}

You can catch the error on your view using

@if($errors->any())
    {{ implode('', $errors->all('<div>:message</div>')) }}
@endif

UPDATE

To display error under each field you can do like this.

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

For better display style with css.

You can refer to the docs here.

UPDATE 2

To display all errors at once

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif

To display error under each field.

@error('firstname')
    <div class="error">{{ $message }}</div>
@enderror

Postgres manually alter sequence

this worked for me:

SELECT pg_catalog.setval('public.hibernate_sequence', 3, true);

Identify if a string is a number

Pull in a reference to Visual Basic in your project and use its Information.IsNumeric method such as shown below and be able to capture floats as well as integers unlike the answer above which only catches ints.

    // Using Microsoft.VisualBasic;

    var txt = "ABCDEFG";

    if (Information.IsNumeric(txt))
        Console.WriteLine ("Numeric");

IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false

what is Array.any? for javascript

The JavaScript native .some() method does exactly what you're looking for:

function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

How do I undo 'git add' before commit?

git remove or git rm can be used for this, with the --cached flag. Try:

git help rm

Java count occurrence of each item in an array

With , you can do it like this:

String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k+" "+v.size()));

Output:

name5 1
name4 1
name3 1
name2 2
name1 1

What it does is:

  • Create a Stream<String> from the original array
  • Group each element by identity, resulting in a Map<String, List<String>>
  • For each key value pair, print the key and the size of the list

If you want to get a Map that contains the number of occurences for each word, it can be done doing:

Map<String, Long> map = Arrays.stream(array)
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

For more informations:

Hope it helps! :)

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

how to pass parameter from @Url.Action to controller function

should you pass it in this way :

public ActionResult CreatePerson(int id) //controller 
window.location.href = "@Url.Action("CreatePerson", "Person",new { @id = 1});

What is the best way to test for an empty string with jquery-out-of-the-box?

if(!my_string){ 
// stuff 
}

and

if(my_string !== "")

if you want to accept null but reject empty

EDIT: woops, forgot your condition is if it IS empty

JavaScript alert not working in Android WebView

if you wish to hide URL from the user, Show an AlertDialog as below.

myWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        mContext);
                builder.setMessage(message)
                        .setNeutralButton("OK", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.dismiss();
                            }
                        }).show();
                result.cancel();
                return true;
            }
    }

Dart/Flutter : Converting timestamp

meh, just use https://github.com/andresaraujo/timeago.dart library; it does all the heavy-lifting for you.

EDIT:

From your question, it seems you wanted relative time conversions, and the timeago library enables you to do this in 1 line of code. Converting Dates isn't something I'd choose to implement myself, as there are a lot of edge cases & it gets fugly quickly, especially if you need to support different locales in the future. More code you write = more you have to test.

import 'package:timeago/timeago.dart' as timeago;

final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));

// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());

// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());

print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes

to convert epochMS to DateTime, just use...

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);

Android Studio was unable to find a valid Jvm (Related to MAC OS)

Open the application package for Android Studio in finder, and edit the Info.plist file. Change the key JVMversion. Put 1.6+ instead of 1.6*. That worked for me!.

Cheers!

Edited:

While this was necessary in older versions of Android Studio, this is no longer recommended. See the official statement

"Please note: Do not edit Info.plist to pick a different version. That will break not only the application signature, but also future patch updates to your installation."

Antonio Jose's answer is the correct one.

Thanks aried3r!

Laravel: Validation unique on update

Just a side note, most answers to this question talk about email_address while in Laravel's inbuilt auth system, the email field name is just email. Here is an example how you can validate a unique field, i.e. an email on the update:

In a Form Request, you do like this:

public function rules()
{
  return [
      'email' => 'required|email|unique:users,email,'.$this->user->id,
  ];
}

Or if you are validating your data in a controller directly:

public function update(Request $request, User $user)
{
  $request->validate([
      'email' => 'required|email|unique:users,email,'.$user->id,
  ]);
}

Update: If you are updating the signed in user and aren't injecting the User model into your route, you may encounter undefined property when accessing id on $this->user. In that case, use:

public function rules()
    {
      return [
          'email' => 'required|email|unique:users,email,'.$this->user()->id,
      ];
    }

A more elegant way since Laravel 5.7 is:

public function rules()
{
    return [
        'email' => ['required', 'email', \Illuminate\Validation\Rule::unique('users')->ignore($this->user()->id)]
    ];
}

P.S: I have added some other rules, i.e. required and email, in order to make this example clear for newbies.

Most popular screen sizes/resolutions on Android phones

A blog article from Localytics, Android Not As Fragmented as Many Think, lists most popular Android sizes and resolutions:

Another concern for Android developers is screen size and resolution. Of all app usage analyzed for this study, 41% of all sessions came from Android devices with 4.3 inch screens, by far the most popular size. 4 inch screens accounted for 22% of sessions, 3.2 inch screens for 11%, and 3.7 inch screens contributed 9%.

Resolutions were even less fragmented, however, with the most widely-seen screen resolution – 800 x 480 pixels – contributing 62% of the study’s sessions. The next most popular screen resolutions were 480 x 320 (14%), 960 x 540 (6%), 480 x 854 (5%) and 320 x 240 (5%).

Please note these statistics are from February 2012, which might be outdated today. Also, please always keep in mind that your app might be used under the inch sizes and resolutions not listed in this article.

EDIT: You should also be aware that there are Android "tablets" with large resolutions. The following quote is from the same article I mentioned:

Screen resolution and size are actually even less fragmented than handsets – 74% of Android tablet usage takes place on 7 inch devices with 1024 x 600 resolution. 22% are 10.1 inch devices with 1280 x 800 resolutions, so by taking into account two screen size/resolution combinations, developers should be able to easily reach nearly all of the Android tablet market.

Use Expect in a Bash script to provide a password to an SSH command

Add the 'interact' Expect command just before your EOD:

#!/bin/bash

read -s PWD

/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com
expect "password"
send "$PWD\n"
interact
EOD
echo "you're out"

This should let you interact with the remote machine until you log out. Then you'll be back in Bash.

How to undo a git merge with conflicts

Sourcetree

If you not commit your merge, then just double click on another branch (=checkout) and when sourcetree ask you about discarding all changes then agree

How can I prevent the backspace key from navigating back?

This solution is similar to others that have been posted, but it uses a simple whitelist making it easily customizable to allow the backspace in specified elements just by setting the selector in the .is() function.

I use it in this form to prevent the backspace on pages from navigating back:

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input:not([readonly]), textarea")) {
        e.preventDefault();
    }
});

How to implement a ConfigurationSection with a ConfigurationElementCollection

If you are looking for a custom configuration section like following

<CustomApplicationConfig>
        <Credentials Username="itsme" Password="mypassword"/>
        <PrimaryAgent Address="10.5.64.26" Port="3560"/>
        <SecondaryAgent Address="10.5.64.7" Port="3570"/>
        <Site Id="123" />
        <Lanes>
          <Lane Id="1" PointId="north" Direction="Entry"/>
          <Lane Id="2" PointId="south" Direction="Exit"/>
        </Lanes> 
</CustomApplicationConfig>

then you can use my implementation of configuration section so to get started add System.Configuration assembly reference to your project

Look at the each nested elements I used, First one is Credentials with two attributes so lets add it first

Credentials Element

public class CredentialsConfigElement : System.Configuration.ConfigurationElement
    {
        [ConfigurationProperty("Username")]
        public string Username
        {
            get 
            {
                return base["Username"] as string;
            }
        }

        [ConfigurationProperty("Password")]
        public string Password
        {
            get
            {
                return base["Password"] as string;
            }
        }
    }

PrimaryAgent and SecondaryAgent

Both has the same attributes and seem like a Address to a set of servers for a primary and a failover, so you just need to create one element class for both of those like following

public class ServerInfoConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Address")]
        public string Address
        {
            get
            {
                return base["Address"] as string;
            }
        }

        [ConfigurationProperty("Port")]
        public int? Port
        {
            get
            {
                return base["Port"] as int?;
            }
        }
    }

I'll explain how to use two different element with one class later in this post, let us skip the SiteId as there is no difference in it. You just have to create one class same as above with one property only. let us see how to implement Lanes collection

it is splitted in two parts first you have to create an element implementation class then you have to create collection element class

LaneConfigElement

public class LaneConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("Id")]
        public string Id
        {
            get
            {
                return base["Id"] as string;
            }
        }

        [ConfigurationProperty("PointId")]
        public string PointId
        {
            get
            {
                return base["PointId"] as string;
            }
        }

        [ConfigurationProperty("Direction")]
        public Direction? Direction
        {
            get
            {
                return base["Direction"] as Direction?;
            }
        }
    }

    public enum Direction
    { 
        Entry,
        Exit
    }

you can notice that one attribute of LanElement is an Enumeration and if you try to use any other value in configuration which is not defined in Enumeration application will throw an System.Configuration.ConfigurationErrorsException on startup. Ok lets move on to Collection Definition

[ConfigurationCollection(typeof(LaneConfigElement), AddItemName = "Lane", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class LaneConfigCollection : ConfigurationElementCollection
    {
        public LaneConfigElement this[int index]
        {
            get { return (LaneConfigElement)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public void Add(LaneConfigElement serviceConfig)
        {
            BaseAdd(serviceConfig);
        }

        public void Clear()
        {
            BaseClear();
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new LaneConfigElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((LaneConfigElement)element).Id;
        }

        public void Remove(LaneConfigElement serviceConfig)
        {
            BaseRemove(serviceConfig.Id);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(String name)
        {
            BaseRemove(name);
        }

    }

you can notice that I have set the AddItemName = "Lane" you can choose whatever you like for your collection entry item, i prefer to use "add" the default one but i changed it just for the sake of this post.

Now all of our nested Elements have been implemented now we should aggregate all of those in a class which has to implement System.Configuration.ConfigurationSection

CustomApplicationConfigSection

public class CustomApplicationConfigSection : System.Configuration.ConfigurationSection
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(CustomApplicationConfigSection));
        public const string SECTION_NAME = "CustomApplicationConfig";

        [ConfigurationProperty("Credentials")]
        public CredentialsConfigElement Credentials
        {
            get
            {
                return base["Credentials"] as CredentialsConfigElement;
            }
        }

        [ConfigurationProperty("PrimaryAgent")]
        public ServerInfoConfigElement PrimaryAgent
        {
            get
            {
                return base["PrimaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("SecondaryAgent")]
        public ServerInfoConfigElement SecondaryAgent
        {
            get
            {
                return base["SecondaryAgent"] as ServerInfoConfigElement;
            }
        }

        [ConfigurationProperty("Site")]
        public SiteConfigElement Site
        {
            get
            {
                return base["Site"] as SiteConfigElement;
            }
        }

        [ConfigurationProperty("Lanes")]
        public LaneConfigCollection Lanes
        {
            get { return base["Lanes"] as LaneConfigCollection; }
        }
    }

Now you can see that we have two properties with name PrimaryAgent and SecondaryAgent both have the same type now you can easily understand why we had only one implementation class against these two element.

Before you can use this newly invented configuration section in your app.config (or web.config) you just need to tell you application that you have invented your own configuration section and give it some respect, to do so you have to add following lines in app.config (may be right after start of root tag).

<configSections>
    <section name="CustomApplicationConfig" type="MyNameSpace.CustomApplicationConfigSection, MyAssemblyName" />
  </configSections>

NOTE: MyAssemblyName should be without .dll e.g. if you assembly file name is myDll.dll then use myDll instead of myDll.dll

to retrieve this configuration use following line of code any where in your application

CustomApplicationConfigSection config = System.Configuration.ConfigurationManager.GetSection(CustomApplicationConfigSection.SECTION_NAME) as CustomApplicationConfigSection;

I hope above post would help you to get started with a bit complicated kind of custom config sections.

Happy Coding :)

****Edit**** To Enable LINQ on LaneConfigCollection you have to implement IEnumerable<LaneConfigElement>

And Add following implementation of GetEnumerator

public new IEnumerator<LaneConfigElement> GetEnumerator()
        {
            int count = base.Count;
            for (int i = 0; i < count; i++)
            {
                yield return base.BaseGet(i) as LaneConfigElement;
            }
        }

for the people who are still confused about how yield really works read this nice article

Two key points taken from above article are

it doesn’t really end the method’s execution. yield return pauses the method execution and the next time you call it (for the next enumeration value), the method will continue to execute from the last yield return call. It sounds a bit confusing I think… (Shay Friedman)

Yield is not a feature of the .Net runtime. It is just a C# language feature which gets compiled into simple IL code by the C# compiler. (Lars Corneliussen)

Pattern matching using a wildcard

You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)

error: ORA-65096: invalid common user or role name in oracle

SQL> alter session set "_ORACLE_SCRIPT"=true;  
SQL> create user sec_admin identified by "Chutinhbk123@!";

What are FTL files

Have a look here.

Following files have FTL extension:

  • Family Tree Legends Family File
  • FreeMarker Template
  • Future Tense Texture

Converting BitmapImage to Bitmap and vice versa

There is no need to use foreign libraries.

Convert a BitmapImage to Bitmap:

private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
    // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));

    using(MemoryStream outStream = new MemoryStream())
    {
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(bitmapImage));
        enc.Save(outStream);
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);

        return new Bitmap(bitmap);
    }
}

To convert the Bitmap back to a BitmapImage:

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
    IntPtr hBitmap = bitmap.GetHbitmap();
    BitmapImage retval;

    try
    {
        retval = (BitmapImage)Imaging.CreateBitmapSourceFromHBitmap(
                     hBitmap,
                     IntPtr.Zero,
                     Int32Rect.Empty,
                     BitmapSizeOptions.FromEmptyOptions());
    }
    finally
    {
        DeleteObject(hBitmap);
    }

    return retval;
}

Standard deviation of a list

pure python code:

from math import sqrt

def stddev(lst):
    mean = float(sum(lst)) / len(lst)
    return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, lst))) / len(lst))

What is special about /dev/tty?

The 'c' means it's a character special file.

Min / Max Validator in Angular 2 Final

I found a library implementing a lot of custom validators - ng2-validation - that can be used with template-driven forms (attribute directives). Example:

<input type="number" [(ngModel)]="someNumber" name="someNumber" #field="ngModel" [range]="[10, 20]"/>
<p *ngIf="someNumber.errors?.range">Must be in range</p>

RuntimeError: module compiled against API version a but this version of numpy is 9

I ran into the same issue tonight. It turned out to be a problem where I had multiple numpy packages installed. An older version was installed in /usr/lib/python2.7 and the correct version was installed in /usr/local/lib/python2.7.

Additionally, I had PYTHONPATH=/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages. PYTHONPATH was finding the older version of numpy before the correct version, so when inside the Python interpreter, it would import the older version of numpy.

One thing which helped was opening a python session an executing the following code:

import numpy as np 
print np.__version__ 
print np.__path__

That should tell you exactly which version Python is using, and where it's installed.

To fix the issue, I changed PYTHONPATH=/usr/local/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages. And I also setup a virtual Python environment using the Hitchiker's Guide to Python, specifically the section titled "Lower level: virtualenv" . I know I should have setup a virtual environment in the first place, but I was tired and being lazy. Oh well, lesson learned!

(Update)

Just in case the docs are moved again, here are the relevant bits on...

Creating a Python Virtual Environment

Install virtualenv via pip:

$ install virtualenv

Test the installation:

$ virtualenv --version

Optionally, et the environment variable VIRTUALENVWRAPPER_PYTHON to change the default version of python used by virtual environments, for example to use Python 3:

$ export VIRTUALENVWRAPPER_PYTHON=$(which python3)

Optionally, set the environment variable WORKON_HOME to change the default directory your Python virtual environments are created in, for example to use /opt/python_envs:

$ export WORKON_HOME=/opt/python_envs

Create a virtual environment for a project:

$ cd my_project_folder
$ virtualenv my_virtual_env_name

Activate the virtual environment, you just created. Assuming you also set WORKON_HOME=/opt/python_envs:

$ source $WORKON_HOME/my_virtual_env_name/bin/activate

Install whatever Python packages your project requires, using either of the following two methods.

Method 1 - Install using pip from command line:

$ pip install python_package_name1
$ pip install python_package_name2

Method 2 - Install using a requests.txt file:

$ echo "python_package_name1" >> requests.txt
$ echo "python_package_name2" >> requests.txt
$ pip install -r ./requests.txt

Optionally, but highly recommended, install virtualenvwrapper. It contains useful commands to make working with virtual Python environments easier:

$ pip install virtualenvwrapper
$ source /usr/local/bin/virtualenvwrapper.sh

On Windows, install virtualenvwrapper using:

$ pip install virtualenvwrapper-win

Basic usage of virtualenvwrapper Create a new virtual environment:

$ mkvirtualenv my_virtual_env_name

List all virtual environments:

$ lsvirtualenv

Activate a virtual environment:

$ workon my_virtual_env_name

Delete a virtual environment (caution! this is irreversible!):

$ rmvirtualenv my_virtual_env_name

I hope this help!

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Though I am new to hibernate but with little research (trial and error we can say) I found out that it is due to inconsistency in annotating the methods/fileds.

when you are annotating @ID on variable make sure all other annotations are also done on variable only and when you are annotating it on getter method same make sure you are annotating all other getter methods only and not their respective variables.

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

How to center an element in the middle of the browser window?

This is checked and works in all browsers.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <style type="text/css">
            html, body { margin: 0; padding: 0; height: 100%; }

            #outer {height: 100%; overflow: hidden; position: relative; width: 100%;}
            #outer[id] {display: table; position: static;}

            #middle {position: absolute; top: 50%; width: 100%; text-align: center;}
            #middle[id] {display: table-cell; vertical-align: middle; position: static;}

            #inner {position: relative; top: -50%; text-align: left;}
            #inner {margin-left: auto; margin-right: auto;}
            #inner {width: 300px; } /* this width should be the width of the box you want centered */
        </style>
    </head>
    <body>

        <div id="outer">
            <div id="middle">
                <div id="inner">
                    centered
                </div>
            </div>
        </div>

    </body>
</html>

What is the difference between print and puts?

puts adds a new line to the end of each argument if there is not one already.

print does not add a new line.


For example:

puts [[1,2,3], [4,5,nil]] Would return:

1
2
3
4
5

Whereas print [[1,2,3], [4,5,nil]] would return:

[[1,2,3], [4,5,nil]]
Notice how puts does not output the nil value whereas print does.

Python set to list

You've shadowed the builtin set by accidentally using it as a variable name, here is a simple way to replicate your error

>>> set=set()
>>> set=set()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

The first line rebinds set to an instance of set. The second line is trying to call the instance which of course fails.

Here is a less confusing version using different names for each variable. Using a fresh interpreter

>>> a=set()
>>> b=a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

Hopefully it is obvious that calling a is an error

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Why do we have to override the equals() method in Java?

.equals() doesn't perform an intelligent comparison for most classes unless the class overrides it. If it's not defined for a (user) class, it behaves the same as ==.

Reference: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html http://www.leepoint.net/data/expressions/22compareobjects.html

Set folder browser dialog start location

Set the SelectedPath property before you call ShowDialog ...

folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();

Will start them at C:\Temp

JavaScript blob filename without link

I just wanted to expand on the accepted answer with support for Internet Explorer (most modern versions, anyways), and to tidy up the code using jQuery:

$(document).ready(function() {
    saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});

function saveFile (name, type, data) {
    if (data !== null && navigator.msSaveBlob)
        return navigator.msSaveBlob(new Blob([data], { type: type }), name);
    var a = $("<a style='display: none;'/>");
    var url = window.URL.createObjectURL(new Blob([data], {type: type}));
    a.attr("href", url);
    a.attr("download", name);
    $("body").append(a);
    a[0].click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

Here is an example Fiddle. Godspeed.

Jquery select this + class

Use find()

$(this).find(".subclass").css("visibility","visible");

I don't understand -Wl,-rpath -Wl,

The -Wl,xxx option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So

gcc -Wl,aaa,bbb,ccc

eventually becomes a linker call

ld aaa bbb ccc

In your case, you want to say "ld -rpath .", so you pass this to gcc as -Wl,-rpath,. Alternatively, you can specify repeat instances of -Wl:

gcc -Wl,aaa -Wl,bbb -Wl,ccc

Note that there is no comma between aaa and the second -Wl.

Or, in your case, -Wl,-rpath -Wl,..

How to see full query from SHOW PROCESSLIST

I just read in the MySQL documentation that SHOW FULL PROCESSLIST by default only lists the threads from your current user connection.

Quote from the MySQL SHOW FULL PROCESSLIST documentation:

If you have the PROCESS privilege, you can see all threads.

So you can enable the Process_priv column in your mysql.user table. Remember to execute FLUSH PRIVILEGES afterwards :)

Android Webview - Completely Clear the Cache

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db")

Did the trick

ab load testing

Steps to set up Apache Bench(AB) on windows (IMO - Recommended).

Step 1 - Install Xampp.
Step 2 - Open CMD.
Step 3 - Go to the apache bench destination (cd C:\xampp\apache\bin) from CMD
Step 4 - Paste the command (ab -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://localhost:yourport/)
Step 5 - Wait for it. Your done

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

Truncate (not round) decimal places in SQL Server

Try like this:

SELECT cast(round(123.456,2,1) as decimal(18,2)) 

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:

Change your <html> tag to include a manifest attribute:

<html manifest="http://www.example.com/example.mf">

A manifest file must be served with the mime-type text/cache-manifest.

A simple manifest looks something like this:

CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js

Once an application is offline it remains cached until one of the following happens:

  1. The user clears their browser's data storage for your site.
  2. The manifest file is modified. Note: updating a file listed in the manifest doesn't mean the browser will re-cache that resource. The manifest file itself must be altered.

create multiple tag docker image

Since 1.10 release, you can now add multiple tags at once on build:

docker build -t name1:tag1 -t name1:tag2 -t name2 .

Source: Add ability to add multiple tags with docker build

how to always round up to the next integer

Xform to double (and back) for a simple ceil?

list.Count()/10 + (list.Count()%10 >0?1:0) - this bad, div + mod

edit 1st: on a 2n thought that's probably faster (depends on the optimization): div * mul (mul is faster than div and mod)

int c=list.Count()/10;
if (c*10<list.Count()) c++;

edit2 scarpe all. forgot the most natural (adding 9 ensures rounding up for integers)

(list.Count()+9)/10

PHP form send email to multiple recipients

Use comma separated values as below.

$email_to = 'Mary <[email protected]>, Kelly <[email protected]>';
@mail($email_to, $email_subject, $email_message, $headers);

or run a foreach for email address

//list of emails in array format and each one will see their own to email address
$arrEmail = array('Mary <[email protected]>', 'Kelly <[email protected]>');

foreach($arrEmail as $key => $email_to)
    @mail($email_to, $email_subject, $email_message, $headers);

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

Just state format at @font-face as following:

_x000D_
_x000D_
@font-face {_x000D_
  font-family: 'Some Family';_x000D_
  src: url('/fonts/fontname.ttf') format('ttf'); /* and this for every font */_x000D_
}
_x000D_
_x000D_
_x000D_

Find first element in a sequence that matches a predicate

I don't think there's anything wrong with either solutions you proposed in your question.

In my own code, I would implement it like this though:

(x for x in seq if predicate(x)).next()

The syntax with () creates a generator, which is more efficient than generating all the list at once with [].

Python 3 ImportError: No module named 'ConfigParser'

This worked for me

cp /usr/local/lib/python3.5/configparser.py /usr/local/lib/python3.5/ConfigParser.py

Difference between "as $key => $value" and "as $value" in PHP foreach

Let's say you have an associative array like this:

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => array('x'=>123)
);

In the first iteration : $key="one" and $value=1.

Sometimes you need this key ,if you want only the value , you can avoid using it.

In the last iteration : $key='seventeen' and $value = array('x'=>123) so to get value of the first element in this array value, you need a key, x in this case: $value['x'] =123.