Programs & Examples On #Serial port

A serial port is a physical interface through which data is transferred (uni- or bidirectionally) one bit at a time. The term usually refers to the RS-232 port with a 9-pin d-sub connector that was once the standard serial interface on a PC.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I think I found the answer in my kernel source documentation: /usr/src/linux-2.6.37-rc3/Documentation/filesystems/proc.txt

1.7 TTY info in /proc/tty
-------------------------

Information about  the  available  and actually used tty's can be found in the
directory /proc/tty.You'll  find  entries  for drivers and line disciplines in
this directory, as shown in Table 1-11.


Table 1-11: Files in /proc/tty
..............................................................................
 File          Content                                        
 drivers       list of drivers and their usage                
 ldiscs        registered line disciplines                    
 driver/serial usage statistic and status of single tty lines 
..............................................................................

To see  which  tty's  are  currently in use, you can simply look into the file
/proc/tty/drivers:

  > cat /proc/tty/drivers 
  pty_slave            /dev/pts      136   0-255 pty:slave 
  pty_master           /dev/ptm      128   0-255 pty:master 
  pty_slave            /dev/ttyp       3   0-255 pty:slave 
  pty_master           /dev/pty        2   0-255 pty:master 
  serial               /dev/cua        5   64-67 serial:callout 
  serial               /dev/ttyS       4   64-67 serial 
  /dev/tty0            /dev/tty0       4       0 system:vtmaster 
  /dev/ptmx            /dev/ptmx       5       2 system 
  /dev/console         /dev/console    5       1 system:console 
  /dev/tty             /dev/tty        5       0 system:/dev/tty 
  unknown              /dev/tty        4    1-63 console 

Here is a link to this file: http://git.kernel.org/?p=linux/kernel/git/next/linux-next.git;a=blob_plain;f=Documentation/filesystems/proc.txt;hb=e8883f8057c0f7c9950fa9f20568f37bfa62f34a

How can I set a custom baud rate on Linux?

You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).

So, you open the device using open() and get a file descriptor, then use it in tcgetattr() to fill your termios structure.

Then clear CBAUD and set CBAUDEX on c_cflag. CBAUDEX has the same value as BOTHER.

After setting this, you can set a custom baud rate using normal functions, like cfsetspeed(), specifying the desired baud rate as an integer.

Python: Making a beep noise

# playsound in cross plate form, just install it with pip
#  first install playsound > pip install playsound
from playsound import playsound
playsound('audio.mp3')

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

Long time reader, first time helper ;)

I'm going through the same hellish experience here with a Prolific USB <> Serial adapter and so far Linux is the easiest to get it to work.

On CentOS, I didn't need to install any drivers etc.. That said,

  • dmesg | grep -i tty or dmesg | grep -i usb showed me /dev/ttyUSB0.
  • screen ttyUSB0 9600 didn't do the trick for me like it did in OSX
  • minicom is new to me but it was complaining about lack of /dev/modem

However, this helped: https://www.centos.org/forums/viewtopic.php?t=21271

So install minicom (yum install minicom) then enter its settings (minicom -s).

Then select Serial Port Setup and change the Serial Device (Option A) to /dev/ttyUSB0, or whatever your device file is as it slightly differs per distro.

Then change the Bps (Option E) to 9600 and the rest should be default (8N1 Y N)

Save as default, then simply minicom and Bob's your uncle.

HTH.

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

Getting Serial Port Information

I tried so many solutions on here that didn't work for me, only displaying some of the ports. But the following displayed All of them and their information.

        using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
        {
            var portnames = SerialPort.GetPortNames();
            var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

            var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();

            foreach(string s in portList)
            {
                Console.WriteLine(s);
            }
        }
    }

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:

CloseHandle(serialHandle);

Python AttributeError: 'module' object has no attribute 'Serial'

I'm adding this solution for people who make the same mistake as I did.

In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.

Problem occurs when you import 'something' when your python file name is 'something.py'.

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

What is the difference between DTR/DSR and RTS/CTS flow control?

An important difference is that some UARTs (16550 notably) will stop receiving characters immediately if their host instructs them to set DSR to be inactive. In contrast, characters will still be received if CTS is inactive. I believe that the intention here is that DSR indicates that the device is no longer listening and so sending any further characters is pointless, while CTS indicates that a buffer is getting full; the latter allows for a certain amount of 'skid' where the flow control line changed state between the DTE sampling it and the next character being transmitted. In (relatively) later devices that support a hardware FIFO it's possible that a number of characters could be transmitted after the DCE has set CTS to be inactive.

How can I "reset" an Arduino board?

Based on my experience with the communication already in use or blocked, I would say that the program you are interfacing with still has the communication open.

I also found that if you disconnect the USB cable it will rest the communication. It is not the greatest solution, but it solves the problem.

Faking an RS232 Serial Port

There's always the hardware route. Purchase two USB to serial converters, and connect them via a NULL modem.

Pro tips: 1) Windows may assign new COM ports to the adapters after every device sleep or reboot. 2) The market leaders in chips for USB to serial are Prolific and FTDI. Both companies are battling knockoffs, and may be blocked in future official Windows drivers. The Linux drivers however work fine with the clones.

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


python to arduino serial read & write

First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,

C:\Python34\Scripts  

Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd will pop up. Write the below code in that cmd window,

pip install PySerial

and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.


after successfully installed the module open python IDLE and write down the bellow code and run it.

import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using        
ser = serial.Serial("COM11", 9600)
while True:
    cc=str(ser.readline())
    print(cc[2:][:-5])   

Python Serial: How to use the read or readline function to read more than 1 character at a time

I use this small method to read Arduino serial monitor with Python

import serial
ser = serial.Serial("COM11", 9600)
while True:
     cc=str(ser.readline())
     print(cc[2:][:-5])

Arduino COM port doesn't work

This fix / solution worked for me: Device Manager --> Ports --> right click on Arduino Uno --> Update Driver Software --> Search automatically for updated driver software

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

How to send data to COM PORT using JAVA?

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

How to find the serial port number on Mac OS X?

mac os x don't use com numbers. you have to use something like 'ser:devicename' , 9600

What's a good, free serial port monitor for reverse-engineering?

I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

First, if you need to talk to a bluetooth 2.x device, this documentation states that :

Hint: If you are connecting to a Bluetooth serial board then try using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However if you are connecting to an Android peer then please generate your own unique UUID.

I didn't think that it would work, but only by replacing the UUID with 00001101-0000-1000-8000-00805F9B34FB it works. However, this code seems to handle the problem of SDK version, and you can just replace the function device.createRfcommSocketToServiceRecord(mMyUuid); with tmp = createBluetoothSocket(mmDevice); after defining the following method :

private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
    throws IOException {
    if(Build.VERSION.SDK_INT >= 10){
        try {
            final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, mMyUuid);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
    }
    return  device.createRfcommSocketToServiceRecord(mMyUuid);
}

The source code isn't mine, but comes from this website.

What is the correct way to read a serial port using .NET framework?

    using System;
    using System.IO.Ports;
    using System.Threading;

    namespace SerialReadTest
    {
        class SerialRead
        {
            static void Main(string[] args)
            {
        Console.WriteLine("Serial read init");
        SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
        port.Open();
        while(true){
          Console.WriteLine(port.ReadLine());
        }

    }
}
}

How do I use dataReceived event of the SerialPort Port Object in C#?

By the way, you can use next code in you event handler:

switch(e.EventType)
{
  case SerialData.Chars:
  {
    // means you receives something
    break;
  }
  case SerialData.Eof:
  {
    // means receiving ended
    break;
  }
}

"The semaphore timeout period has expired" error for USB connection

Okay, I am now connecting without the semaphore timeout problem.

If anyone reading ever encounters the same thing, I hope that this procedure works for you; but no promises; hey, it's windows.

In my case this was Windows 7

I got a little hint from This page on eHow; not sure if that might help anyone or not.

So anyway, this was the simple twenty three step procedure that worked for me

  • Click on start button

  • Choose Control Panel

  • From Control Panel, choose Device Manger

  • From Device Manager, choose Universal Serial Bus Controllers

  • From Universal Serial Bus Controllers, click the little sideways triangle

  • I cannot predict what you'll see on your computer, but on mine I get a long drop-down list

  • Begin the investigation to figure out which one of these members of this list is the culprit...

    • On each member of the drop-down list, right-click on the name

    • A list will open, choose Properties

    • Guesswork time: using the various tabs near the top of the resulting window which opens, make a guess if this is the USB adapter driver which is choking your stuff with semaphore timeouts

  • Once you have made the proper guess, then close the USB Root Hub Properties window (but leave the Device Manager window open).

  • Physically disonnect anything and everything from that USB hub.

  • Unplug it.

  • Return your mouse pointer to that USB Root Hub in the list which you identified earlier.

  • Right click again

  • Choose Uninstall

  • Let Windows do its thing

  • Wait a little while

  • Power Down the whole computer if you have the time; some say this is required. I think I got away without it.

  • Plug the USB hub back into a USB connector on the PC

  • If the list in the device manager blinks and does a few flash-bulbs, it's okay.

  • Plug the BlueTooth connector back into the USB hub

  • Let windows do its thing some more

  • Within two minutes, I had a working COM port again, no semaphore timeouts.

Hope it works for anyone else who may be having a similar problem.

Virtual Serial Port for Linux

There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux.

It is a simple kernel module - a small source file. I don't know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands!

On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes):

#ifndef init_MUTEX
#define init_MUTEX(x) sema_init((x),1)
#endif

When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices.

edit:

I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don't know for sure but I think it crashed a machine in the office I was working on from home. I can't check until I'm back in the office on monday.

The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some "tiny tty" example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing.

edit:

The crash in the office really was the driver's fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine.

I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There's still code missing for hardware flow control managed by the driver, but I don't need it because I'll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code.

If anyone is interested in my version of the code, send me a message and I'll send it to you.

Converting serial port data to TCP/IP in a Linux environment

I have been struggling with the problem for a few days now.

The problem for me originated with VirtualBox/Ubuntu. I have lots of USB serial ports on my machine. When I tried to assign one of them to the VM it clobbered all of them - i.e. the host and other VMs were no longer able to use their USB serial devices.

My solution is to set up a stand-alone serial server on a netbook I happen to have in the closet.

I tried ser2net and it worked to put the serial port on the wire, but remtty did not work. I need to get the port as a tty on the VM.

socat worked perfectly.

There are good instructions here:

Example for remote tty (tty over TCP) using socat

Reading serial data in realtime in Python

A very good solution to this can be found here:

Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs, self.s.read(i) returns an empty string and you might want to throw an exception to indicate the timeout.

It is also supposed to be fast according to the author:

The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.

class ReadLine:
    def __init__(self, s):
        self.buf = bytearray()
        self.s = s

    def readline(self):
        i = self.buf.find(b"\n")
        if i >= 0:
            r = self.buf[:i+1]
            self.buf = self.buf[i+1:]
            return r
        while True:
            i = max(1, min(2048, self.s.in_waiting))
            data = self.s.read(i)
            i = data.find(b"\n")
            if i >= 0:
                r = self.buf + data[:i+1]
                self.buf[0:] = data[i+1:]
                return r
            else:
                self.buf.extend(data)

ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)

while True:

    print(rl.readline())

Print specific part of webpage

I wrote a tiny JavaScript module called PrintElements for dynamically printing parts of a webpage.

It works by iterating through selected node elements, and for each node, it traverses up the DOM tree until the BODY element. At each level, including the initial one (which is the to-be-printed node’s level), it attaches a marker class (pe-preserve-print) to the current node. Then attaches another marker class (pe-no-print) to all siblings of the current node, but only if there is no pe-preserve-print class on them. As a third act, it also attaches another class to preserved ancestor elements pe-preserve-ancestor.

A dead-simple supplementary print-only css will hide and show respective elements. Some benefits of this approach is that all styles are preserved, it does not open a new window, there is no need to move around a lot of DOM elements, and generally it is non-invasive with your original document.

See the demo, or read the related article for further details.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Suppose your project has the following structure and you want to do imports in the notebook.ipynb:

/app
  /mypackage
    mymodule.py
  /notebooks
    notebook.ipynb

If you are running Jupyter inside a docker container without any virtualenv it might be useful to create Jupyter (ipython) config in your project folder:

/app
  /profile_default
    ipython_config.py

Content of ipython_config.py:

c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append("/app")'
]

Open the notebook and check it out:

print(sys.path)

['', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/IPython/extensions', '/root/.ipython', '/app']

Now you can do imports in your notebook without any sys.path appending in the cells:

from mypackage.mymodule import myfunc

Immediate exit of 'while' loop in C++

cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

You don't need a break, in that case.

How to capture the "virtual keyboard show/hide" event in Android?

Not sure if anyone post this. Found this solution simple to use!. The SoftKeyboard class is on gist.github.com. But while keyboard popup/hide event callback we need a handler to properly do things on UI:

/*
Somewhere else in your code
*/
RelativeLayout mainLayout = findViewById(R.layout.main_layout); // You must use your root layout
InputMethodManager im = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);

/*
Instantiate and pass a callback
*/
SoftKeyboard softKeyboard;
softKeyboard = new SoftKeyboard(mainLayout, im);
softKeyboard.setSoftKeyboardCallback(new SoftKeyboard.SoftKeyboardChanged()
{

    @Override
    public void onSoftKeyboardHide() 
    {
        // Code here
        new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Code here will run in UI thread
                    ...
                }
            });
    }

    @Override
    public void onSoftKeyboardShow() 
    {
        // Code here
        new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Code here will run in UI thread
                    ...
                }
            });

    }   
});

Visual Studio: Relative Assembly References Paths

Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.

I've done this plenty of times in VS 2005 without any problems.

How do you use NSAttributedString?

Swift 4

let combination = NSMutableAttributedString()

var part1 = NSMutableAttributedString()
var part2 = NSMutableAttributedString()
var part3 = NSMutableAttributedString()

let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)]

let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)]

let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15),
                                 NSAttributedStringKey.foregroundColor: UIColor.red]

if let regular = attrRegular as? [NSAttributedStringKey : NSObject]{
    part1 = NSMutableAttributedString(string: "first", attributes: regular)

}
if let bold = attrRegular as? [NSAttributedStringKey : NSObject]{
    part2 = NSMutableAttributedString(string: "second", attributes: bold)
}

if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]{
    part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor)
}

combination.append(part1)
combination.append(part2)
combination.append(part3)

Attributes list please see here NSAttributedStringKey on Apple Docs

vertical-align: middle with Bootstrap 2

If I remember correctly from my own use of bootstrap, the .spanN classes are floated, which automatically makes them behave as display: block. To make display: table-cell work, you need to remove the float.

What's the use of ob_start() in php?

You have it backwards. ob_start does not buffer the headers, it buffers the content. Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it.

This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).

Implement touch using Python?

"open(file_name, 'a').close()" did not work for me in Python 2.7 on Windows. "os.utime(file_name, None)" worked just fine.

Also, I had a need to recursively touch all files in a directory with a date older than some date. I created hte following based on ephemient's very helpful response.

def touch(file_name):
    # Update the modified timestamp of a file to now.
    if not os.path.exists(file_name):
        return
    try:
        os.utime(file_name, None)
    except Exception:
        open(file_name, 'a').close()

def midas_touch(root_path, older_than=dt.now(), pattern='**', recursive=False):
    '''
    midas_touch updates the modified timestamp of a file or files in a 
                directory (folder)

    Arguements:
        root_path (str): file name or folder name of file-like object to touch
        older_than (datetime): only touch files with datetime older than this 
                   datetime
        pattern (str): filter files with this pattern (ignored if root_path is
                a single file)
        recursive (boolean): search sub-diretories (ignored if root_path is a 
                  single file)
    '''
    # if root_path NOT exist, exit
    if not os.path.exists(root_path):
        return
    # if root_path DOES exist, continue.
    else:
        # if root_path is a directory, touch all files in root_path
        if os.path.isdir(root_path):
            # get a directory list (list of files in directory)
            dir_list=find_files(root_path, pattern='**', recursive=False)
            # loop through list of files
            for f in dir_list:
                # if the file modified date is older thatn older_than, touch the file
                if dt.fromtimestamp(os.path.getmtime(f)) < older_than:
                    touch(f)
                    print "Touched ", f
        # if root_path is a file, touch the file
        else:
            # if the file modified date is older thatn older_than, touch the file
            if dt.fromtimestamp(os.path.getmtime(f)) < older_than:
                touch(root_path)

Difference between "and" and && in Ruby?

The Ruby Style Guide says it better than I could:

Use &&/|| for boolean expressions, and/or for control flow. (Rule of thumb: If you have to use outer parentheses, you are using the wrong operators.)

# boolean expression
if some_condition && some_other_condition
  do_something
end

# control flow
document.saved? or document.save!

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

Bootstrap date time picker

In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
    <head>_x000D_
      <meta charset="utf-8">_x000D_
      <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    _x000D_
    _x000D_
      <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
    </head>_x000D_
    _x000D_
    _x000D_
    <body>_x000D_
    _x000D_
       <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    _x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Codeigniter - no input file specified

Just add the ? sign after index.php in the .htaccess file :

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

and it would work !

Resize height with Highcharts

Ricardo's answer is correct, however: sometimes you may find yourself in a situation where the container simply doesn't resize as desired as the browser window changes size, thus not allowing highcharts to resize itself.

This always works:

  1. Set up a timed and pipelined resize event listener. Example with 500ms on jsFiddle
  2. use chart.setSize(width, height, doAnimation = true); in your actual resize function to set the height and width dynamically
  3. Set reflow: false in the highcharts-options and of course set height and width explicitly on creation. As we'll be doing our own resize event handling there's no need Highcharts hooks in another one.

How to pass an ArrayList to a varargs method parameter?

Though it is marked as resolved here my KOTLIN RESOLUTION

fun log(properties: Map<String, Any>) {
    val propertyPairsList = properties.map { Pair(it.key, it.value) }
    val bundle = bundleOf(*propertyPairsList.toTypedArray())
}

bundleOf has vararg parameter

How to solve java.lang.NoClassDefFoundError?

Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:

1.firstly, create the instance of class in a simple thread and catch the crash.

2.then call the field method of Class in main thread, you will get the NoClassDefFoundError.

here is the test code:

public class MyClass{
       private static  Handler mHandler = new Handler();
       public static int num = 0;
}

in your onCrete method of Main activity, add test code part:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //test code start
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MyClass myClass = new MyClass();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }).start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    MyClass.num = 3;
    // end of test code
}

there is a simple way to fix it using a handlerThread to init handler:

private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
    handlerThread.start();
    mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}

Material Design not styling alert dialogs

Material Design styling alert dialogs: Custom Font, Button, Color & shape,..

 MaterialAlertDialogBuilder(requireContext(),
                R.style.MyAlertDialogTheme
            )
                .setIcon(R.drawable.ic_dialogs_24px)
                .setTitle("Feedback")
                //.setView(R.layout.edit_text)
                .setMessage("Do you have any additional comments?")
                .setPositiveButton("Send") { dialog, _ ->

                    val input =
                        (dialog as AlertDialog).findViewById<TextView>(
                            android.R.id.text1
                        )
                    Toast.makeText(context, input!!.text, Toast.LENGTH_LONG).show()

                }
                .setNegativeButton("Cancel") { _, _ ->
                    Toast.makeText(requireContext(), "Clicked cancel", Toast.LENGTH_SHORT).show()
                }
                .show()

Style:

  <style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
  
        <item name="android:textAppearanceSmall">@style/MyTextAppearance</item>
        <item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
        <item name="android:textAppearanceLarge">@style/MyTextAppearance</item>

        <item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
        <item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
        <item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>

        <item name="android:backgroundDimEnabled">true</item>

        <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
        </item>

    </style>




    <style name="MyTextAppearance" parent="TextAppearance.AppCompat">
        <item name="android:fontFamily">@font/rosarivo</item>
    </style>


        <style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
   <!--     <item name="backgroundTint">@color/colorPrimaryDark</item>-->
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
       <!-- <item name="android:textColor">@android:color/white</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


    <style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <!--<item name="android:textColor">@android:color/darker_gray</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


  <style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">8dp</item>
    </style>

Output: enter image description here

SQL SERVER DATETIME FORMAT

In MS SQL Server you can do:

SET DATEFORMAT ymd

Sass .scss: Nesting and multiple classes?

You can use the parent selector reference &, it will be replaced by the parent selector after compilation:

For your example:

.container {
    background:red;
    &.desc{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
.container.desc {
    background: blue;
}

The & will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &.

This notation is most often used to write pseudo-elements and -classes:

.element{
    &:hover{ ... }
    &:nth-child(1){ ... }
}

However, you can place the & at virtually any position you like*, so the following is possible too:

.container {
    background:red;
    #id &{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
#id .container {
    background: blue;
}

However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.

*: No other characters than whitespaces are allowed in front of the &. So you cannot do a direct concatenation of selector+& - #id& would throw an error.

How to check type of files without extensions in python?

With newer subprocess library, you can now use the following code (*nix only solution):

import subprocess
import shlex

filename = 'your_file'
cmd = shlex.split('file --mime-type {0}'.format(filename))
result = subprocess.check_output(cmd)
mime_type = result.split()[-1]
print mime_type

Can we pass an array as parameter in any function in PHP?

I composed this code as an example. Hope the idea works!

<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
  function greetings($friends){
    echo "Greetings, $friends <br>";
  }
  foreach ($friends as $friend) {
  greetings($friend);
  }
?>

How can I convert byte size into a human-readable format in Java?

If you use Android, you can simply use android.text.format.Formatter.formatFileSize().

Alternatively, here's a solution based on this popular post:

  /**
   * Formats the bytes to a human readable format
   *
   * @param si true if each kilo==1000, false if kilo==1024
   */
  @SuppressLint("DefaultLocale")
  public static String humanReadableByteCount(final long bytes, final boolean si)
  {
    final int unit = si ? 1000 : 1024;
    if(bytes<unit)
      return bytes + " B";

    double result = bytes;
    final String unitsToUse = (si ? "k" : "K") + "MGTPE";
    int i = 0;
    final int unitsCount = unitsToUse.length();
    while(true)
    {
      result /= unit;
      if(result < unit)
        break;
      // Check if we can go further:
      if(i == unitsCount-1)
        break;
      ++i;
    }

    final StringBuilder sb = new StringBuilder(9);
    sb.append(String.format("%.1f ", result));
    sb.append(unitsToUse.charAt(i));
    if(si)
      sb.append('B');
    else sb.append('i').append('B');
    final String resultStr = sb.toString();
    return resultStr;
  }

Or in Kotlin:

/**
 * formats the bytes to a human readable format
 *
 * @param si true if each kilo==1000, false if kilo==1024
 */
@SuppressLint("DefaultLocale")
fun humanReadableByteCount(bytes: Long, si: Boolean): String? {
    val unit = if (si) 1000.0 else 1024.0
    if (bytes < unit)
        return "$bytes B"
    var result = bytes.toDouble()
    val unitsToUse = (if (si) "k" else "K") + "MGTPE"
    var i = 0
    val unitsCount = unitsToUse.length
    while (true) {
        result /= unit
        if (result < unit || i == unitsCount - 1)
            break
        ++i
    }
    return with(StringBuilder(9)) {
        append(String.format("%.1f ", result))
        append(unitsToUse[i])
        if (si) append('B') else append("iB")
    }.toString()
}

How Do I Upload Eclipse Projects to GitHub?

Many of these answers mention how to share the project on Git, which is easy, you just share the code on git, but one thing to take note of is that there is no apparent "project file" that the end user can double click on. Instead you have to use Import->General->Existing project and select the whole folder

Equivalent of String.format in jQuery

Way past the late season but I've just been looking at the answers given and have my tuppence worth:

Usage:

var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');

Method:

function strFormat() {
    var args = Array.prototype.slice.call(arguments, 1);
    return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
    });
}

Result:

"aalert" is not defined
3.14 3.14 a{2}bc foo

How to find out if a Python object is a string?

if type(varA) == str or type(varB) == str:
    print 'string involved'

from EDX - online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python

Java error: Comparison method violates its general contract

Consider the following case:

First, o1.compareTo(o2) is called. card1.getSet() == card2.getSet() happens to be true and so is card1.getRarity() < card2.getRarity(), so you return 1.

Then, o2.compareTo(o1) is called. Again, card1.getSet() == card2.getSet() is true. Then, you skip to the following else, then card1.getId() == card2.getId() happens to be true, and so is cardType > item.getCardType(). You return 1 again.

From that, o1 > o2, and o2 > o1. You broke the contract.

Simplest way to restart service on a remote computer

I recommend the method given by doofledorfer.

If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.

function ServiceStart(sMachine, sService : string) : boolean;  //start service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    psTemp     : PChar;
    dwChkP     : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);  //connect to the service control manager

  if(schm > 0)then begin // if successful...
    schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);    // open service handle, start and query status
    if(schs > 0)then begin     // if successful...
      psTemp := nil;
      if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
          dwChkP := ss.dwCheckPoint;  //dwCheckPoint contains a value incremented periodically to report progress of a long operation.  Store it.
          Sleep(ss.dwWaitHint);  //Sleep for recommended time before checking status again
          if(not QueryServiceStatus(schs,ss))then
            break;  //couldn't check status
          if(ss.dwCheckPoint < dwChkP)then
            Break;  //if QueryServiceStatus didn't work for some reason, avoid infinite loop
        end;  //while not running
      CloseServiceHandle(schs);
    end;  //if able to get service handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_RUNNING = ss.dwCurrentState;  //if we were able to start it, return true
end;

function ServiceStop(sMachine, sService : string) : boolean;  //stop service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    dwChkP     : DWord;
begin
  schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);

  if(schm > 0)then begin
    schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
    if(schs > 0)then begin
      if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          if(not QueryServiceStatus(schs,ss))then
            Break;

          if(ss.dwCheckPoint < dwChkP)then
            Break;
        end;  //while
      CloseServiceHandle(schs);
    end;  //if able to get svc handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_STOPPED = ss.dwCurrentState;
end;

How can I get href links from HTML using Python?

This is way late to answer but it will work for latest python users:

from bs4 import BeautifulSoup
import requests 


html_page = requests.get('http://www.example.com').text

soup = BeautifulSoup(html_page, "lxml")
for link in soup.findAll('a'):
    print(link.get('href'))

Don't forget to install "requests" and "BeautifulSoup" package and also "lxml". Use .text along with get otherwise it will throw an exception.

"lxml" is used to remove that warning of which parser to be used. You can also use "html.parser" whichever fits your case.

How do I get time of a Python program's execution?

Timeit is a class in Python used to calculate the execution time of small blocks of code.

Default_timer is a method in this class which is used to measure the wall clock timing, not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.

A sample of the code is as follows:

from timeit import default_timer as timer

start= timer()

# Some logic

end = timer()

print("Time taken:", end-start)

How to have a default option in Angular.js select box

In my case, I was need to insert a initial value only to tell to user to select an option, so, I do like the code below:

<select ...
    <option value="" ng-selected="selected">Select one option</option>
</select>

When I tryed an option with the value != of an empty string (null) the option was substituted by angular, but, when put an option like that (with null value), the select apear with this option.

Sorry by my bad english and I hope that I help in something with this.

How to check cordova android version of a cordova/phonegap project?

After upgrading the Application. I observed different Cordova versions.

  1. Apache Cordova Cli version which is 6.0.0.
  2. Cordova Android version which is 5.1.0.
  3. Cordova IOS version which is 4.1.1.
  4. Docs version is which is 6.0.0, shown on the Cordova Docs website.

Now i am confused, On which version basis, Google Dev Console is giving warning?

Please migrate your app(s) to Apache Cordova v.4.1.1 or higher as soon as possible and increment the version number of the upgraded APK. Beginning May 9, 2016, Google Play will block publishing of any new apps or updates that use pre-4.1.1 versions of Apache Cordova.

The vulnerabilities were addressed in Apache Cordova 4.1.1. If you’re using a 3rd party library that bundles Apache Cordova, you’ll need to upgrade it to a version that bundles Apache Cordova 4.1.1 or later.

And before upgrading. Our Application versions were these.

  1. Apache Cordova Cli version which is 5.4.1.
  2. Cordova Android version which is 4.1.1.
  3. Cordova IOS version which is 3.9.1.
  4. Docs version is which is 5.4.1, shown on the Cordova Docs website.

How to access custom attributes from event object in React?

Try instead of assigning dom properties (which is slow) just pass your value as a parameter to function that actually create your handler:

render: function() {
...
<a style={showStyle} onClick={this.removeTag(i)}></a>
...
removeTag = (customAttribute) => (event) => {
    this.setState({inputVal: customAttribute});
}

How to create a directive with a dynamic template in AngularJS?

One way is using a template function in your directive:

...
template: function(tElem, tAttrs){
    return '<div ng-include="' + tAttrs.template + '" />';
}
...

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

Signed versus Unsigned Integers

Just a few points for completeness:

  • this answer is discussing only integer representations. There may be other answers for floating point;

  • the representation of a negative number can vary. The most common (by far - it's nearly universal today) in use today is two's complement. Other representations include one's complement (quite rare) and signed magnitude (vanishingly rare - probably only used on museum pieces) which is simply using the high bit as a sign indicator with the remain bits representing the absolute value of the number.

  • When using two's complement, the variable can represent a larger range (by one) of negative numbers than positive numbers. This is because zero is included in the 'positive' numbers (since the sign bit is not set for zero), but not the negative numbers. This means that the absolute value of the smallest negative number cannot be represented.

  • when using one's complement or signed magnitude you can have zero represented as either a positive or negative number (which is one of a couple of reasons these representations aren't typically used).

Is it possible to run one logrotate check manually?

If you want to force-run a single specific directory or daemon's log files, you can usually find the configuration in /etc/logrotate.d, and they will work standalone.

Keep in mind that global configuration specified in /etc/logrotate.conf will not apply, so if you do this you should ensure you specify all the options you want in the /etc/logrotate.d/[servicename] config file specifically.

You can try it out with -d to see what would happen:

logrotate -df /etc/logrotate.d/nginx

Then you can run (using nginx as an example):

logrotate -f /etc/logrotate.d/nginx

And the nginx logs alone will be rotated.

! [rejected] master -> master (fetch first)

The reason it happened in my case was when creating the GitHub rep link, I initialized it with README file

While creating Git remote do not initialize it with README file otherwise it would show err

Don't do that & it will definitely work fine Instead initialize it with the readme file if you wish to after pushing to the master branch

Using grep to search for hex strings in a file

If you want search for printable strings, you can use:

strings -ao filename | grep string

strings will output all printable strings from a binary with offsets, and grep will search within.

If you want search for any binary string, here is your friend:

Could not commit JPA transaction: Transaction marked as rollbackOnly

As explained @Yaroslav Stavnichiy if a service is marked as transactional spring tries to handle transaction itself. If any exception occurs then a rollback operation performed. If in your scenario ServiceUser.method() is not performing any transactional operation you can use @Transactional.TxType annotation. 'NEVER' option is used to manage that method outside transactional context.

Transactional.TxType reference doc is here.

How to count the number of columns in a table using SQL?

Maybe something like this:

SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'

this will count number of columns in a the table FOO

You can also just

select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';

where the owner is schema and note that Table Names are upper case

Auto-increment primary key in SQL tables

I don't have Express Management Studio on this machine, so I'm going based on memory. I think you need to set the column as "IDENTITY", and there should be a [+] under properties where you can expand, and set auto-increment to true.

getContext is not a function

I recently got this error because the typo, I write 'canavas' instead of 'canvas', hope this could help someone who is searching for this.

Composer Update Laravel

The following works for me:

composer update --no-scripts

Select tableview row programmatically

From reference documentation:

Calling this method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor does it send UITableViewSelectionDidChangeNotification notifications to observers.

What I would do is:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self doSomethingWithRowAtIndexPath:indexPath];
}

And then, from where you wanted to call selectRowAtIndexPath, you instead call doSomethingWithRowAtIndexPath. On top of that, you can additionally also call selectRowAtIndexPath if you want the UI feedback to happen.

How to disable auto-play for local video in iframe

Replace the iframe for this:

<video class="video-fluid z-depth-1" loop controls muted>
  <source src="videos/example.mp4" type="video/mp4" />
</video>

How to define Singleton in TypeScript

Singleton classes in TypeScript are generally an anti-pattern. You can simply use namespaces instead.

Useless singleton pattern

class Singleton {
    /* ... lots of singleton logic ... */
    public someMethod() { ... }
}

// Using
var x = Singleton.getInstance();
x.someMethod();

Namespace equivalent

export namespace Singleton {
    export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";

SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reason

How to install SQL Server Management Studio 2008 component only

The accepted answer was correct up until July 2011. To get the latest version, including the Service Pack you should find the latest version as described here:

For example, if you check the SP2 CTP and SP1, you'll find the latest version of SQL Server Management Studio under SP1:

Download the 32-bit (x86) or 64-bit (x64) version of the SQLManagementStudio*.exe files as appropriate and install it. You can find out whether your system is 32-bit or 64-bit by right clicking Computer, selecting Properties and looking at the System Type.

Although you could apply the service pack to the base version that results from following the accepted answer, it's easier to just download the latest version of SQL Server Management Studio and simply install it in one step.

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

Android Imagebutton change Image OnClick

This misled me a bit - it should be setImageResource instead of setBackgroundResource :) !!

The following works fine :

ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);       
 btn.setImageResource(R.drawable.actions_record);

while when using the setBackgroundResource the actual imagebutton's image stays while the background image is changed which leads to a ugly looking imageButton object

Thanks.

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I am not an expert. If you are getting ORA-01017 while trying to connect HR schema from SQL Developer in Oracle 11g Please try to unlock the HR as follows

alter user HR identified by hr DEFAULT tablespace users temporary tablespace temp account unlock;

Format number to always show 2 decimal places

This answer will fail if value = 1.005.

As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:

Number(Math.round(1.005+'e2')+'e-2'); // 1.01

Cleaner code as suggested by @Kon, and the original author:

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)

You may add toFixed() at the end to retain the decimal point e.g: 1.00 but note that it will return as string.

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)

Credit: Rounding Decimals in JavaScript

Iterator invalidation rules

Since this question draws so many votes and kind of becomes an FAQ, I guess it would be better to write a separate answer to mention one significant difference between C++03 and C++11 regarding the impact of std::vector's insertion operation on the validity of iterators and references with respect to reserve() and capacity(), which the most upvoted answer failed to notice.

C++ 03:

Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().

C++11:

Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

So in C++03, it is not "unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)" as mentioned in the other answer, instead, it should be "greater than the size specified in the most recent call to reserve()". This is one thing that C++03 differs from C++11. In C++03, once an insert() causes the size of the vector to reach the value specified in the previous reserve() call (which could well be smaller than the current capacity() since a reserve() could result a bigger capacity() than asked for), any subsequent insert() could cause reallocation and invalidate all the iterators and references. In C++11, this won't happen and you can always trust capacity() to know with certainty that the next reallocation won't take place before the size overpasses capacity().

In conclusion, if you are working with a C++03 vector and you want to make sure a reallocation won't happen when you perform insertion, it's the value of the argument you previously passed to reserve() that you should check the size against, not the return value of a call to capacity(), otherwise you may get yourself surprised at a "premature" reallocation.

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

You have to save that location somehow.

Say it's a POST form, just put the current location in a hidden field and then use it in the header() Location.

How to get index of object by its property in JavaScript?

Only way known for me is to looping through all array:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name==="John"){index=i;break;}

or case insensitive:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name.toLowerCase()==="john"){index=i;break;}

On result variable index contain index of object or -1 if not found.

How to center a subview of UIView

Using the same center in the view and subview is the simplest way of doing it. You can do something like this,

UIView *innerView = ....;
innerView.view.center = self.view.center;
[self.view addSubView:innerView];

Get the IP address of the machine

As you have found out there is no such thing as a single "local IP address". Here's how to find out the local address that can be sent out to a specific host.

  1. Create a UDP socket
  2. Connect the socket to an outside address (the host that will eventually receive the local address)
  3. Use getsockname to get the local address

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

Linq on DataTable: select specific column into datatable, not whole table

Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...

Consider following example, suppose we have DataTable like below.

DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));

Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.

Area | Quantity | Breath | Length | Price = Quantity * breath *Length

Than we have to fire following query which will give us exact result as we want.

var data = ObjDt.AsEnumerable().Select
            (r => new
            {
                Area = r.Field<string>("Area"),
                Que = r.Field<int>("Quantity"),
                Breath = r.Field<decimal>("Breath"),
                Length = r.Field<decimal>("Length"),
                totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
            }).ToList();

We just have to assign this data variable as Data Source.

By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…

Set keyboard caret position in html textbox

If you need to focus some textbox and your only problem is that the entire text gets highlighted whereas you want the caret to be at the end, then in that specific case, you can use this trick of setting the textbox value to itself after focus:

$("#myinputfield").focus().val($("#myinputfield").val());

HTTP headers in Websockets client API

You can not send custom header when you want to establish WebSockets connection using JavaScript WebSockets API. You can use Subprotocols headers by using the second WebSocket class constructor:

var ws = new WebSocket("ws://example.com/service", "soap");

and then you can get the Subprotocols headers using Sec-WebSocket-Protocol key on the server.

There is also a limitation, your Subprotocols headers values can not contain a comma (,) !

To get specific part of a string in c#

You can use Substring:

string b = a.Substring(0,3);

Converting PKCS#12 certificate into PEM using OpenSSL

You just need to supply a password. You can do it within the same command line with the following syntax:

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]

You will then be prompted for a password to encrypt the private key in your output file. Include the "nodes" option in the line above if you want to export the private key unencrypted (plaintext):

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes

More info: http://www.openssl.org/docs/apps/pkcs12.html

Stop executing further code in Java

To stop executing java code just use this command:

    System.exit(1);

After this command java stops immediately!

for example:

    int i = 5;
    if (i == 5) {
       System.out.println("All is fine...java programm executes without problem");
    } else {
       System.out.println("ERROR occured :::: java programm has stopped!!!");
       System.exit(1);
    }

Change drawable color programmatically

Try this:

Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.my_drawable); 
Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(wrappedDrawable, Color.RED);    

Using DrawableCompat is important because it provides backwards compatibility and bug fixes on API 22 devices and earlier.

Syntax error: Illegal return statement in JavaScript

return only makes sense inside a function. There is no function in your code.

Also, your code is worthy if the Department of Redundancy Department. Assuming you move it to a proper function, this would be better:

return confirm(".json_encode($message).");

EDIT much much later: Changed code to use json_encode to ensure the message contents don't break just because of an apostrophe in the message.

How do I turn off Oracle password expiration?

I will suggest its not a good idea to turn off the password expiration as it can lead to possible threats to confidentiality, integrity and availability of data.

However if you want so.

If you have proper access use following SQL

SELECT username, account_status FROM dba_users;

This should give you result like this.

   USERNAME                       ACCOUNT_STATUS
------------------------------ -----------------

SYSTEM                         OPEN
SYS                            OPEN
SDMADM                         OPEN
MARKETPLACE                    OPEN
SCHEMAOWNER                    OPEN
ANONYMOUS                      OPEN
SCHEMAOWNER2                   OPEN
SDMADM2                        OPEN
SCHEMAOWNER1                   OPEN
SDMADM1                        OPEN
HR                             EXPIRED(GRACE)

USERNAME                       ACCOUNT_STATUS
------------------------------ -----------------

APEX_PUBLIC_USER               LOCKED
APEX_040000                    LOCKED
FLOWS_FILES                    LOCKED
XS$NULL                        EXPIRED & LOCKED
OUTLN                          EXPIRED & LOCKED
XDB                            EXPIRED & LOCKED
CTXSYS                         EXPIRED & LOCKED
MDSYS                          EXPIRED & LOCKED

Now you can use Pedro Carriço answer https://stackoverflow.com/a/6777079/2432468

Javascript String to int conversion

Although parseInt is the official function to do this, you can achieve the same with this code:

number*1

The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.

javascript toISOString() ignores timezone offset

moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.

The following works as well:

var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
// => '2015-01-26T06:40:36.181'

The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.

How can I get the current screen orientation?

In some devices void onConfigurationChanged() may crash. User will use this code to get current screen orientation.

public int getScreenOrientation()
{
    Display getOrient = getActivity().getWindowManager().getDefaultDisplay();
    int orientation = Configuration.ORIENTATION_UNDEFINED;
    if(getOrient.getWidth()==getOrient.getHeight()){
        orientation = Configuration.ORIENTATION_SQUARE;
    } else{ 
        if(getOrient.getWidth() < getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_PORTRAIT;
        }else { 
             orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return orientation;
}

And use

if (orientation==1)        // 1 for Configuration.ORIENTATION_PORTRAIT
{                          // 2 for Configuration.ORIENTATION_LANDSCAPE
   //your code             // 0 for Configuration.ORIENTATION_SQUARE
}

How can I create a text box for a note in markdown?

Have you tried using double tabs? To make a box:

Start on a fresh line
Hit tab twice, type up the content
Your content should appear in a box

It works for me in a regular Rmarkdown document with html output. The double-tabbed portion should appear in a rounded rectangular light grey box.

Inline Form nested within Horizontal Form in Bootstrap 3

I have created a demo for you.

Here is how your nested structure should be in Bootstrap 3:

<div class="form-group">
    <label for="birthday" class="col-xs-2 control-label">Birthday</label>
    <div class="col-xs-10">
        <div class="form-inline">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="year"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="month"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="day"/>
            </div>
        </div>
    </div>
</div>

Notice how the whole form-inline is nested within the col-xs-10 div containing the control of the horizontal form. In other terms, the whole form-inline is the "control" of the birthday label in the main horizontal form.

Note that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:

.form-inline .form-group{
    margin-left: 0;
    margin-right: 0;
}

Java GC (Allocation Failure)

"Allocation Failure" is a cause of GC cycle to kick in.

"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.

Older JVM were not printing GC cause for minor GC cycles.

"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark is enabled).

How to compare two dates along with time in java

Use compareTo()

Return Values

0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

Like

if(date1.compareTo(date2)>0) 

Jquery: how to trigger click event on pressing enter key

$('#txtSearchProdAssign').keypress(function (e) {
  if (e.which == 13) {
    $('input[name = butAssignProd]').click();
    return false;  
  }
});

I also just found Submitting a form on 'Enter' which covers most of the issues comprehensively.

How many bits is a "word"?

On x86/x64 processors, a byte is 8 bits, and there are 256 possible binary states in 8 bits, 0 thru 255. This is how the OS translates your keyboard key strokes into letters on the screen. When you press the 'A' key, the keyboard sends a binary signal equal to the number 97 to the computer, and the computer prints a lowercase 'a' on the screen. You can confirm this in any Windows text editing software by holding an ALT key, typing 97 on the NUMPAD, then releasing the ALT key. If you replace '97' with any number from 0 to 255, you will see the character associated with that number on the system's character code page printed on the screen.

If a character is 8 bits, or 1 byte, then a WORD must be at least 2 characters, so 16 bits or 2 bytes. Traditionally, you might think of a word as a varying number of characters, but in a computer, everything that is calculable is based on static rules. Besides, a computer doesn't know what letters and symbols are, it only knows how to count numbers. So, in computer language, if a WORD is equal to 2 characters, then a double-word, or DWORD, is 2 WORDs, which is the same as 4 characters or bytes, which is equal to 32 bits. Furthermore, a quad-word, or QWORD, is 2 DWORDs, same as 4 WORDs, 8 characters, or 64 bits.

Note that these terms are limited in function to the Windows API for developers, but may appear in other circumstances (eg. the Linux dd command uses numerical suffixes to compound byte and block sizes, where c is 1 byte and w is bytes).

How to reload/refresh an element(image) in jQuery

I may have to reload the image source several times. I found a solution with Lodash that works well for me:

$("#myimg").attr('src', _.split($("#myimg").attr('src'), '?', 1)[0] + '?t=' + _.now());

An existing timestamp will be truncated and replaced with a new one.

Getting only 1 decimal place

Are you trying to represent it with only one digit:

print("{:.1f}".format(number)) # Python3
print "%.1f" % number          # Python2

or actually round off the other decimal places?

round(number,1)

or even round strictly down?

math.floor(number*10)/10

How should I pass multiple parameters to an ASP.Net Web API GET?

Just add a new route to the WebApiConfig entries.

For instance, to call:

public IEnumerable<SampleObject> Get(int pageNumber, int pageSize) { ..

add:

config.Routes.MapHttpRoute(
    name: "GetPagedData",
    routeTemplate: "api/{controller}/{pageNumber}/{pageSize}"
);

Then add the parameters to the HTTP call:

GET //<service address>/Api/Data/2/10 

FirstOrDefault returns NullReferenceException if no match is found

Simply use the question mark trick for null checks:

string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID))?.Value.DisplayName ?? "DEFINE A DEFAULT DISPLAY NAME HERE";

How to get distinct values from an array of objects in JavaScript?

Here's another way to solve this:

var result = {};
for(var i in array) {
    result[array[i].age] = null;
}
result = Object.keys(result);

I have no idea how fast this solution is compared to the others, but I like the cleaner look. ;-)


EDIT: Okay, the above seems to be the slowest solution of all here.

I've created a performance test case here: http://jsperf.com/distinct-values-from-array

Instead of testing for the ages (Integers), I chose to compare the names (Strings).

Method 1 (TS's solution) is very fast. Interestingly enough, Method 7 outperforms all other solutions, here I just got rid of .indexOf() and used a "manual" implementation of it, avoiding looped function calling:

var result = [];
loop1: for (var i = 0; i < array.length; i++) {
    var name = array[i].name;
    for (var i2 = 0; i2 < result.length; i2++) {
        if (result[i2] == name) {
            continue loop1;
        }
    }
    result.push(name);
}

The difference in performance using Safari & Firefox is amazing, and it seems like Chrome does the best job on optimization.

I'm not exactly sure why the above snippets is so fast compared to the others, maybe someone wiser than me has an answer. ;-)

What does "publicPath" in Webpack do?

publicPath is used by webpack for the replacing relative path defined in your css for refering image and font file.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

I had a similar issue with 50,000 rdf/xml files in 5,000 directories (the Project Gutenberg catalog file). I solved it with riot (in the jena distribution)

the directory is cache/epub/NN/nn.rdf (where NN is a number)

in the directory above the directory where all the files are, i.e. in cache

riot epub/*/*.rdf --output=turtle > allTurtle.ttl

This produces possibly many warnings but the result is in a format which can be loaded into jena (using the fuseki web interface).

surprisingly simple (at least in this case).

How to set the timezone in Django?

Here is the list of valid timezones:

http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

You can use

TIME_ZONE = 'Europe/Istanbul'

for UTC+02:00

How to make this Header/Content/Footer layout using CSS?

After fiddling around a while I found a solution that works in >IE7, Chrome, Firefox:

http://jsfiddle.net/xfXaw/

* {
    margin:0;
    padding:0;
}

html, body {
    height:100%;
}

#wrap {
    min-height:100%;

}

#header {
    background: red;
}

#content {
    padding-bottom: 50px;
}

#footer {
    height:50px;
    margin-top:-50px;
    background: green;
}

HTML:

<div id="wrap">
    <div id="header">header</div>
    <div id="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. </div>
</div>
<div id="footer">footer</div>

How do I move a file (or folder) from one folder to another in TortoiseSVN?

In Windows Explorer, with the right-mouse button, click and drag the file from where it is to where you want it. Upon releasing the right-mouse button, you will see a context menu with options such as "SVN Move versioned file here".

http://tortoisesvn.net/most-forgotten-feature

Better way to right align text in HTML Table

A number of years ago (in the IE only days) I was using the <col align="right"> tag, but I just tested it and and it seems to be an IE only feature:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Test</title>
</head>
<body>
    <table width="100%" border="1">
        <col align="left" />
        <col align="left" />
        <col align="right" />
        <tr>
            <th>ISBN</th>
            <th>Title</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>3476896</td>
            <td>My first HTML</td>
            <td>$53</td>
        </tr>
    </table>
</body>
</html>

The snippet is taken from www.w3schools.com. Of course, it should not be used (unless for some reason you really target the IE rendering engine only), but I thought it would be interesting to mention it.

Edit:

Overall, I don't understand the reasoning behing abandoning this tag. It would appear to be very useful (at least for manual HTML publishing).

How do I upgrade PHP in Mac OS X?

There is no built-in package manager. MacPorts doesn't recognize php as an installed package because it didn't install PHP itself.

You could still install it with MacPorts. sudo port install php52 (or whichever version you want) will install PHP.

It won't overwrite the Apple-supplied version. It'll install it under /opt/local. You can add /opt/local to the beginning of your $PATH, and use the MacPorts version in your Apache config.

Match all elements having class name starting with a specific string

You can easily add multiple classes to divs... So:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

.myclass {...}

And you can still use your other classes like this:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

.myclass.myclass-three {...}

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

Using a remote repository with non-standard port

SSH based git access method can be specified in <repo_path>/.git/config using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:

URL style:

url = ssh://[user@]host.xz[:port]/path/to/repo.git/

SCP style:

url = [user@]host.xz:path/to/repo.git/

Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config host definition in your ~/.ssh/config such as:

Host my_git_host
HostName git.some.host.org
Port 24589
User not_a_root_user

Then you can test in a shell with:

ssh my_git_host

and alter your SCP-style URI in <repo_path>/.git/config as:

url = my_git_host:path/to/repo.git/

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

To anybody who is facing this issue on MacOS machines, try this:

  1. brew uninstall gpg
  2. brew install gpg2
  3. brew install pinentry-mac (if needed)
  4. gpg --full-generate-key Create a key by using an algorithm.
  5. Get generated key by executing: gpg --list-keys
  6. Set the key here git config --global user.signingkey <Key from your list>
  7. git config --global gpg.program /usr/local/bin/gpg
  8. git config --global commit.gpgsign true
  9. If you want to export your Key to GitHub then: gpg --armor --export <key> and add this key to GitHub at GPG keys: https://github.com/settings/keys (with START and END line included)

If the issue still exists:

test -r ~/.bash_profile && echo 'export GPG_TTY=$(tty)' >> ~/.bash_profile

echo 'export GPG_TTY=$(tty)' >> ~/.profile

If the issue still exists:

Install https://gpgtools.org and sign the key that you used by pressing Sign from the menu bar: Key->Sign

If the issue still exists:

Go to: ??your global .gitconfig file which in my case is at: ??/Users/gent/.gitconfig And modify the .gitconfig file (please make sure Email and Name are the same with the one that you have created while generating the Key):

_x000D_
_x000D_
[user]_x000D_
 email = [email protected]_x000D_
 name = Gent_x000D_
 signingkey = <YOURKEY>_x000D_
[gpg]_x000D_
 program = /usr/local/bin/gpg_x000D_
[commit]_x000D_
 gpsign = true_x000D_
 gpgsign = true_x000D_
[filter "lfs"]_x000D_
 process = git-lfs filter-process_x000D_
 required = true_x000D_
 clean = git-lfs clean -- %f_x000D_
 smudge = git-lfs smudge -- %f_x000D_
[credential]_x000D_
 helper = osxkeychain
_x000D_
_x000D_
_x000D_

How to push object into an array using AngularJS

'Push' is for arrays.

You can do something like this:

app.js:

(function() {

var app = angular.module('myApp', []);

 app.controller('myController', ['$scope', function($scope) {

    $scope.myText = "Let's go";

    $scope.arrayText = [
            'Hello',
            'world'
        ];

    $scope.addText = function() {
        $scope.arrayText.push(this.myText);
    }

 }]);

})();

index.html

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <div>
      <form ng-controller="myController" ng-submit="addText()">
           <input type="text" ng-model="myText" value="Lets go">
           <input type="submit" id="submit"/>
           <pre>list={{arrayText}}</pre>
      </form>
    </div>
  </body>
</html>

What does <![CDATA[]]> in XML mean?

CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be.

The key differences between CDATA and comments are:

This means given these four snippets of XML from one well-formed document:

<!ENTITY MyParamEntity "Has been expanded">

<!--
Within this comment I can use ]]>
and other reserved characters like <
&, ', and ", but %MyParamEntity; will not be expanded
(if I retrieve the text of this node it will contain
%MyParamEntity; and not "Has been expanded")
and I can't place two dashes next to each other.
-->

<![CDATA[
Within this Character Data block I can
use double dashes as much as I want (along with <, &, ', and ")
*and* %MyParamEntity; will be expanded to the text
"Has been expanded" ... however, I can't use
the CEND sequence. If I need to use CEND I must escape one of the
brackets or the greater-than sign using concatenated CDATA sections.
]]>

<description>An example of escaped CENDs</description>
<!-- This text contains a CEND ]]> -->
<!-- In this first case we put the ]] at the end of the first CDATA block
     and the > in the second CDATA block -->
<data><![CDATA[This text contains a CEND ]]]]><![CDATA[>]]></data>
<!-- In this second case we put a ] at the end of the first CDATA block
     and the ]> in the second CDATA block -->
<alternative><![CDATA[This text contains a CEND ]]]><![CDATA[]>]]></alternative>

How do I add options to a DropDownList using jQuery?

U can use direct

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

-> Here u can use direct string

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

How to convert string values from a dictionary, into int/float datatypes?

For python 3,

    for d in list:
        d.update((k, float(v)) for k, v in d.items())

Difference between "enqueue" and "dequeue"

A queue is a certain 2-sided data structure. You can add new elements on one side, and remove elements from the other side (as opposed to a stack that has only one side). Enqueue means to add an element, dequeue to remove an element. Please have a look here.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

How to select records without duplicate on just one field in SQL?

DISTINCT is the keyword
For me your query is correct

Just try to do this first

SELECT DISTINCT title,id FROM tbl_countries

Later on you can try with order by.

Android - Start service on boot

Looks very similar to mine but I use the full package name for the receiver:

<receiver android:name=".StartupIntentReceiver">

I have:

<receiver android:name="com.your.package.AutoStart"> 

Pyspark: display a spark data frame in a table format

Yes: call the toPandas method on your dataframe and you'll get an actual pandas dataframe !

How to change MySQL column definition?

This should do it:

ALTER TABLE test MODIFY locationExpert VARCHAR(120) 

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

How do I prompt a user for confirmation in bash script?

[[ -f ./${sname} ]] && read -p "File exists. Are you sure? " -n 1

[[ ! $REPLY =~ ^[Yy]$ ]] && exit 1

used this in a function to look for an existing file and prompt before overwriting.

How to enable external request in IIS Express?

I was unable to serve iis requests to other users in my local network, all I had to do (in addition to the above) was restart my BT Hub router.

jQuery UI Datepicker - Multiple Date Selections

Use this plugin http://multidatespickr.sourceforge.net

  • Select date ranges.
  • Pick multiple dates not in secuence.
  • Define a maximum number of pickable dates.
  • Define a range X days from where it is possible to select Y dates. Define unavailable dates

Get unique values from a list in python

Maintaining order:

# oneliners
# slow -> . --- 14.417 seconds ---
[x for i, x in enumerate(array) if x not in array[0:i]]

# fast -> . --- 0.0378 seconds ---
[x for i, x in enumerate(array) if array.index(x) == i]

# multiple lines
# fastest -> --- 0.012 seconds ---
uniq = []
[uniq.append(x) for x in array if x not in uniq]
uniq

Order doesn't matter:

# fastest-est -> --- 0.0035 seconds ---
list(set(array))

When do I need to use a semicolon vs a slash in Oracle SQL?

I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.

There is a huge difference in SQL*Plus between the meaning of a / and a ; because they work differently.

The ; ends a SQL statement, whereas the / executes whatever is in the current "buffer". So when you use a ; and a / the statement is actually executed twice.

You can easily see that using a / after running a statement:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> drop table foo;

Table dropped.

SQL> /
drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

In this case one actually notices the error.


But assuming there is a SQL script like this:

drop table foo;
/

And this is run from within SQL*Plus then this will be very confusing:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> @drop

Table dropped.

drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

The / is mainly required in order to run statements that have embedded ; like a CREATE PROCEDURE statement.

server error:405 - HTTP verb used to access this page is not allowed

Try renaming the default file. In my case, a recent move to IIS7.5 gave the 405 error. I changed index.aspx to default.aspx and it worked immediately for me.

Function to convert column number to letter?

There is a very simple way using Excel power: Use Range.Cells.Address property, this way:

strCol = Cells(1, lngRow).Address(xlRowRelative, xlColRelative)

This will return the address of the desired column on row 1. Take it of the 1:

strCol = Left(strCol, len(strCol) - 1)

Note that it so fast and powerful that you can return column addresses that even exists!

Substitute lngRow for the desired column number using Selection.Column property!

How does one use glide to download an image into a bitmap?

UPDATE

Now we need to use Custom Targets

SAMPLE CODE

    Glide.with(mContext)
            .asBitmap()
            .load("url")
            .into(new CustomTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {
                }
            });

How does one use glide to download an image into a bitmap?

The above all answer are correct but outdated

because in new version of Glide implementation 'com.github.bumptech.glide:glide:4.8.0'

You will find below error in code

  • The .asBitmap() is not available in glide:4.8.0

enter image description here

  • SimpleTarget<Bitmap> is deprecated

enter image description here

Here is solution

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;



public class MainActivity extends AppCompatActivity {

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);

        Glide.with(this)
                .load("")
                .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
                .into(new Target<Drawable>() {
                    @Override
                    public void onLoadStarted(@Nullable Drawable placeholder) {

                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {

                    }

                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {

                        Bitmap bitmap = drawableToBitmap(resource);
                        imageView.setImageBitmap(bitmap);
                        // now you can use bitmap as per your requirement
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }

                    @Override
                    public void getSize(@NonNull SizeReadyCallback cb) {

                    }

                    @Override
                    public void removeCallback(@NonNull SizeReadyCallback cb) {

                    }

                    @Override
                    public void setRequest(@Nullable Request request) {

                    }

                    @Nullable
                    @Override
                    public Request getRequest() {
                        return null;
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onStop() {

                    }

                    @Override
                    public void onDestroy() {

                    }
                });

    }

    public static Bitmap drawableToBitmap(Drawable drawable) {

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}

Name [jdbc/mydb] is not bound in this Context

For those who use Tomcat with Bitronix, this will fix the problem:

The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.

In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:

(if you already used them, make sure your references are correct):

  • btm.root
  • bitronix.tm.configuration

e.g.

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Now, restart your server and check the log.

How can I adjust DIV width to contents

I'd like to add to the other answers this pretty new solution:

If you don't want the element to become inline-block, you can do this:

.parent{
  width: min-content;
}

The support is increasing fast, so when edge decides to implement it, it will be really great: http://caniuse.com/#search=intrinsic

Setting the Vim background colors

supplement of windows

gvim version: 8.2

location of .gvimrc: %userprofile%/.gvimrc

" .gvimrc
colorscheme darkblue

Which color is allows me to choose?

Find your install directory and go to the directory of colors. in my case is: %PROGRAMFILES(X86)%\Vim\vim82\colors

blue.vim
darkblue.vim
slate.vim
...
README.txt

HTML Code for text checkbox '?'

U+F0FE ? is not a checkbox, it's a Private Use Area character that might render as anything. Whilst you can certainly try to include it in an HTML document, either directly in a UTF-8 document, or as a character reference like &#xF0FE;, you shouldn't expect it to render as a checkbox. It certainly doesn't on any of my browsers—although on some the ‘unknown character’ glyph is a square box that at least looks similar!

So where does U+F0FE come from? It is an unfortunate artifact of Word RTF export where the original document used a symbol font: one with no standard mapping to normal unicode characters; specifically, in this case, Wingdings. If you need to accept Word RTF from documents still authored with symbol fonts, then you will need to map those symbol characters to proper Unicode characters. Unfortunately that's tricky as it requires you to know the particular symbol font and have a map for it. See this post for background.

The standardised Unicode characters that best represent a checkbox are:

  • ?, U+2610 Ballot box
  • ?, U+2611 Ballot box with check

If you don't have a Unicode-safe editor you can naturally spell them as &#x2610; and &#x2611;.

(There is also U+2612 using an X, ?.)

How to define an optional field in protobuf 3

Another way is that you can use bitmask for each optional field. and set those bits if values are set and reset those bits which values are not set

enum bitsV {
    baz_present = 1; // 0x01
    baz1_present = 2; // 0x02

}
message Foo {
    uint32 bitMask;
    required int32 bar = 1;
    optional int32 baz = 2;
    optional int32 baz1 = 3;
}

On parsing check for value of bitMask.

if (bitMask & baz_present)
    baz is present

if (bitMask & baz1_present)
    baz1 is present

jQuery: selecting each td in a tr

Fully example to demonstrate how jQuery query all data in HTML table.

Assume there is a table like the following in your HTML code.

<table id="someTable">
  <thead>
    <tr>
      <td>title 0</td>
      <td>title 1</td>
      <td>title 2</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>row 0 td 0</td>
      <td>row 0 td 1</td>
      <td>row 0 td 2</td>
    </tr>
    <tr>
      <td>row 1 td 0</td>
      <td>row 1 td 1</td>
      <td>row 1 td 2</td>
    </tr>
    <tr>
      <td>row 2 td 0</td>
      <td>row 2 td 1</td>
      <td>row 2 td 2</td>
    </tr>
    <tr> ... </tr>
    <tr> ... </tr>
    ...
    <tr> ... </tr>
    <tr>
      <td>row n td 0</td>
      <td>row n td 1</td>
      <td>row n td 2</td>
    </tr>
  </tbody>
</table>

Then, The Answer, the code to print all row all column, should like this

$('#someTable tbody tr').each( (tr_idx,tr) => {
    $(tr).children('td').each( (td_idx, td) => {
        console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
    });                 
});

After running the code, the result will show

[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
...
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2

Summary.
In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.

From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.

Jackson: how to prevent field serialization

Aside from @JsonIgnore, there are a couple of other possibilities:

  • Use JSON Views to filter out fields conditionally (by default, not used for deserialization; in 2.0 will be available but you can use different view on serialization, deserialization)
  • @JsonIgnoreProperties on class may be useful

Casting objects in Java

In this example your superclass variable is telling the subclass object to implement the method of the superclass. This is the case of the java object type casting. Here the method() function is originally the method of the superclass but the superclass variable cannot access the other methods of the subclass object that are not present in the superclass.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

My answer is similar to @Ron-E, but I got a few more errors/corrections so I'm putting my steps below for Mac OSX on Mavericks and Python 2.7.6.

  1. Install Python mysql package (if you get a success message, then ignore the below steps)

    pip install mysql-python
    
  2. When I did the above, I got the error "EnvironmentError: mysql_config not found" enter image description here To fix this, I did the below in terminal:

    export PATH=$PATH:/usr/local/mysql/bin
    
  3. When I reran step 1, I get a new error "error: command 'cc' failed with exit status 1" enter image description here To fix this, I did the below in terminal:

     export CFLAGS=-Qunused-arguments
     export CPPFLAGS=-Qunused-arguments
    
  4. I reran step 1 and got the success message 'Successfully installed mysql-python'!

WPF ListView - detect when selected item is clicked

I couldn't get the accepted answer to work the way I wanted it to (see Farrukh's comment).

I came up with a slightly different solution which also feels more native because it selects the item on mouse button down and then you're able to react to it when the mouse button gets released:

XAML:

<ListView Name="MyListView" ItemsSource={Binding MyItems}>
<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        <EventSetter Event="PreviewMouseLeftButtonUp" Handler="ListViewItem_PreviewMouseLeftButtonUp" />
    </Style>
</ListView.ItemContainerStyle>

Code behind:

private void ListViewItem_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    MyListView.SelectedItems.Clear();

    ListViewItem item = sender as ListViewItem;
    if (item != null)
    {
        item.IsSelected = true;
        MyListView.SelectedItem = item;
    }
}

private void ListViewItem_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    ListViewItem item = sender as ListViewItem;
    if (item != null && item.IsSelected)
    {
        // do stuff
    }
}

DateTime.TryParse issue with dates of yyyy-dd-MM format

DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);

how to download file using AngularJS and calling MVC API?

I had the same problem. Solved it by using a javascript library called FileSaver

Just call

saveAs(file, 'filename');

Full http post request:

$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
  .success(function(data) {
            var file = new Blob([data], { type: 'application/pdf' });
            saveAs(file, 'filename.pdf');
        });

Android Studio: Plugin with id 'android-library' not found

Use mavenCentral() or jcenter() adding in the build.gradle file the script:

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'   
    }
}

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

My fix was to change the web.config file to correlate with my new server name for SQL Connection (IT Security had just done a netdom rename on my development box.

How can I set the default timezone in node.js?

As of Node 13, you can now repeatedly set process.env.TZ and it will be reflected in the timezone of new Date objects. I don't know if I'd use this in production code but it would definitely be useful in unit tests.

> process.env.TZ = 'Europe/London';
'Europe/London'
> (new Date().toString())
'Fri Mar 20 2020 09:39:59 GMT+0000 (Greenwich Mean Time)'

> process.env.TZ = 'Europe/Amsterdam';
'Europe/Amsterdam'
> (new Date().toString())
'Fri Mar 20 2020 10:40:07 GMT+0100 (Central European Standard Time)'

Insert auto increment primary key to existing table

How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..

This a table currently created - Number of Records found: 4 name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

This an end result sought (TABLE DESCRIPTION) -

Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

Instead of getting this -

Number of Records found: 5 id int(11) NO PRI name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

after trying..

$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";

how to get this? -

Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES

i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.

Single-threaded apartment - cannot instantiate ActiveX control

The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.

You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.

var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
  return(z)
}

How can I turn a List of Lists into a List in Java 8?

Method to convert a List<List> to List :

listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());

See this example:

public class Example {

    public static void main(String[] args) {
        List<List<String>> listOfLists = Collections.singletonList(Arrays.asList("a", "b", "v"));
        List<String> list = listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());

        System.out.println("listOfLists => " + listOfLists);
        System.out.println("list => " + list);
    }

}       

It prints:

listOfLists => [[a, b, c]]
list => [a, b, c]

In Python this can be done using List Comprehension.

list_of_lists = [['Roopa','Roopi','Tabu', 'Soudipta'],[180.0, 1231, 2112, 3112], [130], [158.2], [220.2]]

flatten = [val for sublist in list_of_lists for val in sublist]

print(flatten)
['Roopa', 'Roopi', 'Tabu', 'Soudipta', 180.0, 1231, 2112, 3112, 130, 158.2, 220.2]

How to copy marked text in notepad++

Try this instead:

First, fix the line ending problem: (Notepad++ doesn't allow multi-line regular expressions)

Search [Extended Mode]: \r\n> (Or your own system's line endings)

Replace: >

then

Search [Regex Mode]: <option[^>]+value="([^"]+)"[^>]*>.*

(if you want all occurences of value rather than just the options, simple remove the leading option)

Replace: \1

Explanation of the second regular expression:

<option[^>]+     Find a < followed by "option" followed by 
                 at least one character which is not a >

value="          Find the string value="

([^"]+)          Find one or more characters which are not a " and save them
                 to group \1

"[^>]*>.*        Find a " followed by zero or more non-'>' characters
                 followed by a > followed by zero or more characters.

Yes, it's parsing HTML with a regex -- these warnings apply -- check the output carefully.

How to get an enum value from a string value in Java?

Using Blah.valueOf(string) is best but you can use Enum.valueOf(Blah.class, string) as well.

How do I search for files in Visual Studio Code?

Also works in ubuntu with Ctrl+E

calling another method from the main method in java

This is a fundamental understanding in Java, but can be a little tricky to new programmers. Do a little research on the difference between a static and instance method. The basic difference is the instance method do() is only accessible to a instance of the class foo.

You must instantiate (create an instance of) the class, creating an object, that you use to call the instance method.

I have included your example with a couple comments and example.

public class SomeName {

//this is a static method and cannot call an instance method without a object
public static void main(String[] args){

    // can't do this from this static method, no object reference
    // someMethod();

    //create instance of object
    SomeName thisObj = new SomeName();
    //call instance method using object
    thisObj.someMethod();
}

//instance method
public void someMethod(){
    System.out.print("some message...");
}

}// end class SomeName

Javascript - Append HTML to container element without innerHTML

<div id="Result">
</div>

<script>
for(var i=0; i<=10; i++){
var data = "<b>vijay</b>";
 document.getElementById('Result').innerHTML += data;
}
</script>

assign the data for div with "+=" symbol you can append data including previous html data

How to print multiple lines of text with Python

As far as I know, there are three different ways.

Use \n in your print:

print("first line\nSecond line")

Use sep="\n" in print:

print("first line", "second line", sep="\n")

Use triple quotes and a multiline string:

print("""
Line1
Line2
""")

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

Export data from R to Excel

Here is a way to write data from a dataframe into an excel file by different IDs and into different tabs (sheets) by another ID associated to the first level id. Imagine you have a dataframe that has email_address as one column for a number of different users, but each email has a number of 'sub-ids' that have all the data.

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email_address = c(rep('[email protected]',3), rep('[email protected]', 3), rep('[email protected]', 3)))

So ids 1,2,3 would be associated with [email protected]. The following code splits the data by email and then puts 1,2,3 into different tabs. The important thing is to set append = True when writing the .xlsx file.


temp_dir <- tempdir()

for(i in unique(data$email_address)){
    
  data %>% 
    filter(email_address == i) %>% 
    arrange(id) -> subset_data
  
  for(j in unique(subset_data$id)){
    write.xlsx(subset_data %>% filter(id == j), 
      file = str_c(temp_dir,"/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0- 
       9._%+-]+"),'_', Sys.Date(), '.xlsx'), 
      sheetName = as.character(j), 
      append = TRUE)}
 
  }

The regex gets the name from the email address and puts it into the file-name.

Hope somebody finds this useful. I'm sure there's more elegant ways of doing this but it works.

Btw, here is a way to then send these individual files to the various email addresses in the data.frame. Code goes into second loop [j]

  send.mail(from = "[email protected]",
            to = i,
          subject = paste("Your report for", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"), 'on', Sys.Date()),
          body = "Your email body",
          authenticate = TRUE,
          smtp = list(host.name = "XXX", port = XXX,
                      user.name = Sys.getenv("XXX"), passwd = Sys.getenv("XXX")),
          attach.files = str_c(temp_dir, "/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"),'_', Sys.Date(), '.xlsx'))


google console error `OR-IEH-01`

It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.

Here’s how you can find the details of your transaction:

  1. Sign in to your Google Payments account at https://payments.google.com.

  2. On the left menu, select the “Subscriptions and services” page.

  3. On the “Other purchase activity” card, click View purchases.

  4. Click the “Google Play” registration transaction to see your payment method.

  5. You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.

To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

CSS file not refreshing in browser

Having this problem before I found out my own lazy solution (based on other people suggestions). It should be helpful if your <head> contents go through php interpreter.

To force downloading file every time you make changes to it, you could add file byte size of this file after question mark sign at the end.

<link rel="stylesheet" type="text/css" href="styles.css?<?=filesize('styles.css');?>">

EDIT: As suggested in comments, filemtime() is actually a better solution as long as your files have properly updated modify time (I, myself, have experienced such issues in the past, while working with remote files):

<link rel="stylesheet" type="text/css" href="styles.css?<?=filemtime('styles.css');?>">

How to change string into QString?

If compiled with STL compatibility, QString has a static method to convert a std::string to a QString:

std::string str = "abc";
QString qstr = QString::fromStdString(str);

Open Bootstrap Modal from code-behind

FYI,

I've seen this strange behavior before in jQuery widgets. Part of the key is to put the updatepanel inside the modal. This allows the DOM of the updatepanel to "stay with" the modal (however it works with bootstrap).

How to compare type of an object in Python?

You can always use the type(x) == type(y) trick, where y is something with known type.

# check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)

Often there are better ways of doing that, particularly with any recent python. But if you only want to remember one thing, you can remember that.

In this case, the better ways would be:

# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None

Note the last case: there is only one instance of NoneType in python, and that is None. You'll see NoneType a lot in exceptions (TypeError: 'NoneType' object is unsubscriptable -- happens to me all the time..) but you'll hardly ever need to refer to it in code.

Finally, as fengshaun points out, type checking in python is not always a good idea. It's more pythonic to just use the value as though it is the type you expect, and catch (or allow to propagate) exceptions that result from it.

Why is quicksort better than mergesort?

From the Wikipedia entry on Quicksort:

Quicksort also competes with mergesort, another recursive sort algorithm but with the benefit of worst-case T(nlogn) running time. Mergesort is a stable sort, unlike quicksort and heapsort, and can be easily adapted to operate on linked lists and very large lists stored on slow-to-access media such as disk storage or network attached storage. Although quicksort can be written to operate on linked lists, it will often suffer from poor pivot choices without random access. The main disadvantage of mergesort is that, when operating on arrays, it requires T(n) auxiliary space in the best case, whereas the variant of quicksort with in-place partitioning and tail recursion uses only T(logn) space. (Note that when operating on linked lists, mergesort only requires a small, constant amount of auxiliary storage.)

How to center images on a web page for all screen sizes

In your specific case, you can set the containing a element to be:

a {
    display: block;
    text-align: center;
}

JS Bin demo.

PHP: how can I get file creation date?

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';

if (file_exists($filename)) {

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

take(1) vs first()

It seems that in RxJS 5.2.0 the .first() operator has a bug,

Because of that bug .take(1) and .first() can behave quite different if you are using them with switchMap:

With take(1) you will get behavior as expected:

var x = Rx.Observable.interval(1000)
   .do( x=> console.log("One"))
   .take(1)
   .switchMap(x => Rx.Observable.interval(1000))
   .do( x=> console.log("Two"))
   .subscribe((x) => {})

// In the console you will see:
// One
// Two
// Two
// Two
// Two
// etc...

But with .first() you will get wrong behavior:

var x = Rx.Observable.interval(1000)
  .do( x=> console.log("One"))
  .first()
  .switchMap(x => Rx.Observable.interval(1000))
  .do( x=> console.log("Two"))
  .subscribe((x) => {})

// In console you will see:
// One
// One
// Two
// One
// Two
// One
// etc... 

Here's a link to codepen

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I faced the above mentioned problem when I forgot to pass a keyword argument name to url() function.

Code with error

 url(r"^testing/$", views.testing, "testing")

Code without error

url(r"^testing/$", views.testing, name="testing")

So finally I removed the above error in this way. It might be something different in your case. So check your url patterns in urls.py.

Camera access through browser

In iOS6, Apple supports this via the <input type="file"> tag. I couldn't find a useful link in Apple's developer documentation, but there's an example here.

It looks like overlays and more advanced functionality is not yet available, but this should work for a lot of use cases.

EDIT: The w3c has a spec that iOS6 Safari seems to implement a subset of. The capture attribute is notably missing.

Get div's offsetTop positions in React

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var n = ReactDOM.findDOMNode(this);
    console.log(n.offsetTop);
  }

You can just grab the offsetTop from the Node.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Android Writing Logs to text File

microlog4android works for me but the documentation is pretty poor. All they need to add is a this is a quick start tutorial.

Here is a quick tutorial I found.

  1. Add the following static variable in your main Activity:

    private static final Logger logger = LoggerFactory.getLogger();
    
  2. Add the following to your onCreate() method:

    PropertyConfigurator.getConfigurator(this).configure();
    
  3. Create a file named microlog.properties and store it in assets directory

  4. Edit the microlog.properties file as follows:

    microlog.level=DEBUG
    microlog.appender=LogCatAppender;FileAppender
    microlog.formatter=PatternFormatter
    microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T
    
  5. Add logging statements like this:

    logger.debug("M4A");
    

For each class you create a logger object as specified in 1)

6.You may be add the following permission:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Here is the source for tutorial

How to clear a chart from a canvas so that hover events cannot be triggered?

First put chart in some variable then history it next time before init

#Check if myChart object exist then distort it

    if($scope.myChart) {
      $scope.myChart.destroy();
    }

    $scope.myChart  = new Chart(targetCanvas

Prevent flicker on webkit-transition of webkit-transform

Add this css property to the element being flickered:

-webkit-transform-style: preserve-3d;

(And a big thanks to Nathan Hoad: http://nathanhoad.net/how-to-stop-css-animation-flicker-in-webkit)

How to undo a git merge with conflicts

Assuming you are using the latest git,

git merge --abort

Graphviz's executables are not found (Python 3.4)

I had faced same problem while trying to create decision tree through pydotplus and graphviz. And used the path variable method to resolve this issue.

Below are the exact steps I used:

  1. Although I already had graphviz through conda install command , I re-downloaded the latest package from below path. https://graphviz.gitlab.io/_pages/Download/Download_windows.html Downloaded : graphviz-2.38.zip (Stable Release)

  2. Copied the extracted folder under following path on C: Drive. C:\Program Files (x86)\

  3. Modified the system path variable and added following path to it. Path Variable : Control Panel > System and Security > System > Advance system Setting > Environment Variable > Path C:\Program Files (x86)\graphviz-2.38\release\bin;

  4. After adding above path to environment variable , restarted the system.

  5. It worked fine , and I was able to create Decision tree into png.

    enter image description here

How to delete rows from a pandas DataFrame based on a conditional expression

You can assign the DataFrame to a filtered version of itself:

df = df[df.score > 50]

This is faster than drop:

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to get tf.exe (TFS command line client)?

You need to install Team Explorer, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.

2012 version http://www.microsoft.com/en-gb/download/details.aspx?id=30656

2013 version http://www.microsoft.com/en-us/download/details.aspx?id=40776

2019 version https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=TeamExplorer&rel=16

You also might be interested in the TFS power tools. They add some extra command line features (using tfpt.exe) and also add some extra IDE features.

How do I activate C++ 11 in CMake?

The CMake command target_compile_features() is used to specify the required C++ feature cxx_range_for. CMake will then induce the C++ standard to be used.

cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(foobar CXX)
add_executable(foobar main.cc)
target_compile_features(foobar PRIVATE cxx_range_for)

There is no need to use add_definitions(-std=c++11) or to modify the CMake variable CMAKE_CXX_FLAGS, because CMake will make sure the C++ compiler is invoked with the appropriate command line flags.

Maybe your C++ program uses other C++ features than cxx_range_for. The CMake global property CMAKE_CXX_KNOWN_FEATURES lists the C++ features you can choose from.

Instead of using target_compile_features() you can also specify the C++ standard explicitly by setting the CMake properties CXX_STANDARD and CXX_STANDARD_REQUIRED for your CMake target.

See also my more detailed answer.

Is it possible to declare a variable in Gradle usable in Java?

Here are two ways to pass value from Gradle to use in Java;

Generate Java Constants

android {
    buildTypes {
        debug {
            buildConfigField "int", "FOO", "42"
            buildConfigField "String", "FOO_STRING", "\"foo\""
            buildConfigField "boolean", "LOG", "true"
        }

        release {
            buildConfigField "int", "FOO", "52"
            buildConfigField "String", "FOO_STRING", "\"bar\""
            buildConfigField "boolean", "LOG", "false"
        }
    }
}

You can access them with BuildConfig.FOO

Generate Android resources

android {
    buildTypes {
        debug{
            resValue "string", "app_name", "My App Name Debug"
        }
        release {
            resValue "string", "app_name", "My App Name"
        }
    }
}

You can access them in the usual way with @string/app_name or R.string.app_name

how to add picasso library in android studio

Add the Picasso library in Dependency

dependencies {
       ...
       implementation 'com.squareup.picasso:picasso:2.71828'
       ...
    }

Sync The Project Create one imageview in Layout

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

Add the Internet permission in Manifest file

<uses-permission android:name="android.permission.INTERNET" />

//Initialize ImageView

ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Loading image from below url into imageView

Picasso.get()
   .load("YOUR IMAGE URL HERE")
   .into(imageView);

curl.h no such file or directory

sudo apt-get install curl-devel

sudo apt-get install libcurl-dev

(will install the default alternative)

OR

sudo apt-get install libcurl4-openssl-dev

(the OpenSSL variant)

OR

sudo apt-get install libcurl4-gnutls-dev

(the gnutls variant)

How to make a Generic Type Cast function

While probably not as clean looking as the IConvertible approach, you could always use the straightforward checking typeof(T) to return a T:

public static T ReturnType<T>(string stringValue)
{
    if (typeof(T) == typeof(int))
        return (T)(object)1;
    else if (typeof(T) == typeof(FooBar))
        return (T)(object)new FooBar(stringValue);
    else
        return default(T);
}

public class FooBar
{
    public FooBar(string something)
    {}
}

Insert data into table with result from another select query

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`;

How to Set AllowOverride all

Goto your_severpath/apache_ver/conf/ Open the file httpd.conf in Notepad.

Find this line:

#LoadModule vhost_alias_module modules/mod_vhost_alias.so

Remove the hash symbol:

LoadModule vhost_alias_module modules/mod_vhost_alias.so

Then goto <Directory />

and change to:

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

Then restart your local server.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

For those interested, this is code for creating SHA-256 hash using sjcl:

import sjcl from 'sjcl'

const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

java.lang.IllegalArgumentException: contains a path separator

I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!

 public class MyClass {    

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");  
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}

Screenshot sizes for publishing android app on Google Play

When I publish apps I use the following screenshot sizes:

Phone: 1080 x 1920 I prepare 8 images with title, some fancy background and a screenshot inside a smartphone mockup. So it's more than a simple screenshot. It gives some nice branding and helps you to stand out from other apps out there.

Tablet 7": 1200 x 1920 - I do actually a couple of raw screenshots of 7" emulator so that the user could know how the layout will appear on his device. No fancy design with titles etc.

Tablet 10": 1800 x 2560 - same thing here, just a couple of raw screenshots.

all in .png format. Hope this helps.

How do I get the position selected in a RecyclerView?

To complement @tyczj answer:

Generic Adapter Pseido code:

public abstract class GenericRecycleAdapter<T, K extends RecyclerView.ViewHolder> extends RecyclerView.Adapter{ 

private List<T> mList;
//default implementation code 

public abstract int getLayout();

@Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(getLayout(), parent, false);
        return getCustomHolder(v);
    }

    public Holders.TextImageHolder getCustomHolder(View v) {
        return new Holders.TextImageHolder(v){
            @Override
            public void onClick(View v) {
                onItem(mList.get(this.getAdapterPosition()));
            }
        };
    }

abstract void onItem(T t);

 @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    onSet(mList.get(position), (K) holder);

}

public abstract void onSet(T item, K holder);

}

ViewHolder:

public class Holders  {

    public static class TextImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView text;

        public TextImageHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.text);
            text.setOnClickListener(this);


        }

        @Override
        public void onClick(View v) {

        }
    }


}

Adapter usage:

public class CategoriesAdapter extends GenericRecycleAdapter<Category, Holders.TextImageHolder> {


    public CategoriesAdapter(List<Category> list, Context context) {
        super(list, context);
    }

    @Override
    void onItem(Category category) {

    }


    @Override
    public int getLayout() {
        return R.layout.categories_row;
    }

    @Override
    public void onSet(Category item, Holders.TextImageHolder holder) {

    }



}

How to use SortedMap interface in Java?

I would use TreeMap, which implements SortedMap. It is designed exactly for that.

Example:

Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

How to redirect a URL path in IIS?

Taken from Microsoft Technet.

Redirecting Web Sites in IIS 6.0 (IIS 6.0)


When a browser requests a page or program on your Web site, the Web server locates the page identified by the URL and returns it to the browser. When you move a page on your Web site, you can't always correct all of the links that refer to the old URL of the page. To make sure that browsers can find the page at the new URL, you can instruct the Web server to redirect the browser to the new URL.

You can redirect requests for files in one directory to a different directory, to a different Web site, or to another file in a different directory. When the browser requests the file at the original URL, the Web server instructs the browser to request the page by using the new URL.

Important

You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".

Procedures

To redirect requests to another Web site or directory


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination directory or Web site. For example, to redirect all requests for files in the Catalog directory to the NewCatalog directory, type /NewCatalog.

To redirect all requests to a single file


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination file.

  5. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

    You can use wildcards and redirect variables in the destination URL to precisely control how the original URL is translated into the destination URL.

    You can also use the redirect method to redirect all requests for files in a particular directory to a program. Generally, you should pass any parameters from the original URL to the program, which you can do by using redirect variables.

    To redirect requests to a program


  6. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  7. Click the Home Directory, Virtual Directory, or Directory tab.

  8. Under The content for this source should come from, click A redirection to a URL.

    In the Redirect to box, type the URL of the program, including any redirect variables needed to pass parameters to the program. For example, to redirect all requests for scripts in a Scripts directory to a logging program that records the requested URL and any parameters passed with the URL, type /Scripts/Logger.exe?URL=$V+PARAMS=$P. $V and $P are redirect variables.

  9. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

What’s the best way to check if a file exists in C++? (cross platform)

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

How to use wait and notify in Java without IllegalMonitorStateException?

You can only call notify on objects where you own their monitor. So you need something like

synchronized(threadObject)
{
   threadObject.notify();
}

Error: Segmentation fault (core dumped)

It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga

faulthandler.enable()
// bad code goes here

or

$ python3 -q -X faulthandler
>>> /// bad cod goes here

How do I import an SQL file using the command line in MySQL?

I thought it could be useful for those who are using Mac OS X:

/Applications/xampp/xamppfiles/bin/mysql -u root -p database < database.sql

Replace xampp with mamp or other web servers.

How to show PIL Image in ipython notebook

Based on other answers and my tries, best experience would be first installing, pillow and scipy, then using the following starting code on your jupyter notebook:

%matplotlib inline
from matplotlib.pyplot import imshow
from scipy.misc import imread

imshow(imread('image.jpg', 1))

Tick symbol in HTML/XHTML

You can add a little white one with a Base64 Encoded GIF (online generator here):

url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==")

With Chrome, for instance, I use it to style the checkbox control:

INPUT[type=checkbox]:focus
{
outline:1px solid rgba(0,0,0,0.2);
}

INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
-webkit-appearance: button;
width: 17px;
height: 17px;
margin-top: 1px;
cursor:pointer;
}

INPUT[type=checkbox]:checked
{
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}

If you just wanted it in an IMG tag, you would do the checkmark/tickmark as:

<img alt="" src="data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==" width="11" height="10">

Submit form using <a> tag

Try this:

Suppose HTML like this :

   <form id="myform" name="myform" method="POST" action="process_edit_questionnaire.php?project=<?php echo $project_id; ?>">
      <div id="question_block">
            testing form
        </div>
     <a href="javascript: submit();">Submit</a>
        </form>

JS :

   <script type='text/javascript'>
     function submit()
      {
         document.forms["myform"].submit();
      }
   </script>

you can check it out here : http://jsfiddle.net/Zm426/7/

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

How can I create a simple index.html file which lists all files/directories?

If you have node then you can use fs like in this answer to get all the files:

const { resolve } = require('path'),
  { readdir } = require('fs').promises;

async function getFiles(dir) {
  const dirents = await readdir(dir, { withFileTypes: true });
  const files = await Promise.all(dirents.map((dirent) => {
    const res = resolve(dir, dirent.name);
    return dirent.isDirectory() ? getFiles(res) : res;
  }));
  return Array.prototype.concat(...files);
}

And you might use that like this:

const directory = "./Documents/";
  
getFiles(directory).then(results => {
  const html = `<ul>` +
  results.map(fileOrDirectory => `<li>${fileOrDirectory}</li>`).join('\n') +
  `</ul>`;

  process.stdout.write(html);
  // or you could use something like fs.writeFile to write the file directly
});

You could call it at the command-line with something like this:

$ node thatScript.js > index.html

Can I do Model->where('id', ARRAY) multiple where conditions?

You can use whereIn which accepts an array as second paramter.

DB:table('table')
   ->whereIn('column', [value, value, value])
   ->get()

You can chain where multiple times.

DB:table('table')->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->get();

This will use AND operator. if you need OR you can use orWhere method.

For advanced where statements

DB::table('table')
    ->where('column', 'operator', 'value')
    ->orWhere(function($query)
    {
        $query->where('column', 'operator', 'value')
            ->where('column', 'operator', 'value');
    })
    ->get();

Official way to ask jQuery wait for all images to load before executing something

For those who want to be notified of download completion of a single image that gets requested after $(window).load fires, you can use the image element's load event.

e.g.:

// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");

// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");

// wait for the image to load 
$imgElement.load(function() {
    alert("The image has loaded; width: " + $imgElement.width() + "px");
});

How to jump back to NERDTree from file in tab?

Ctrl+ww cycle though all windows

Ctrl+wh takes you left a window

Ctrl+wj takes you down a window

Ctrl+wk takes you up a window

Ctrl+wl takes you right a window

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

Android - styling seek bar

For those who use Data Binding:

  1. Add the following static method to any class

    @BindingAdapter("app:thumbTintCompat")
    public static void setThumbTint(SeekBar seekBar, @ColorInt int color) {
        seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }
    
  2. Add app:thumbTintCompat attribute to your SeekBar

    <SeekBar
           android:id="@+id/seek_bar"
           style="@style/Widget.AppCompat.SeekBar"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           app:thumbTintCompat="@{@android:color/white}"
    />
    

That's it. Now you can use app:thumbTintCompat with any SeekBar. The progress tint can be configured in the same way.

Note: this method is also compatble with pre-lollipop devices.

Closing Twitter Bootstrap Modal From Angular Controller

You can add data-dismiss="modal" to your button attributes which call angularjs funtion.

Such as;

<button type="button" class="btn btn-default" data-dismiss="modal">Send Form</button>

Displaying a vector of strings in C++

You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.

#include <iostream>
#include <vector>
#include <string.h>

int main ()
{
  std::vector<std::string> myvector ;
  std::vector<std::string>::iterator it;

   it = myvector.begin();
  std::string myarray [] = { "Hi","hello","wassup" };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
    std::cout << '\n';

  return 0;
}

How to use Checkbox inside Select Option

Only add class create div and add class form-control. iam use JSP,boostrap4. Ignore c:foreach.

<div class="multi-select form-control" style="height:107.292px;">
        <div class="checkbox" id="checkbox-expedientes">
            <c:forEach var="item" items="${postulantes}">
                <label class="form-check-label">
                    <input id="options" class="postulantes" type="checkbox" value="1">Option 1</label>
            </c:forEach>
        </div>
    </div>

HTML5 LocalStorage: Checking if a key exists

This method worked for me:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}