Programs & Examples On #Latency

This tag implies latency is a significant consideration

How do I simulate a low bandwidth, high latency environment?

If you're on linux, I find the Traffic Control program to be a great help for this sort of thing.

What's the simplest way of detecting keyboard input in a script from the terminal?

Edit:

I've thought about this problem a lot, and there are a few different behaviors one could want. I've been implementing most of them for Unix and Windows, and will post them here once they are done.

Synchronous/Blocking key capture:

  1. A simple input or raw_input, a blocking function which returns text typed by a user once they press a newline.
  2. A simple blocking function that waits for the user to press a single key, then returns that key

Asynchronous key capture:

  1. A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)
  2. A callback that is called with the typed text after the user presses enter (a less realtime keylogger)
  3. A callback that is called with the keys pressed when a program is running (say, in a for loop or while loop)

Polling:

  1. The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).

  2. The same as 1, except that poll only returns something once the user presses a newline.

Robots:

These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user

Implementations

Synchronous/Blocking key capture:

A simple input or raw_input, a blocking function which returns text typed by a user once they press a newline.

typedString = raw_input()

A simple blocking function that waits for the user to press a single key, then returns that key

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            try:
                self.impl = _GetchMacCarbon()
            except(AttributeError, ImportError):
                self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

class _GetchMacCarbon:
    """
    A function which returns the current ASCII key that is down;
    if no ASCII key is down, the null string is returned.  The
    page http://www.mactech.com/macintosh-c/chap02-1.html was
    very helpful in figuring out how to do this.
    """
    def __init__(self):
        import Carbon
        Carbon.Evt #see if it has this (in Unix, it doesn't)

    def __call__(self):
        import Carbon
        if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
            return ''
        else:
            #
            # The event contains the following info:
            # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            #
            # The message (msg) contains the ASCII char which is
            # extracted with the 0x000000FF charCodeMask; this
            # number is converted to an ASCII character with chr() and
            # returned
            #
            (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            return chr(msg & 0x000000FF)


def getKey():
    inkey = _Getch()
    import sys
    for i in xrange(sys.maxint):
        k=inkey()
        if k<>'':break

    return k

Asynchronous key capture:

A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)

A callback that is called with the typed text after the user presses enter (a less realtime keylogger)

Windows:

This uses the windows Robot given below, naming the script keyPress.py

# Some if this is from http://nullege.com/codes/show/src@e@i@einstein-HEAD@Python25Einstein@[email protected]/380/win32api.GetStdHandle
# and
# http://nullege.com/codes/show/src@v@i@VistA-HEAD@Python@[email protected]/901/win32console.GetStdHandle.PeekConsoleInput

from ctypes import *
import time
import threading

from win32api import STD_INPUT_HANDLE, STD_OUTPUT_HANDLE

from win32console import GetStdHandle, KEY_EVENT, ENABLE_WINDOW_INPUT, ENABLE_MOUSE_INPUT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT

import keyPress


class CaptureLines():
    def __init__(self):
        self.stopLock = threading.Lock()

        self.isCapturingInputLines = False

        self.inputLinesHookCallback = CFUNCTYPE(c_int)(self.inputLinesHook)
        self.pyosInputHookPointer = c_void_p.in_dll(pythonapi, "PyOS_InputHook")
        self.originalPyOsInputHookPointerValue = self.pyosInputHookPointer.value

        self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

    def inputLinesHook(self):

        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
        inputChars = self.readHandle.ReadConsole(10000000)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT)

        if inputChars == "\r\n":
            keyPress.KeyPress("\n")
            return 0

        inputChars = inputChars[:-2]

        inputChars += "\n"

        for c in inputChars:
            keyPress.KeyPress(c)

        self.inputCallback(inputChars)

        return 0


    def startCapture(self, inputCallback):
        self.stopLock.acquire()

        try:
            if self.isCapturingInputLines:
                raise Exception("Already capturing keystrokes")

            self.isCapturingInputLines = True
            self.inputCallback = inputCallback

            self.pyosInputHookPointer.value = cast(self.inputLinesHookCallback, c_void_p).value
        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

    def stopCapture(self):
        self.stopLock.acquire()

        try:
            if not self.isCapturingInputLines:
                raise Exception("Keystrokes already aren't being captured")

            self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

            self.isCapturingInputLines = False
            self.pyosInputHookPointer.value = self.originalPyOsInputHookPointerValue

        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

A callback that is called with the keys pressed when a program is running (say, in a for loop or while loop)

Windows:

import threading
from win32api import STD_INPUT_HANDLE
from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT


class KeyAsyncReader():
    def __init__(self):
        self.stopLock = threading.Lock()
        self.stopped = True
        self.capturedChars = ""

        self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)



    def startReading(self, readCallback):
        self.stopLock.acquire()

        try:
            if not self.stopped:
                raise Exception("Capture is already going")

            self.stopped = False
            self.readCallback = readCallback

            backgroundCaptureThread = threading.Thread(target=self.backgroundThreadReading)
            backgroundCaptureThread.daemon = True
            backgroundCaptureThread.start()
        except:
            self.stopLock.release()
            raise

        self.stopLock.release()


    def backgroundThreadReading(self):
        curEventLength = 0
        curKeysLength = 0
        while True:
            eventsPeek = self.readHandle.PeekConsoleInput(10000)

            self.stopLock.acquire()
            if self.stopped:
                self.stopLock.release()
                return
            self.stopLock.release()


            if len(eventsPeek) == 0:
                continue

            if not len(eventsPeek) == curEventLength:
                if self.getCharsFromEvents(eventsPeek[curEventLength:]):
                    self.stopLock.acquire()
                    self.stopped = True
                    self.stopLock.release()
                    break

                curEventLength = len(eventsPeek)



    def getCharsFromEvents(self, eventsPeek):
        callbackReturnedTrue = False
        for curEvent in eventsPeek:
            if curEvent.EventType == KEY_EVENT:
                    if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
                        pass
                    else:
                        curChar = str(curEvent.Char)
                        if self.readCallback(curChar) == True:
                            callbackReturnedTrue = True


        return callbackReturnedTrue

    def stopReading(self):
        self.stopLock.acquire()
        self.stopped = True
        self.stopLock.release()

Polling:

The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).

Windows and OS X (and maybe Linux):

global isWindows

isWindows = False
try:
    from win32api import STD_INPUT_HANDLE
    from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT
    isWindows = True
except ImportError as e:
    import sys
    import select
    import termios


class KeyPoller():
    def __enter__(self):
        global isWindows
        if isWindows:
            self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
            self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

            self.curEventLength = 0
            self.curKeysLength = 0

            self.capturedChars = []
        else:
            # Save the terminal settings
            self.fd = sys.stdin.fileno()
            self.new_term = termios.tcgetattr(self.fd)
            self.old_term = termios.tcgetattr(self.fd)

            # New terminal setting unbuffered
            self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)

        return self

    def __exit__(self, type, value, traceback):
        if isWindows:
            pass
        else:
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)

    def poll(self):
        if isWindows:
            if not len(self.capturedChars) == 0:
                return self.capturedChars.pop(0)

            eventsPeek = self.readHandle.PeekConsoleInput(10000)

            if len(eventsPeek) == 0:
                return None

            if not len(eventsPeek) == self.curEventLength:
                for curEvent in eventsPeek[self.curEventLength:]:
                    if curEvent.EventType == KEY_EVENT:
                        if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
                            pass
                        else:
                            curChar = str(curEvent.Char)
                            self.capturedChars.append(curChar)
                self.curEventLength = len(eventsPeek)

            if not len(self.capturedChars) == 0:
                return self.capturedChars.pop(0)
            else:
                return None
        else:
            dr,dw,de = select.select([sys.stdin], [], [], 0)
            if not dr == []:
                return sys.stdin.read(1)
            return None

Simple use case:

with KeyPoller() as keyPoller:
    while True:
        c = keyPoller.poll()
        if not c is None:
            if c == "c":
                break
            print c

The same as above, except that poll only returns something once the user presses a newline.

Robots:

These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user

Windows:

# Modified from http://stackoverflow.com/a/13615802/2924421

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# C struct definitions
wintypes.ULONG_PTR = wintypes.WPARAM

SendInput = ctypes.windll.user32.SendInput

PUL = ctypes.POINTER(ctypes.c_ulong)

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

def KeyDown(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyUp(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    extra = ctypes.c_ulong(0)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag | KEYEVENTF_KEYUP, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyPress(unicodeKey):
    time.sleep(0.0001)
    KeyDown(unicodeKey)
    time.sleep(0.0001)
    KeyUp(unicodeKey)
    time.sleep(0.0001)


def GetKeyCode(unicodeKey):
    k = unicodeKey
    curKeyCode = 0
    if k == "up": curKeyCode = 0x26
    elif k == "down": curKeyCode = 0x28
    elif k == "left": curKeyCode = 0x25
    elif k == "right": curKeyCode = 0x27
    elif k == "home": curKeyCode = 0x24
    elif k == "end": curKeyCode = 0x23
    elif k == "insert": curKeyCode = 0x2D
    elif k == "pgup": curKeyCode = 0x21
    elif k == "pgdn": curKeyCode = 0x22
    elif k == "delete": curKeyCode = 0x2E
    elif k == "\n": curKeyCode = 0x0D

    if curKeyCode == 0:
        return 0, int(unicodeKey.encode("hex"), 16), KEYEVENTF_UNICODE
    else:
        return curKeyCode, 0, 0

OS X:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent


def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)



# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
    else:
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'
}


keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E
}

How do I implement interfaces in python?

There are third-party implementations of interfaces for Python (most popular is Zope's, also used in Twisted), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Class" (ABC), which combines an interface with the possibility of having some implementation aspects there too. ABCs are particularly well supported in Python 2.6 and later, see the PEP, but even in earlier versions of Python they're normally seen as "the way to go" -- just define a class some of whose methods raise NotImplementedError so that subclasses will be on notice that they'd better override those methods!-)

make sounds (beep) with c++

The ASCII bell character might be what you are looking for. Number 7 in this table.

TextView Marquee not working

To have your own scroll speed and flexibility to customize marquee properties, use the following:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:fadingEdge="horizontal"
    android:lines="1"
    android:id="@+id/myTextView"
    android:padding="4dp"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:text="Simple application that shows how to use marquee, with a long text" />

Within your activity:

private void setTranslation() {
        TranslateAnimation tanim = new TranslateAnimation(
                TranslateAnimation.ABSOLUTE, 1.0f * screenWidth,
                TranslateAnimation.ABSOLUTE, -1.0f * screenWidth,
                TranslateAnimation.ABSOLUTE, 0.0f,
                TranslateAnimation.ABSOLUTE, 0.0f);
        tanim.setDuration(1000);
        tanim.setInterpolator(new LinearInterpolator());
        tanim.setRepeatCount(Animation.INFINITE);
        tanim.setRepeatMode(Animation.ABSOLUTE);

        textView.startAnimation(tanim);
    } 

Clicking HTML 5 Video element to play, pause video, breaks play button

Not to bring up an old post but I landed on this question in my search for the same solution. I ended up coming up with something of my own. Figured I'd contribute.

HTML:

<video class="video"><source src=""></video>

JAVASCRIPT: "JQUERY"

$('.video').click(function(){this.paused?this.play():this.pause();});

Ansible: copy a directory content to another directory

the ansible doc is quite clear https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html for parameter src it says the following:

Local path to a file to copy to the remote server.
This can be absolute or relative.
If path is a directory, it is copied recursively. In this case, if path ends with "/", 
only inside contents of that directory are copied to destination. Otherwise, if it 
does not end with "/", the directory itself with all contents is copied. This behavior 
is similar to the rsync command line tool.

So what you need is skip the / at the end of your src path.

- name: copy html file
  copy: src=/home/vagrant/dist dest=/usr/share/nginx/html/

from jquery $.ajax to angular $http

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

MySQL Creating tables with Foreign Keys giving errno: 150

execute below line before creating table : SET FOREIGN_KEY_CHECKS = 0;

FOREIGN_KEY_CHECKS option specifies whether or not to check foreign key constraints for InnoDB tables.

-- Specify to check foreign key constraints (this is the default)

SET FOREIGN_KEY_CHECKS = 1;

 

-- Do not check foreign key constraints

SET FOREIGN_KEY_CHECKS = 0;

When to Use : Temporarily disabling referential constraints (set FOREIGN_KEY_CHECKS to 0) is useful when you need to re-create the tables and load data in any parent-child order

What is the difference between JSF, Servlet and JSP?

The basic difference between Servlets and JSP is that in Servlets we write java code and in that we embed HTML code and there is just reverse case with JSP . In JSP we write HTML code and in that we embed java code using tags provided by JSP.

Button text toggle in jquery

I preffer the following way, it can be used by any button.

<button class='pushme' data-default-text="PUSH ME" data-new-text="DON'T PUSH ME">PUSH ME</button>

$(".pushme").click(function () {
    var $element = $(this);
    $element.text(function(i, text) {
        return text == $element.data('default-text') ? $element.data('new-text')
                                                     : $element.data('default-text');
    });
});

demo

How to parse/format dates with LocalDateTime? (Java 8)

All the answers are good. The java8+ have these patterns for parsing and formatting timezone: V, z, O, X, x, Z.

Here's they are, for parsing, according to rules from the documentation :

   Symbol  Meaning                     Presentation      Examples
   ------  -------                     ------------      -------
   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

But how about formatting? Here's a sample for a date (assuming ZonedDateTime) that show these patters behavior for different formatting patters:

// The helper function:
static void printInPattern(ZonedDateTime dt, String pattern) {
    System.out.println(pattern + ": " + dt.format(DateTimeFormatter.ofPattern(pattern)));
}        

// The date:
String strDate = "2020-11-03 16:40:44 America/Los_Angeles";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzzz");
ZonedDateTime dt = ZonedDateTime.parse(strDate, format);
// 2020-11-03T16:40:44-08:00[America/Los_Angeles]

// Rules:
// printInPattern(dt, "V");     // exception!
printInPattern(dt, "VV");       // America/Los_Angeles
// printInPattern(dt, "VVV");   // exception!
// printInPattern(dt, "VVVV");  // exception!
printInPattern(dt, "z");        // PST
printInPattern(dt, "zz");       // PST
printInPattern(dt, "zzz");      // PST
printInPattern(dt, "zzzz");     // Pacific Standard Time
printInPattern(dt, "O");        // GMT-8
// printInPattern(dt, "OO");    // exception!
// printInPattern(dt, "OO0");   // exception!
printInPattern(dt, "OOOO");     // GMT-08:00
printInPattern(dt, "X");        // -08
printInPattern(dt, "XX");       // -0800
printInPattern(dt, "XXX");      // -08:00
printInPattern(dt, "XXXX");     // -0800
printInPattern(dt, "XXXXX");    // -08:00
printInPattern(dt, "x");        // -08
printInPattern(dt, "xx");       // -0800
printInPattern(dt, "xxx");      // -08:00
printInPattern(dt, "xxxx");     // -0800
printInPattern(dt, "xxxxx");    // -08:00
printInPattern(dt, "Z");        // -0800
printInPattern(dt, "ZZ");       // -0800
printInPattern(dt, "ZZZ");      // -0800
printInPattern(dt, "ZZZZ");     // GMT-08:00
printInPattern(dt, "ZZZZZ");    // -08:00

In the case of positive offset the + sign character is used everywhere(where there is - now) and never omitted.

This well works for new java.time types. If you're about to use these for java.util.Date or java.util.Calendar - not all going to work as those types are broken(and so marked as deprecated, please don't use them)

How to validate a date?

Hi Please find the answer below.this is done by validating the date newly created

var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
        || d.getMonth() != (month - 1)
        || d.getDate() != date) {
    alert("invalid date");
    return false;
}

java.lang.ClassCastException

A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {
  Fruit myFruit = (Fruit)myApple;
}

Get the current time in C

#include <stdio.h>
#include <time.h>

void main()
{
    time_t t;
    time(&t);
    clrscr();

    printf("Today's date and time : %s",ctime(&t));
    getch();
}

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

Use jQuery to navigate away from page

window.location = myUrl;

Anyway, this is not jQuery: it's plain javascript

Android, Java: HTTP POST Request

I'd rather recommend you to use Volley to make GET, PUT, POST... requests.

First, add dependency in your gradle file.

compile 'com.he5ed.lib:volley:android-cts-5.1_r4'

Now, use this code snippet to make requests.

RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

        StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("Response", response);
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.d("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String>();
                //add your parameters here as key-value pairs
                params.put("username", username);
                params.put("password", password);

                return params;
            }
        };
        queue.add(postRequest);

Install a Nuget package in Visual Studio Code

You can do it easily using "vscode-nuget-package-manager". Go to the marketplace and install this. After That

1) Press Ctrl+P or Ctrl+Shift+P (and skip 2)

2) Type ">"

3) Then select "Nuget Package Manager:Add Package"

4) Enter package name Ex: Dapper

5) select package name and version

6) Done.

How can you represent inheritance in a database?

I lean towards method #1 (a unified Section table), for the sake of efficiently retrieving entire policies with all their sections (which I assume your system will be doing a lot).

Further, I don't know what version of SQL Server you're using, but in 2008+ Sparse Columns help optimize performance in situations where many of the values in a column will be NULL.

Ultimately, you'll have to decide just how "similar" the policy sections are. Unless they differ substantially, I think a more-normalized solution might be more trouble than it's worth... but only you can make that call. :)

Alternate table row color using CSS?

<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>

Update multiple rows in same query using PostgreSQL

Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :

drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;

select * from results_dummy;

-- THE update of multiple rows with/by different values
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;

select * from results_dummy;

-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;

javax.servlet.ServletException cannot be resolved to a type in spring web app

import javax.servlet

STEP 1

Go to properties of your project ( with Alt+Enter or righ-click )

STEP 2

check on Apache Tomcat v7.0 under Targeted Runtime and it works.

source: https://stackoverflow.com/a/9287149

Django download a file

I use this method:

{% if quote.myfile %}
    <div class="">
        <a role="button" 
            href="{{ quote.myfile.url }}"
            download="{{ quote.myfile.url }}"
            class="btn btn-light text-dark ml-0">
            Download attachment
        </a>
    </div>
{% endif %}

How to pass multiple checkboxes using jQuery ajax post

Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.

var data = { 'venue[]' : []};

$("input:checked").each(function() {
   data['venue[]'].push($(this).val());
});

In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)

Run CSS3 animation only once (at page loading)

The following code without "iteration-count: 1" was resulting in all line items pulsing after entering, until the last item loaded, even though 'pulse was not being used.

<li class="animated slideInLeft delay-1s animation-iteration-count: 1"><i class="fa fa-credit-card" aria-hidden="true"></i> 1111</li>


<li class="animated slideInRight delay-1-5s animation-iteration-count: 1"><i class="fa fa-university" aria-hidden="true"></i> 222222</li>

<li class="animated lightSpeedIn delay-2s animation-iteration-count: 1"><i class="fa fa-industry" aria-hidden="true"></i> aaaaaa</li>

<li class="animated slideInLeft delay-2-5s animation-iteration-count: 1"><i class="fa fa-key" aria-hidden="true"></i> bbbbb</li>

<li class="animated slideInRight delay-3s animation-iteration-count: 1"><i class="fa fa-thumbs-up" aria-hidden="true"></i> ccccc</li>

Is object empty?

Elegant way - use keys

var myEmptyObj = {};
var myFullObj = {"key":"value"};
console.log(Object.keys(myEmptyObj).length); //0
console.log(Object.keys(myFullObj).length); //1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Android SDK location

I found it here C:\Users\username\AppData\Local\Android\sdk .

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

How to hide a TemplateField column in a GridView

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
         e.Row.Cells[columnIndex].Visible = false;
}


If you don't prefer hard-coded index, the only workaround I can suggest is to provide a HeaderText for the GridViewColumn and then find the column using that HeaderText.

protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    ((DataControlField)UsersGrid.Columns
            .Cast<DataControlField>()
            .Where(fld => fld.HeaderText == "Email")
            .SingleOrDefault()).Visible = false;
}

how to execute php code within javascript

May be this way:

    <?php 
     if($_SERVER['REQUEST_METHOD']=="POST") {
       echo 'asdasda';
     }
    ?>

    <form method="post">
    <button type="submit" id="okButton">Order now</button>
</form>

List of foreign keys and the tables they reference in Oracle DB

My version, in my humble opinion, more readable:

SELECT   PARENT.TABLE_NAME  "PARENT TABLE_NAME"
,        PARENT.CONSTRAINT_NAME  "PARENT PK CONSTRAINT"
,       '->' " "
,        CHILD.TABLE_NAME  "CHILD TABLE_NAME"
,        CHILD.COLUMN_NAME  "CHILD COLUMN_NAME"
,        CHILD.CONSTRAINT_NAME  "CHILD CONSTRAINT_NAME"
FROM     ALL_CONS_COLUMNS   CHILD
,        ALL_CONSTRAINTS   CT
,        ALL_CONSTRAINTS   PARENT
WHERE    CHILD.OWNER  =  CT.OWNER
AND      CT.CONSTRAINT_TYPE  = 'R'
AND      CHILD.CONSTRAINT_NAME  =  CT.CONSTRAINT_NAME 
AND      CT.R_OWNER  =  PARENT.OWNER
AND      CT.R_CONSTRAINT_NAME  =  PARENT.CONSTRAINT_NAME 
AND      CHILD.TABLE_NAME  = ::table -- table name variable
AND      CT.OWNER  = ::owner; -- schema variable, could not be needed

Max length UITextField

With Swift 5 and iOS 12, try the following implementation of textField(_:shouldChangeCharactersIn:replacementString:) method that is part of the UITextFieldDelegate protocol:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let textFieldText = textField.text,
        let rangeOfTextToReplace = Range(range, in: textFieldText) else {
            return false
    }
    let substringToReplace = textFieldText[rangeOfTextToReplace]
    let count = textFieldText.count - substringToReplace.count + string.count
    return count <= 10
}
  • The most important part of this code is the conversion from range (NSRange) to rangeOfTextToReplace (Range<String.Index>). See this video tutorial to understand why this conversion is important.
  • To make this code work properly, you should also set the textField's smartInsertDeleteType value to UITextSmartInsertDeleteType.no. This will prevent the possible insertion of an (unwanted) extra space when performing a paste operation.

The complete sample code below shows how to implement textField(_:shouldChangeCharactersIn:replacementString:) in a UIViewController:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField! // Link this to a UITextField in Storyboard

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.smartInsertDeleteType = UITextSmartInsertDeleteType.no
        textField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textFieldText = textField.text,
            let rangeOfTextToReplace = Range(range, in: textFieldText) else {
                return false
        }
        let substringToReplace = textFieldText[rangeOfTextToReplace]
        let count = textFieldText.count - substringToReplace.count + string.count
        return count <= 10
    }

}

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

How to include clean target in Makefile?

By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done

How to automatically update your docker containers, if base-images are updated

One of the ways to do it is to drive this through your CI/CD systems. Once your parent image is built, have something that scans your git repos for images using that parent. If found, you'd then send a pull request to bump to new versions of the image. The pull request, if all tests pass, would be merged and you'd have a new child image based on updated parent. An example of a tool that takes this approach can be found here: https://engineering.salesforce.com/open-sourcing-dockerfile-image-update-6400121c1a75 .

If you don't control your parent image, as would be the case if you are depending on the official ubuntu image, you can write some tooling that detects changes in the parent image tag or checksum(not the same thing, tags are mutable) and invoke children image builds accordingly.

How to install a specific JDK on Mac OS X?

For people using any LION OS X 10.7.X

They uploaded Java SE 6 version 1.6.0_26 available here

http://support.apple.com/kb/dl1421

Installing a plain plugin jar in Eclipse 3.5

in Eclipse 4.4.1

  1. copy jar in "C:\eclipse\plugins"
  2. edit file "C:\eclipse\configuration\org.eclipse.equinox.simpleconfigurator\bundles.info"
  3. add jar info. example: com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
  4. restart Eclipse.

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

In Charles, go to Proxy>>Proxy Settings and select the SSL tab. Add your host to the list of Locations.

For example, if your secure call is going to https://secure.example.com, you can enter secure.example.com, or *.example.com.

Once the above is in place, you may need to right-click on the call in the main Charles window and select the SSL Proxying option.

Hope this helps.

Remove xticks in a matplotlib plot?

# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

Reordering arrays

Here is an immutable version for those who are interested:

function immutableMove(arr, from, to) {
  return arr.reduce((prev, current, idx, self) => {
    if (from === to) {
      prev.push(current);
    }
    if (idx === from) {
      return prev;
    }
    if (from < to) {
      prev.push(current);
    }
    if (idx === to) {
      prev.push(self[from]);
    }
    if (from > to) {
      prev.push(current);
    }
    return prev;
  }, []);
}

When and how should I use a ThreadLocal variable?

Threadlocal provides a very easy way to achieve objects reusability with zero cost.

I had a situation where multiple threads were creating an image of mutable cache, on each update notification.

I used a Threadlocal on each thread, and then each thread would just need to reset old image and then update it again from the cache on each update notification.

Usual reusable objects from object pools have thread safety cost associated with them, while this approach has none.

How to debug Google Apps Script (aka where does Logger.log log to?)

I've gone through these posts and somehow ended up finding a simple answer, which I'm posting here for those how want short and sweet solutions:

  1. Use console.log("Hello World") in your script.
  2. Go to https://script.google.com/home/my and select your add-on.
  3. Click on the ellipsis menu on Project Details, select Executions.

enter image description here

  1. Click on the header of the latest execution and read the log.

enter image description here

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

This is a bug in pycharm. PyCharm seems to be expecting the referenced module to be included in an __all__ = [] statement.

For proper coding etiquette, should you include the __all__ statement from your modules? ..this is actually the question we hear young Spock answering while he was being tested, to which he responded: "It is morally praiseworthy but not morally obligatory."

To get around it, you can simply disable that (extremely non-critical) (highly useful) inspection globally, or suppress it for the specific function or statement.

To do so:

  • put the caret over the erroring text ('choice', from your example above)
  • Bring up the intention menu (alt-enter by default, mine is set to alt-backspace)
  • hit the right arrow to open the submenu, and select the relevant action

PyCharm has its share of small bugs like this, but in my opinion its benefits far outweigh its drawbacks. If you'd like to try another good IDE, there's also Spyder/Spyderlib.

I know this is quite a bit after you asked your question, but I hope this helps (you, or someone else).

Edited: Originally, I thought that this was specific to checking __all__, but it looks like it's the more general 'Unresolved References' check, which can be very useful. It's probably best to use statement-level disabling of the feature, either by using the menu as mentioned above, or by specifying # noinspection PyUnresolvedReferences on the line preceding the statement.

How to fill in proxy information in cntlm config file?

The solution takes two steps!

First, complete the user, domain, and proxy fields in cntlm.ini. The username and domain should probably be whatever you use to log in to Windows at your office, eg.

Username            employee1730
Domain              corporate
Proxy               proxy.infosys.corp:8080

Then test cntlm with a command such as

cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk

It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini, eg:

Auth            NTLM
PassNT          A2A7104B1CE00000000000000007E1E1
PassLM          C66000000000000000000000008060C8

Finally, set the http_proxy environment variable in Windows (assuming you didn't change with the Listen field which by default is set to 3128) to the following

http://localhost:3128

Android dependency has different version for the compile and runtime

Add this code in your project level build.gradle file.

subprojects {
    project.configurations.all {
        resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "version which should be used - in your case 28.0.0-beta2"
            }
        }
    }
}

Sample Code :

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'io.fabric.tools:gradle:1.31.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


subprojects {
    project.configurations.all {
        resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "28.0.0"
            }
        }
    }
}

How do I find out what type each object is in a ArrayList<Object>?

import java.util.ArrayList;

/**
 * @author potter
 *
 */
public class storeAny {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Object> anyTy=new ArrayList<Object>();
        anyTy.add(new Integer(1));
        anyTy.add(new String("Jesus"));
        anyTy.add(new Double(12.88));
        anyTy.add(new Double(12.89));
        anyTy.add(new Double(12.84));
        anyTy.add(new Double(12.82));

        for (Object o : anyTy) {
            if(o instanceof String){
                System.out.println(o.toString());
            } else if(o instanceof Integer) {
                System.out.println(o.toString());   
            } else if(o instanceof Double) {
                System.out.println(o.toString());
            }
        }
    }
}

Undoing a 'git push'

git reset --hard HEAD^
git push origin -f

This will remove the last commit from your local device as well as Github

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

rejected master -> master (non-fast-forward)

This is because you did some changes in your master so the project ask you to pull first. If you want to push it anyway you can use brute force by typing this:

git push -f origin master

Remember to first commit your changes:

git add .
git commit -m "Your commit message"

How to download a file from my server using SSH (using PuTTY on Windows)

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Even without connection-sharing, you can still use the psftp or pscp from Windows command line.

See How to use PSCP to copy file from Unix machine to Windows machine ...?

Note that the scp is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).


If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop (what typically resolves to a path like C:\Users\username\Desktop).


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.

(I'm the author of WinSCP)

Handling urllib2's timeout? - Python

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

Project with path ':mypath' could not be found in root project 'myproject'

It's not enough to have just compile project("xy") dependency. You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).

Create a settings.gradle file in the root of your project and add this:

include ':progressfragment'

to that file. Then sync Gradle and it should work.

Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.

How to read/write a boolean when implementing the Parcelable interface?

It is hard to identify the real question here. I guess it is how to deal with booleans when implementing the Parcelable interface.

Some attributes of MyObject are boolean but Parcel don't have any method read/writeBoolean.

You will have to either store the value as a string or as a byte. If you go for a string then you'll have to use the static method of the String class called valueOf() to parse the boolean value. It isn't as effective as saving it in a byte tough.

String.valueOf(theBoolean);

If you go for a byte you'll have to implement a conversion logic yourself.

byte convBool = -1;
if (theBoolean) {
    convBool = 1;
} else {
    convBool = 0;
}

When unmarshalling the Parcel object you have to take care of the conversion to the original type.

Making an API call in Python with an API that requires a bearer token

Here is full example of implementation in cURL and in Python - for authorization and for making API calls

cURL

1. Authorization

You have received access data like this:

Username: johndoe

Password: zznAQOoWyj8uuAgq

Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa

Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga

Which you can call in cURL like this:

curl -k -d "grant_type=password&username=Username&password=Password" \

                    -H "Authorization: Basic Base64(consumer-key:consumer-secret)" \

                       https://somedomain.test.com/token

or for this case it would be:

curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \

                    -H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \

                      https://somedomain.test.com/token

Answer would be something like:

{
    "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
    "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
    "scope": "default",
    "token_type": "Bearer",
    "expires_in": 3600
}

2. Calling API

Here is how you call some API that uses authentication from above. Limit and offset are just examples of 2 parameters that API could implement. You need access_token from above inserted after "Bearer ".So here is how you call some API with authentication data from above:

curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"

Python

Same thing from above implemented in Python. I've put text in comments so code could be copy-pasted.

# Authorization data

import base64
import requests

username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()

# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh


headersAuth = {
    'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}

data = {
  'grant_type': 'password',
  'username': username,
  'password': password
}

## Authentication request

response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()

# When you print that response you will get dictionary like this:

    {
        "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
        "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
        "scope": "default",
        "token_type": "Bearer",
        "expires_in": 3600
    }

# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].


# Using authentication to make API calls   

## Define header for making API calls that will hold authentication data

headersAPI = {
    'accept': 'application/json',
    'Authorization': 'Bearer '+j['access_token'],
}

### Usage of parameters defined in your API
params = (
    ('offset', '0'),
    ('limit', '20'),
)

# Making sample API call with authentication and API parameters data

response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()

How to quit a java app from within the program

This should do it in the correct way:

mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowListener() {

@Override
public void windowClosing(WindowEvent e) {
    if (doQuestion("Really want to exit?")) {
      mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainFrame.dispose();
    }
}

Check if a div exists with jquery

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

Select Rows with id having even number

Sql Server we can use %

select * from orders where ID % 2 = 0;

This can be used in both Mysql and oracle. It is more affection to use mod function that %.

select * from orders where mod(ID,2) = 0

What is 'PermSize' in Java?

The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

You probably haven't installed GLUT:

  1. Install GLUT If you do not have GLUT installed on your machine you can download it from: http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip (or whatever version) GLUT Libraries and header files are • glut32.lib • glut.h

Source: http://cacs.usc.edu/education/cs596/OGL_Setup.pdf

EDIT:

The quickest way is to download the latest header, and compiled DLLs for it, place it in your system32 folder or reference it in your project. Version 3.7 (latest as of this post) is here: http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip

Folder references:

glut.h: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\GL\'
glut32.lib: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\'
glut32.dll: 'C:\Windows\System32\'

For 64-bit machines, you will want to do this.
glut32.dll: 'C:\Windows\SysWOW64\'

Same pattern applies to freeglut and GLEW files with the header files in the GL folder, lib in the lib folder, and dll in the System32 (and SysWOW64) folder.
1. Under Visual C++, select Empty Project.
2. Go to Project -> Properties. Select Linker -> Input then add the following to the Additional Dependencies field:
opengl32.lib
glu32.lib
glut32.lib

Reprinted from here

batch file to list folders within a folder to one level

Dir

Use the dir command. Type in dir /? for help and options.

dir /a:d /b

Redirect

Then use a redirect to save the list to a file.

> list.txt

Together

dir /a:d /b > list.txt

This will output just the names of the directories. if you want the full path of the directories use this below.


Full Path

for /f "delims=" %%D in ('dir /a:d /b') do echo %%~fD

Alternative

other method just using the for command. See for /? for help and options. This can output just the name %%~nxD or the full path %%~fD

for /d %%D in (*) do echo %%~fD

Notes

To use these commands directly on the command line, change the double percent signs to single percent signs. %% to %

To redirect the for methods, just add the redirect after the echo statements. Use the double arrow >> redirect here to append to the file, else only the last statement will be written to the file due to overwriting all the others.

... echo %%~fD>> list.txt

java.lang.IllegalArgumentException: No converter found for return value of type

While using Spring Boot 2.2 I run into a similiar error message and while googling my error message

No converter for [class java.util.ArrayList] with preset Content-Type 'null'

this question here is on top, but all answers here did not work for me, so I think it's a good idea to add the answer I found myself:

I had to add the following dependencies to the pom.xml:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
</dependency>

<dependency>
  <groupId>com.thoughtworks.xstream</groupId>
  <artifactId>xstream</artifactId>
  <version>1.4.11.1</version>
</dependency>

After this I need to add the following to the WebApplication class:

@SpringBootApplication
public class WebApplication
 {
  // ...

  @Bean
  public HttpMessageConverter<Object> createXmlHttpMessageConverter()
   {
    final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
    final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
    xstreamMarshaller.setAutodetectAnnotations(true);
    xmlConverter.setMarshaller(xstreamMarshaller);
    xmlConverter.setUnmarshaller(xstreamMarshaller);
    return xmlConverter;
   }

}

Last but not least within my @Controller I used:

@GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType. APPLICATION_JSON_VALUE})
@ResponseBody
public List<MeterTypeEntity> listXmlJson(final Model model)
 {
  return this.service.list();
 }

So now I got JSON and XML return values depending on the requests Accept header.

To make the XML output more readable (remove the complete package name from tag names) you could also add @XStreamAlias the following to your entity class:

@Table("ExampleTypes")
@XStreamAlias("ExampleType")
public class ExampleTypeEntity
 {
  // ...
 }

Hopefully this will help others with the same problem.

How can I get the current date and time in UTC or GMT in Java?

This code prints the current time UTC.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class Test
{
    public static void main(final String[] args) throws ParseException
    {
        final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        f.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(f.format(new Date()));
    }
}

Result

2013-10-26 14:37:48 UTC

flow 2 columns of text automatically with CSS

Maybe a slightly tighter version? My use case is outputting college majors given a json array of majors (data).

var count_data      = data.length;

$.each( data, function( index ){
    var column = ( index < count_data/2 ) ? 1 : 2;
    $("#column"+column).append(this.name+'<br/>');
});

<div id="majors_view" class="span12 pull-left">

  <div class="row-fluid">
    <div class="span5" id="column1"> </div>
    <div class="span5 offset1" id="column2"> </div>
  </div>

</div>

Import Excel Spreadsheet Data to an EXISTING sql table?

If you would like a software tool to do this, you might like to check out this step-by-step guide:

"How to Validate and Import Excel spreadsheet to SQL Server database"

http://leansoftware.net/forum/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

git remote add with other SSH port

Rather than using the ssh:// protocol prefix, you can continue using the conventional URL form for accessing git over SSH, with one small change. As a reminder, the conventional URL is:

git@host:path/to/repo.git

To specify an alternative port, put brackets around the user@host part, including the port:

[git@host:port]:path/to/repo.git

But if the port change is merely temporary, you can tell git to use a different SSH command instead of changing your repository’s remote URL:

export GIT_SSH_COMMAND='ssh -p port'
git clone git@host:path/to/repo.git # for instance

Find files and tar them (with spaces)

Use this:

find . -type f -print0 | tar -czvf backup.tar.gz --null -T -

It will:

  • deal with files with spaces, newlines, leading dashes, and other funniness
  • handle an unlimited number of files
  • won't repeatedly overwrite your backup.tar.gz like using tar -c with xargs will do when you have a large number of files

Also see:

How to split page into 4 equal parts?

Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.

The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.

As a bonus, text is responsively centered in the quarters.

HTML:

<head>
  <meta charset="utf-8">
  <title>Box model</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <h1 id="title">Title Bar</h1>
  <div id="dividedbox">
    <div class="quarter" id="NW">
      <p>NW</p>
    </div>
    <div class="quarter" id="NE">
      <p>NE</p>
    </div>
    <div class="quarter" id="SE">
      <p>SE</p>
    </div>?
    <div class="quarter" id="SW">
      <p>SW</p>
    </div>
  </div>
</body>

</html>

CSS:

html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%}   /* for div growth */
.quarter {position: absolute; width:50%; height:50%;  /* gives quarters their size */
  display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0;    left:0;     background:orange;     }
#NE { top:0;    left:50%;   background:lightblue;  }
#SW { top:50%;  left:0;     background:green;      }
#SE { top:50%;  left:50%;   background:red;        }

http://jsfiddle.net/og0j2d3v/

How to trigger click event on href element

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();
                  ^
              Important!

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

How to get exact browser name and version?

I have created a function in PHP language to get browser name, browser version, operating system (windows/linux etc.) along with device type (desktop / mobile / tablet).

function getBrowserInfo(){
    $browserInfo = array('user_agent'=>'','browser'=>'','browser_version'=>'','os_platform'=>'','pattern'=>'', 'device'=>'');

    $u_agent = $_SERVER['HTTP_USER_AGENT']; 
    $bname = 'Unknown';
    $ub = 'Unknown';
    $version = "";
    $platform = 'Unknown';

    $deviceType='Desktop';

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$u_agent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($u_agent,0,4))){

        $deviceType='Mobile';

    }

    if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10') {
        $deviceType='Tablet';
    }

    if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
        $deviceType='Tablet';
    }

    //$detect = new Mobile_Detect();
    
    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';

    } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';

    } elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the user agent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'IE'; 
        $ub = "MSIE";

    } else if(preg_match('/Firefox/i',$u_agent))
    { 
        $bname = 'Mozilla Firefox'; 
        $ub = "Firefox"; 

    } else if(preg_match('/Chrome/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Chrome'; 
        $ub = "Chrome"; 

    } else if(preg_match('/Safari/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Safari'; 
        $ub = "Safari"; 

    } else if(preg_match('/Opera/i',$u_agent) || preg_match('/OPR/i',$u_agent)) 
    { 
        $bname = 'Opera'; 
        $ub = "Opera"; 

    } else if(preg_match('/Netscape/i',$u_agent)) 
    { 
        $bname = 'Netscape'; 
        $ub = "Netscape"; 

    } else if((isset($u_agent) && (strpos($u_agent, 'Trident') !== false || strpos($u_agent, 'MSIE') !== false)))
    {
        $bname = 'Internet Explorer'; 
        $ub = 'Internet Explorer'; 
    } 
    

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';

    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];

        } else {
            $version= @$matches['version'][1];
        }

    } else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'user_agent' => $u_agent,
        'browser'      => $bname,
        'browser_version'   => $version,
        'os_platform'  => $platform,
        'pattern'   => $pattern,
        'device'    => $deviceType
    );
}

This solved my problem of browser detection, I hope, this will also help you. Thank you.

MySQL "incorrect string value" error when save unicode string in Django

Improvement to @madprops answer - solution as a django management command:

import MySQLdb
from django.conf import settings

from django.core.management.base import BaseCommand


class Command(BaseCommand):

    def handle(self, *args, **options):
        host = settings.DATABASES['default']['HOST']
        password = settings.DATABASES['default']['PASSWORD']
        user = settings.DATABASES['default']['USER']
        dbname = settings.DATABASES['default']['NAME']

        db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
        cursor = db.cursor()

        cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

        sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
        cursor.execute(sql)

        results = cursor.fetchall()
        for row in results:
            print(f'Changing table "{row[0]}"...')
            sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
            cursor.execute(sql)
        db.close()

Hope this helps anybody but me :)

Determine Pixel Length of String in Javascript/jQuery?

The contexts used for HTML Canvases have a built-in method for checking the size of a font. This method returns a TextMetrics object, which has a width property that contains the width of the text.

function getWidthOfText(txt, fontname, fontsize){
    if(getWidthOfText.c === undefined){
        getWidthOfText.c=document.createElement('canvas');
        getWidthOfText.ctx=getWidthOfText.c.getContext('2d');
    }
    var fontspec = fontsize + ' ' + fontname;
    if(getWidthOfText.ctx.font !== fontspec)
        getWidthOfText.ctx.font = fontspec;
    return getWidthOfText.ctx.measureText(txt).width;
}

Or, as some of the other users have suggested, you can wrap it in a span element:

function getWidthOfText(txt, fontname, fontsize){
    if(getWidthOfText.e === undefined){
        getWidthOfText.e = document.createElement('span');
        getWidthOfText.e.style.display = "none";
        document.body.appendChild(getWidthOfText.e);
    }
    if(getWidthOfText.e.style.fontSize !== fontsize)
        getWidthOfText.e.style.fontSize = fontsize;
    if(getWidthOfText.e.style.fontFamily !== fontname)
        getWidthOfText.e.style.fontFamily = fontname;
    getWidthOfText.e.innerText = txt;
    return getWidthOfText.e.offsetWidth;
}

EDIT 2020: added font name+size caching at Igor Okorokov's suggestion.

Exception from HRESULT: 0x800A03EC Error

Got same error in this line

 Object temp = range.Cells[i][0].Value;

Solved with non-zero based index

 Object temp = range.Cells[i][1].Value;

How is it possible that the guys who created this library thought it was a good idea to use non-zero based indexing?

Unable to execute dex: Multiple dex files define

This is a build path issue.

  • Make sure your bin folder is not included in your build path.

  • Right click on your project -> go to properties -> Build Path.

  • Make sure that Honeycomb library is in your libs/ folder and not in your source folder.

  • Include the libraries in libs/ individually in the build path.

    BTW, you may want to bring in the android-support-v4 library to get Ice Cream Sandwich support instead of the Honeycomb support library.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

How connect Postgres to localhost server using pgAdmin on Ubuntu?

if you open the psql console in a terminal window, by typing

$ psql

you're super user username will be shown before the =#, for example:

elisechant=#$

That will be the user name you should use for localhost.

Standardize data columns in R

The dplyr package has two functions that do this.

> require(dplyr)

To mutate specific columns of a data table, you can use the function mutate_at(). To mutate all columns, you can use mutate_all.

The following is a brief example for using these functions to standardize data.

Mutate specific columns:

dt = data.table(a = runif(3500), b = runif(3500), c = runif(3500))
dt = data.table(dt %>% mutate_at(vars("a", "c"), scale)) # can also index columns by number, e.g., vars(c(1,3))

> apply(dt, 2, mean)
            a             b             c 
 1.783137e-16  5.064855e-01 -5.245395e-17 

> apply(dt, 2, sd)
        a         b         c 
1.0000000 0.2906622 1.0000000 

Mutate all columns:

dt = data.table(a = runif(3500), b = runif(3500), c = runif(3500))
dt = data.table(dt %>% mutate_all(scale))

> apply(dt, 2, mean)
            a             b             c 
-1.728266e-16  9.291994e-17  1.683551e-16 

> apply(dt, 2, sd)
a b c 
1 1 1 

How do you decompile a swf file

This can also be done freely online: http://www.showmycode.com/

EDIT A quick Google search turned up this list, which probably has all the tools you could possibly want (look at the comments as well): http://bruce-lab.blogspot.co.il/2010/08/freeswfdecompilers.html

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

Get local href value from anchor (a) tag

The href property sets or returns the value of the href attribute of a link.

  var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
    var url="https://www.google.com/";
    console.log( url+hello);

Clear Application's Data Programmatically

Try this code

private void clearAppData() {
    try {
        if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
        } else {
            Runtime.getRuntime().exec("pm clear " + getApplicationContext().getPackageName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

What is the strict aliasing rule?

A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to uint32_ts or uint16_ts). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.

So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:

typedef struct Msg
{
    unsigned int a;
    unsigned int b;
} Msg;

void SendWord(uint32_t);

int main(void)
{
    // Get a 32-bit buffer from the system
    uint32_t* buff = malloc(sizeof(Msg));
    
    // Alias that buffer through message
    Msg* msg = (Msg*)(buff);
    
    // Send a bunch of messages    
    for (int i = 0; i < 10; ++i)
    {
        msg->a = i;
        msg->b = i+1;
        SendWord(buff[0]);
        SendWord(buff[1]);   
    }
}

The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a compatible type or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, maybe get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.

(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)

To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of buff every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load buff[0] and buff[1] into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of buff could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.

Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.

void SendMessage(uint32_t* buff, size_t size32)
{
    for (int i = 0; i < size32; ++i) 
    {
        SendWord(buff[i]);
    }
}

And rewrote our earlier loop to take advantage of this convenient function

for (int i = 0; i < 10; ++i)
{
    msg->a = i;
    msg->b = i+1;
    SendMessage(buff, 2);
}

The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If SendMessage is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.

So how do I get around this?

  • Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.

      union {
          Msg msg;
          unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
      };
    
  • You can disable strict aliasing in your compiler (f[no-]strict-aliasing in gcc))

  • You can use char* for aliasing instead of your system's word. The rules allow an exception for char* (including signed char and unsigned char). It's always assumed that char* aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.

Beginner beware

This is only one potential minefield when overlaying two types onto each other. You should also learn about endianness, word alignment, and how to deal with alignment issues through packing structs correctly.

Footnote

1 The types that C 2011 6.5 7 allows an lvalue to access are:

  • a type compatible with the effective type of the object,
  • a qualified version of a type compatible with the effective type of the object,
  • a type that is the signed or unsigned type corresponding to the effective type of the object,
  • a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
  • a character type.

Inline labels in Matplotlib

A simpler approach like the one Ioannis Filippidis do :

import matplotlib.pyplot as plt
import numpy as np

# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)

# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')

factor=3/4 ;offset=20  # text position in view  
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22  t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()

code python 3 on sageCell

How can I sanitize user input with PHP?

To address the XSS issue, take a look at HTML Purifier. It is fairly configurable and has a decent track record.

As for the SQL injection attacks, make sure you check the user input, and then run it though mysql_real_escape_string(). The function won't defeat all injection attacks, though, so it is important that you check the data before dumping it into your query string.

A better solution is to use prepared statements. The PDO library and mysqli extension support these.

Capture keyboardinterrupt in Python without try-except

If someone is in search for a quick minimal solution,

import signal

# The code which crashes program on interruption

signal.signal(signal.SIGINT, call_this_function_if_interrupted)

# The code skipped if interrupted

How to remove border of drop down list : CSS

This solution seems not working for me.

select {
    border: 0px;
    outline: 0px;
}

But you may set select border to the background color of the container and it will work.

How to get all values from python enum class?

Using a classmethod with __members__:

class RoleNames(str, Enum):
    AGENT = "agent"
    USER = "user"
    PRIMARY_USER = "primary_user"
    SUPER_USER = "super_user"
    
    @classmethod
    def list_roles(cls):
        role_names = [member.value for role, member in cls.__members__.items()]
        return role_names
>>> role_names = RoleNames.list_roles()
>>> print(role_names)

or if you have multiple Enum classes and want to abstract the classmethod:

class BaseEnum(Enum):
    @classmethod
    def list_roles(cls):
        role_names = [member.value for role, member in cls.__members__.items()]
        return role_names


class RoleNames(str, BaseEnum):    
    AGENT = "agent"
    USER = "user"
    PRIMARY_USER = "primary_user"
    SUPER_USER = "super_user"
    

class PermissionNames(str, BaseEnum):
    READ = "updated_at"
    WRITE = "sort_by"
    READ_WRITE = "sort_order"

How to find the width of a div using vanilla JavaScript?

You can use clientWidth or offsetWidth Mozilla developer network reference

It would be like:

document.getElementById("yourDiv").clientWidth; // returns number, like 728

or with borders width :

document.getElementById("yourDiv").offsetWidth; // 728 + borders width

Why is the minidlna database not being refreshed?

I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.

ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).

I'm still trying to find a way around this. If anyone has any input, it's most welcome.

Find html label associated with a given input

$("label[for='inputId']").text()

This helped me to get the label of an input element using its ID.

CSS background image to fit height, width should auto-scale in proportion

I just had the same issue and this helped me:

html {
    height: auto;
    min-height: 100%;
    background-size:cover;
}

How do I make WRAP_CONTENT work on a RecyclerView

Put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content.

Source: This comment.

Split array into chunks

_x000D_
_x000D_
    const array = [86,133,87,133,88,133,89,133,90,133];_x000D_
    const new_array = [];_x000D_
_x000D_
 const chunksize = 2;_x000D_
    while (array.length) {_x000D_
     const chunk = array.splice(0,chunksize);_x000D_
     new_array.push(chunk);_x000D_
    }_x000D_
_x000D_
    console.log(new_array)
_x000D_
_x000D_
_x000D_

How does one reorder columns in a data frame?

# reorder by column name
data <- data[c("A", "B", "C")]

#reorder by column index
data <- data[c(1,3,2)]

How do I ZIP a file in C#, using no 3rd-party APIs?

    private static string CompressFile(string sourceFileName)
    {
        using (ZipArchive archive = ZipFile.Open(Path.ChangeExtension(sourceFileName, ".zip"), ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile(sourceFileName, Path.GetFileName(sourceFileName));
        }
        return Path.ChangeExtension(sourceFileName, ".zip");
    }

OSError - Errno 13 Permission denied

Simply try:

sudo cp /source /destination

What is the usefulness of PUT and DELETE HTTP request methods?

Although I take the risk of not being popular I say they are not useful nowadays.

I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.

Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.

Let's take an example:

  • /api/entity/list/{id} vs GET /api/entity/{id}
  • /api/entity/add/{id} vs POST /api/entity
  • /api/entity/edit/{id} vs PUT /api/entity/{id}
  • /api/entity/delete/{id} vs DELETE /api/entity/{id}

On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.

Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.

In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.

Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards

sudo: docker-compose: command not found

I will leave this here as a possible fix, worked for me at least and might help others. Pretty sure this would be a linux only fix.

I decided to not go with the pip install and go with the github version (option one on the installation guide).

Instead of placing the copied docker-compose directory into /usr/local/bin/docker-compose from the curl/github command, I went with /usr/bin/docker-compose which is the location of Docker itself and will force the program to run in root. So it works in root and sudo but now won't work without sudo so the opposite effect which is what you want to run it as a user anyways.

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

Adjust UILabel height to text

In swift 4.1 and Xcode 9.4.1

Only 3 steps

Step 1)

//To calculate height for label based on text size and width
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat {
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text

    label.sizeToFit()
    return label.frame.height
}

Step 2)

//Call this function
let height = heightForView(text: "This is your text", font: UIFont.systemFont(ofSize: 17), width: 300)
print(height)//Output : 41.0

Step 3)

//This is your label
let proNameLbl = UILabel(frame: CGRect(x: 0, y: 20, width: 300, height: height))
proNameLbl.text = "This is your text"
proNameLbl.font = UIFont.systemFont(ofSize: 17)
proNameLbl.numberOfLines = 0
proNameLbl.lineBreakMode = .byWordWrapping
infoView.addSubview(proNameLbl)

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

SVN- How to commit multiple files in a single shot

You can use an svn changelist to keep track of a set of files that you want to commit together.

The linked page goes into lots of details, but here's an executive summary example:

$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist

How to Debug Variables in Smarty like in PHP var_dump()

try this .... Set $debugging to TRUE in Smarty.

How do I prevent mails sent through PHP mail() from going to spam?

You must to add a needle headers:

Sample code :

$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "BCC: [email protected]\r\n";

if ( mail($to,$subject,$message,$headers) ) {
   echo "The email has been sent!";
   } else {
   echo "The email has failed!";
   }
?> 

How do I use regular expressions in bash scripts?

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

How to create a popup windows in javafx

The Popup class might be better than the Stage class, depending on what you want. Stage is either modal (you can't click on anything else in your app) or it vanishes if you click elsewhere in your app (because it's a separate window). Popup stays on top but is not modal.

See this Popup Window example.

Change selected value of kendo ui dropdownlist

You have to use Kendo UI DropDownList select method (documentation in here).

Basically you should:

// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");

If you know the index you can use:

// selects by index
dropdownlist.select(1);

If not, use:

// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
    return dataItem.symbol === "test";
});

JSFiddle example here

REST / SOAP endpoints for a WCF service

MSDN seems to have an article for this now:

https://msdn.microsoft.com/en-us/library/bb412196(v=vs.110).aspx

Intro:

By default, Windows Communication Foundation (WCF) makes endpoints available only to SOAP clients. In How to: Create a Basic WCF Web HTTP Service, an endpoint is made available to non-SOAP clients. There may be times when you want to make the same contract available both ways, as a Web endpoint and as a SOAP endpoint. This topic shows an example of how to do this.

Android Studio - Auto complete and other features not working

  1. Close Android Studio

  2. Go to c_users_path_on_windows/.AndroidStudio3.5/system/

  3. Delete the cache folder

  4. Start Android Studio

    This works for me.

Trim leading and trailing spaces from a string in awk

If you want to trim all spaces, only in lines that have a comma, and use awk, then the following will work for you:

awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt

If you only want to remove spaces in the second column, change the expression to

awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt

Note that gsub substitutes the character in // with the second expression, in the variable that is the third parameter - and does so in-place - in other words, when it's done, the $0 (or $2) has been modified.

Full explanation:

-F,            use comma as field separator 
               (so the thing before the first comma is $1, etc)
/,/            operate only on lines with a comma 
               (this means empty lines are skipped)
gsub(a,b,c)    match the regular expression a, replace it with b, 
               and do all this with the contents of c
print$1","$2   print the contents of field 1, a comma, then field 2
input.txt      use input.txt as the source of lines to process

EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub commands. Whilst giving credit I will give an explanation of how it works.

gsub(/^[ \t]+/,"",$2);    - starting at the beginning (^) replace all (+ = zero or more, greedy)
                             consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)}    - do the same, but now for all space up to the end of string ($)
1                         - ="true". Shorthand for "use default action", which is print $0
                          - that is, print the entire (modified) line

Android - Launcher Icon Size

According to the Material design guidelines (here, under "DP unit grid"), your product icon should be of size 48 dp, with a padding of 1dp, except for the case of XXXHDPI, where the padding should be 4dp.

So, in pixels, the sizes are:

  • 48 × 48 (mdpi) , with 1 dp padding
  • 72 × 72 (hdpi), with 1 dp padding
  • 96 × 96 (xhdpi), with 1 dp padding
  • 144 × 144 (xxhdpi), with 1 dp padding
  • 192 × 192 (xxxhdpi) , with 4 dp padding

I recommend to avoid using VectorDrawable as some launchers don't support it, but I think WEBP should be ok as long as you have your minSdk support transparency for them (API 18 and above - Android 4.3).

If you publish on the Play Store, the requirement to what to upload there are (based on here) :

  • 32-bit PNG (with alpha)
  • Dimensions: 512px by 512px
  • Maximum file size: 1024KB

ActionBar text color

I was having the same problem as you, it's a Holo.Light theme but I wanted to style the ActionBar color, so I needed to change the text color as well and also both Title and Menus. So at the end I went to git hub and looked at source code until I find the damn correct style:

<?xml version="1.0" encoding="utf-8"?>
<!-- For honeycomb and up -->
<resources>

    <style name="myTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/myTheme.ActionBar</item>
        <item name="android:actionMenuTextColor">@color/actionBarText</item>
    </style>

    <style name="myTheme.ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">@drawable/actionbarbground</item>
        <item name="android:titleTextStyle">@style/myTheme.ActionBar.Text</item>
    </style>

    <style name="myTheme.ActionBar.Text" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/actionBarText</item>
    </style>

</resources>

so now all you have to do is set whatever @color/actionBarText and@drawable/actionbarbground you want!

Path to Powershell.exe (v 2.0)

Here is one way...

(Get-Process powershell | select -First 1).Path

Here is possibly a better way, as it returns the first hit on the path, just like if you had ran Powershell from a command prompt...

(Get-Command powershell.exe).Definition

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

In AVD emulator how to see sdcard folder? and Install apk to AVD?

//in linux

// in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img that is your sdcard file.

//To install apk in linux

$adb install ./yourfolder/myapkfile.apk

HTTPS using Jersey Client

If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.

SSLContext sslContext = null;
try {
  sslContext = SSLContext.getInstance("SSL");
  // Create a new X509TrustManager
  sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
  throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
  .sslContext(sslContext).build();
return client;

private TrustManager[] getTrustManager() {
  return new TrustManager[] {
    new X509TrustManager() {
      @Override
      public X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
    }
  };
}

MySQL - DATE_ADD month interval

DATE_ADD works just fine with different months. The problem is that you are adding six months to 2001-01-01 and July 1st is supposed to be there.

This is what you want to do:

SELECT * 
FROM mydb 
WHERE creationdate BETWEEN "2011-01-01" 
                   AND DATE_ADD("2011-01-01", INTERVAL 6 MONTH) - INTERVAL 1 DAY
GROUP BY MONTH(creationdate)

OR

SELECT * 
FROM mydb 
WHERE creationdate >= "2011-01-01" 
AND creationdate < DATE_ADD("2011-01-01", INTERVAL 6 MONTH)
GROUP BY MONTH(creationdate)

For further learning, take a look at DATE_ADD documentation.

*edited to correct syntax

Adb Devices can't find my phone

I have a ZTE Crescent phone (Orange San Francisco II).

When I connect the phone to the USB a disk shows up in OS X named 'ZTE_USB_Driver'.

Running adb devices displays no connected devices. But after I eject the 'ZTE_USB_Driver' disk from OS X, and run adb devices again the phone shows up as connected.

Why would you use Expression<Func<T>> rather than Func<T>?

When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).

Conceptually, Expression<Func<T>> is completely different from Func<T>. Func<T> denotes a delegate which is pretty much a pointer to a method and Expression<Func<T>> denotes a tree data structure for a lambda expression. This tree structure describes what a lambda expression does rather than doing the actual thing. It basically holds data about the composition of expressions, variables, method calls, ... (for example it holds information such as this lambda is some constant + some parameter). You can use this description to convert it to an actual method (with Expression.Compile) or do other stuff (like the LINQ to SQL example) with it. The act of treating lambdas as anonymous methods and expression trees is purely a compile time thing.

Func<int> myFunc = () => 10; // similar to: int myAnonMethod() { return 10; }

will effectively compile to an IL method that gets nothing and returns 10.

Expression<Func<int>> myExpression = () => 10;

will be converted to a data structure that describes an expression that gets no parameters and returns the value 10:

Expression vs Func larger image

While they both look the same at compile time, what the compiler generates is totally different.

What is sr-only in Bootstrap 3?

As JoshC said, the class .sr-only is used to visually hide the information used for screen readers only. But not only to hide labels. You might consider hiding various other elements such as "skip to main content" link, icons which have an alternative texts etc.

BTW. you can also use .sr-only sr-only-focusable if you need the element to become visible when focused e.g. "skip to main content"

If you want make your website even more accessible I recommend to start here:

Why?

According to the World Health Organization, 285 million people have vision impairments. So making a website accessible is important.

IMPORTANT: Avoid treating disabled users differently. Generally speaking try to avoid developing a different content for different groups of users. Instead try to make accessible the existing content so that it simply works out-of-the-box and for all not specifically targeting e.g. screen readers. In other words don't try to reinvent the wheel. Otherwise the resulting accessibility will often be worse than if there was nothing developed at all. We developers should not assume how those users will use our website. So be very careful when you need to develop such solutions. Obviously a "skip link" is a good example of such content if it's made visible when focused. But there many bad examples too. Such would be hiding from a screen reader a "zoom" button on the map assuming that it has no relevance to blind users. But surprisingly, a zoom function indeed is used among blind users! They like to download images like many other users do (even in high resolution), for sending them to somebody else or for using them in some other context. Source - Read more @ADG: Bad ARIA practices

How to remove an iOS app from the App Store

I just changed availability date to a future date. After doing that, I received following message -

You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.

Which means that the app is removed and no longer available.

Could not find a part of the path ... bin\roslyn\csc.exe

Reboot Windows.

This is the only solution that worked for me after trying rebuild, delete contents of bin and rebuild, restart Visual Studio.

It's yet another example of how terrible C#/.NET build tools are.

I think (after reading many of the answers), the overall conclusion is that the cause and solution of this problem heavily depends on the setup and project, so if one answer does not work, just try another. Try non-intrusive/destructive solutions, such as restarting Visual Studio, rebooting, rebuilding, etc., FIRST, before messing with NuGet packages or reinstalling development tools. Good luck!

(NOTE: Using Visual Studio 2019, and project file was originally created in Visual Studio 2015. Maybe this helps someone investigate the issue)

(EDIT: Could this be caused by not rebooting after installing/modifying the Visual Studio installation or updating Visual Studio when the installer prompts to reboot?)

Excel 2010: how to use autocomplete in validation list

As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.

As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.

Get difference between 2 dates in JavaScript?

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

In Chrome 55, prevent showing Download button for HTML 5 video

This can hide download button on Chrome when HTML5 Audio is used.

_x000D_
_x000D_
 #aPlayer > audio { width: 100% }_x000D_
/* Chrome 29+ */_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0)_x000D_
  and (min-resolution:.001dpcm) {_x000D_
     /* HIDE DOWNLOAD AUDIO BUTTON */_x000D_
     #aPlayer {_x000D_
           overflow: hidden;width: 390px; _x000D_
    }_x000D_
_x000D_
    #aPlayer > audio { _x000D_
      width: 420px; _x000D_
    }_x000D_
}_x000D_
_x000D_
/* Chrome 22-28 */_x000D_
@media screen and(-webkit-min-device-pixel-ratio:0) {_x000D_
    _x000D_
      #aPlayer {_x000D_
           overflow: hidden;width: 390px; _x000D_
        }_x000D_
_x000D_
    #aPlayer > audio { width: 420px; }_x000D_
}
_x000D_
<div id="aPlayer">_x000D_
 <audio autoplay="autoplay" controls="controls">_x000D_
  <source src="http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2012.mp3" type="audio/mpeg" />_x000D_
 </audio>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Click here to see the screenshot

Change Default branch in gitlab

To change the default branch in Gitlab 7.7.2:

  • Click Settings in the left-hand bar
  • Change the Default Branch to the desired branch
  • Click Save Changes.

Change background color of selected item on a ListView

This is a simple method that can handle selection even if the list is long as well:

public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;
    rowView = inflater.inflate(R.layout.list_item, null);
    //Handle your items.
    //StringHolder.mSelectedItem is a public static variable.
    if(getItemId(position)==StringHolder.mSelectedItem){
        rowView.setBackgroundColor(Color.LTGRAY);

    }else{
        rowView.setBackgroundColor(Color.TRANSPARENT);
    }
    return rowView;
}

And then in your onclicklistener:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1);
            catagoryAdapter.notifyDataSetChanged();
.....

Disabling right click on images using jquery

The better way of doing this without jQuery:

const images = document.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
    images[i].addEventListener('contextmenu', event => event.preventDefault());
}

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

In lollipop and above versions Android introduced multiple users, When you delete an app it still exists in device. Please make sure your app is deleted from all users and then reinstall it.

You can check by going to Settings->Apps->All and check your app in the list, On selecting your app tap on more button in actionbar and select uninstall for all users.

Detect backspace and del on "input" event?

//Here's one example, not sure what your application is but here is a relevant and likely application 
function addDashesOnKeyUp()
{
    var tb = document.getElementById("tb1"); 
    var key = event.which || event.keyCode || event.charCode;

    if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) ) 
    {
        tb.value += "-"
    } 
}

How to export a CSV to Excel using Powershell

If you want to convert CSV to Excel without Excel being installed, you can use the great .NET library EPPlus (under LGPL license) to create and modify Excel Sheets and also convert CSV to Excel really fast!

Preparation

  1. Download the latest stable EPPlus version
  2. Extract EPPlus to your preferred location (e.g. to $HOME\Documents\WindowsPowerShell\Modules\EPPlus)
  3. Right Click EPPlus.dll, select Properties and at the bottom of the General Tab click "Unblock" to allow loading of this dll. If you don't have the rights to do this, try [Reflection.Assembly]::UnsafeLoadFrom($DLLPath) | Out-Null

Detailed Powershell Commands to import CSV to Excel

# Create temporary CSV and Excel file names
$FileNameCSV = "$HOME\Downloads\test.csv"
$FileNameExcel = "$HOME\Downloads\test.xlsx"

# Create CSV File (with first line containing type information and empty last line)
Get-Process | Export-Csv -Delimiter ';' -Encoding UTF8 -Path $FileNameCSV

# Load EPPlus
$DLLPath = "$HOME\Documents\WindowsPowerShell\Modules\EPPlus\EPPlus.dll"
[Reflection.Assembly]::LoadFile($DLLPath) | Out-Null

# Set CSV Format
$Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
$Format.Delimiter = ";"
# use Text Qualifier if your CSV entries are quoted, e.g. "Cell1","Cell2"
$Format.TextQualifier = '"'
$Format.Encoding = [System.Text.Encoding]::UTF8
$Format.SkipLinesBeginning = '1'
$Format.SkipLinesEnd = '1'

# Set Preferred Table Style
$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1

# Create Excel File
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage 
$Worksheet = $ExcelPackage.Workbook.Worksheets.Add("FromCSV")

# Load CSV File with first row as heads using a table style
$null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true) 

# Load CSV File without table style
#$null=$Worksheet.Cells.LoadFromText($file,$format) 

# Fit Column Size to Size of Content
$Worksheet.Cells[$Worksheet.Dimension.Address].AutoFitColumns()

# Save Excel File
$ExcelPackage.SaveAs($FileNameExcel) 

Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"

Changing git commit message after push (given that no one pulled from remote)

It should be noted that if you use push --force with mutiple refs, they will ALL be modified as a result. Make sure to pay attention to where your git repo is configured to push to. Fortunately there is a way to safeguard the process slightly, by specifying a single branch to update. Read from the git man pages:

Note that --force applies to all the refs that are pushed, hence using it with push.default set to matching or with multiple push destinations configured with remote.*.push may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a + in front of the refspec to push (e.g git push origin +master to force a push to the master branch).

Is try-catch like error handling possible in ASP Classic?

1) Add On Error Resume Next at top of the page

2) Add following code at bottom of the page

If Err.Number <> 0 Then

  Response.Write (Err.Description)   

  Response.End 

End If

On Error GoTo 0

libpthread.so.0: error adding symbols: DSO missing from command line

What I have found is that sometimes the library that the linker complains about is not the one causing the problem. Possibly there is a clever way to work out where the problem is but this is what I do:

  • Comment out all the linked libraries in the link command.
  • Clean out all .o's, .so's etc (Usually make clean is enough, but you may want to run a recursive find + rm, or something similar).
  • Uncomment the libraries in the link command one at a time and re-arrange the order as necessary.

@peter karasev: I have come across the same problem with a gcc 4.8.2 cmake project on CentOS7. The order of the libraries in "target_link_libraries" section is important. I guess cmake just passes the list on to the linker as-is, i.e. it doesn't try and work out the correct order. This is reasonable - when you think about it cmake can't know what the correct order is until the linking is successfully completed.

Stop handler.postDelayed()

  Boolean condition=false;  //Instance variable declaration.

 //-----------------Inside oncreate--------------------------------------------------- 
  start =(Button)findViewById(R.id.id_start);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                starthandler();

                if(condition=true)
                {
                    condition=false;
                }


            }
        });

        stop=(Button) findViewById(R.id.id_stoplocatingsmartplug);

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stophandler();

            }
        });


    }

//-----------------Inside oncreate---------------------------------------------------

 public void starthandler()
    {

        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {


                if(!condition)
                {
                    //Do something after 100ms 


                }

            }
        }, 5000);

    }


    public void stophandler()
    {
        condition=true;
    }

How do you redirect HTTPS to HTTP?

This has not been tested but I think this should work using mod_rewrite

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

Set Radiobuttonlist Selected from Codebehind

We can change the item by value, here is the trick:

radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2

How do I make an image smaller with CSS?

CSS 3 introduces the background-size property, but support is not universal.

Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.

Difference between HashSet and HashMap?

Differences: with respect to heirarchy: HashSet implements Set. HashMap implements Map and stores a mapping of keys and values.

A use of HashSet and HashMap with respect to database would help you understand the significance of each.
HashSet: is generally used for storing unique collection objects. E.g: It might be used as implementation class for storing many-to-one relation ship between
class Item and Class Bid where (Item has many Bids) HashMap: is used to map a key to value.the value may be null or any Object /list of Object (which is object in itself).

fetch in git doesn't get all branches

Remote update

You need to run

git remote update

or

git remote update <remote> 

Then you can run git branch -r to list the remote branches.

Checkout a new branch

To track a (new) remote branch as a local branch:

git checkout -b <local branch> <remote>/<remote branch>

or (sometimes it doesn't work without the extra remotes/):

git checkout -b <local branch> remotes/<remote>/<remote branch>

Helpful git cheatsheets

LISTAGG function: "result of string concatenation is too long"

Managing overflows in LISTAGG

We can use the Database 12c SQL pattern matching function, MATCH_RECOGNIZE, to return a list of values that does not exceed limit.

Example code and more explanation in below link.

https://blogs.oracle.com/datawarehousing/entry/managing_overflows_in_listagg

How to delete or change directory of a cloned git repository on a local computer

  1. Go to working directory where you project folder (cloned folder) is placed.
  2. Now delete the folder.
  3. in windows just right click and do delete.
  4. in command line use rm -r "folder name"
  5. this worked for me

Spring MVC @PathVariable with dot (.) is getting truncated

In Spring Boot Rest Controller, I have resolved these by following Steps:

RestController :

@GetMapping("/statusByEmail/{email:.+}/")
public String statusByEmail(@PathVariable(value = "email") String email){
  //code
}

And From Rest Client:

Get http://mywebhook.com/statusByEmail/[email protected]/

What does the "map" method do in Ruby?

It "maps" a function to each item in an Enumerable - in this case, a range. So it would call the block passed once for every integer from 0 to param_count (exclusive - you're right about the dots) and return an array containing each return value.

Here's the documentation for Enumerable#map. It also has an alias, collect.

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

I believe I wasted like 1 day on researching it and this what I have come out with.

You need to add the Impersonating user to the Debug folder of your Solution as the Framework will try to access the DLL from this location and place it in Temporary Asp.Net Folder.

So basically follow these 2 steps

  1. Give permission to Temporary Asp.Net Folder under C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files and make sure the user you are adding here is the same you are using while Impersonating.

  2. Add the Impersonating user to the Debug folder of your Solution YourSolutionPath .. \bin\Debug

This should work

Displaying a vector of strings in C++

vector.size() returns the size of a vector. You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. First put some data in the vector and then try to add them. You can take input from the user for the number of string user wants to enter.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
    vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        userString.push_back(word);
        sentence += userString[i] + " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

another thing, actually you don't have to use a vector to do this.Two strings can do the job for you.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

and if you want to enter string until the user wish , code will be like this:

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    //int SIZE;
    //cin>>SIZE;    //what will be the size of the vector
    while(cin>>word)
    {
        //cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
  //  system("PAUSE");
    return 0;
}

How to find column names for all tables in all databases in SQL Server

Some minor improvements

->previous answers weren't showing all results

->possible to filter on column name by setting the column name variable

DECLARE @columnname nvarchar(150)
SET @columnname=''

DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name COLLATE SQL_Latin1_General_CP1_CI_AS as name,c.name COLLATE SQL_Latin1_General_CP1_CI_AS as columnname,c.column_id
from '+d.name+'.sys.columns            c
    inner join '+d.name+'.sys.objects  o on c.object_id=o.object_id
    INNER JOIN '+d.name+'.sys.schemas  sh on o.schema_id=sh.schema_id
    where c.name like ''%'+@columnname+'%'' and sh.name<>''sys'' 
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

How can I use jQuery in Greasemonkey?

@require is NOT only processed when the script is first installed! On my observations it is proccessed on the first execution time! So you can install a script via Greasemonkey's command for creating a brand-new script. The only thing you have to take care about is, that there is no page reload triggered, befor you add the @requirepart. (and save the new script...)

If REST applications are supposed to be stateless, how do you manage sessions?

There is no spoon.

Don't think of statelessness like "sending all your stuff to the server again and again". No way. There will be state, always - database itself is a kind of state after all, you're a registered user, so any set of client-side info won't be valid without the server side. Technically, you're never truly stateless.

The Login Debate

    What does it even mean to not keep a session - and log in every time?

    Some mean "send the password each time", that's just plain stupid. Some say "nah of course not, send a token instead" - lo and behold, PHP session is doing almost exactly that. It sends a session id which is a kind of token and it helps you reach your personal stuff without resending u/pw every time. It's also quite reliable and well tested. And yes, convenient, which can turn into a drawback, see next paragraph.

Reduce footprint

    What you should do, instead, and what makes real sense, is thin your webserver footprint to the minimum. Languages like PHP make it very easy to just stuff everything in the session storage - but sessions have a price tag. If you have several webservers, they need to share session info, because they share the load too - any of them may have to serve the next request.

    A shared storage is a must. Server needs to know at least if someone's logged in or not. (And if you bother the database every time you need to decide this, you're practically doomed.) Shared storages need to be a lot faster than the database. This brings the temptation: okay, I have a very fast storage, why not do everything there? - and that's where things go nasty in the other way.

So you're saying, keep session storage to the minimum?

    Again, it's your decision. You can store stuff there for performance reasons (database is almost always slower than Redis), you can store information redundantly, implement your own caching, whatever - just keep in mind that web servers will have a bigger load if you store a lot of rubbish on them. Also, if they break under heavy loads (and they will), you lose valuable information; with the REST way of thinking, all that happens in this case is the client sends the same (!) request again and it gets served this time.

How to do it right then?

    No one-fits-all solution here. I'd say choose a level of statelessness and go with that. Sessions may be loved by some and hated by others but they're not going anywhere. With every request, send as much information as makes sense, a bit more perhaps; but don't interpret statelessness as not having a session, nor as logging in every time. Somehow the server must know it's you; PHP session ids are one good way, manually generated tokens are another.

    Think and decide - don't let design trends think for you.

What is the purpose of willSet and didSet in Swift?

The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get/set, you need another field to hold the value. With willSet and didSet, you can take action when the value is modified without needing another field. For instance, in that example:

class Foo {
    var myProperty: Int = 0 {
        didSet {
            print("The value of myProperty changed from \(oldValue) to \(myProperty)")
        }
    }
}

myProperty prints its old and new value every time it is modified. With just getters and setters, I would need this instead:

class Foo {
    var myPropertyValue: Int = 0
    var myProperty: Int {
        get { return myPropertyValue }
        set {
            print("The value of myProperty changed from \(myPropertyValue) to \(newValue)")
            myPropertyValue = newValue
        }
    }
}

So willSet and didSet represent an economy of a couple of lines, and less noise in the field list.

Adding items to an object through the .push() method

Another way of doing it would be:

stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});

Read more here: Object.assign()

Unable to import path from django.urls

For those who are using python 2.7, python2.7 don't support django 2 so you can't install django.urls. If you are already using python 3.6 so you need to upgrade django to latest version which is greater than 2.

  • On PowerShell

    pip install -U django

  • Verification

>

PS C:\Users\xyz> python
Python 3.6.6 |Anaconda, Inc.| (default, Jul 25 2018, 15:27:00) [MSC v.1910 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> from django.urls import path
>>>

As next prompt came, it means it is installed now and ready to use.

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

Retrieving Android API version programmatically

Build.VERSION.RELEASE;

That will give you the actual numbers of your version; aka 2.3.3 or 2.2. The problem with using Build.VERSION.SDK_INT is if you have a rooted phone or custom rom, you could have a non standard OS (aka my android is running 2.3.5) and that will return a null when using Build.VERSION.SDK_INT so Build.VERSION.RELEASE will work no matter using standard Android version or not !

To use it, you could just do this;

String androidOS = Build.VERSION.RELEASE;

How to get screen dimensions as pixels in Android

Isn't this a much better solution? DisplayMetrics comes with everything you need and works from API 1.

public void getScreenInfo(){
    DisplayMetrics metrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

    heightPixels = metrics.heightPixels;
    widthPixels = metrics.widthPixels;
    density = metrics.density;
    densityDpi = metrics.densityDpi;
}

You can also get the actual display (including screen decors, such as Status Bar or software navigation bar) using getRealMetrics, but this works on 17+ only.

Am I missing something?

what is the differences between sql server authentication and windows authentication..?

I think the main difference is security.

Windows Authentication means that the identity is handled as part of the windows handashaking and now password is ever 'out there' for interception.

SQL Authentication means that you have to store (or provide) a username and a password yourself making it much easier to breach. A heap of effort has gone into making windows authentication very robust and secure.

Might I suggest that if you do implement Windows Authentication use Groups and Roles to do it. Groups in Windows and Roles in SQL. Having to setup lots of users in SQL is a big pain when you can just setup the group and then add each user to the group. (I think most security should be done this way anyway).

Android: keep Service running when app is killed

If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved method of your service as follows:

 Intent intent = new Intent("com.android.ServiceStopped");
 sendBroadcast(intent);

and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.

Object passed as parameter to another class, by value or reference?

Assuming someTestObj is a class and not a struct, the object is passed by reference, which means that both obj and someTestObj refer to the same object. E.g. changing name in one will change it in the other. However, unlike if you passed it using the ref keyword, setting obj = somethingElse will not change someTestObj.

Storing Data in MySQL as JSON

This is an old question, but I am still able to see this at the top of the search result of Google, so I guess it would be meaningful to add a new answer 4 years after the question is asked.

First of all, there is better support in storing JSON in RDBMS. You may consider switching to PostgreSQL (although MySQL has supported JSON since v5.7.7). PostgreSQL uses very similar SQL commands as MySQL except they support more functions. One of the functions they added is that they provide JSON data type and you are now able to query the JSON stored. (Some reference on this) If you are not making up the query directly in your program, for example, using PDO in php or eloquent in Laravel, all you need to do is just to install PostgreSQL on your server and change database connection settings. You don't even need to change your code.

Most of the time, as the other answers suggested, storing data as JSON directly in RDBMS is not a good idea. There are some exception though. One situation I can think of is a field with variable number of linked entry.

For example, for storing tag of a blog post, normally you will need to have a table for blog post, a table of tag and a matching table. So, when the user wants to edit a post and you need to display which tag is related to that post, you will need to query 3 tables. This will damage the performance a lot if your matching table / tag table is long.

By storing the tags as JSON in the blog post table, the same action only requires a single table search. The user will then be able to see the blog post to be edit quicker, but this will damage the performance if you want to make a report on what post is linked to a tag, or maybe search by tag.

You may also try to de-normalize the database. By duplicating the data and storing the data in both ways, you can receive benefit of both method. You will just need a little bit more time to store your data and more storage space (which is cheap comparing to the cost of more computing power)

Check if a row exists, otherwise insert

I assume a single row for each flight? If so:

IF EXISTS (SELECT * FROM Bookings WHERE FLightID = @Id)
BEGIN
    --UPDATE HERE
END
ELSE
BEGIN
   -- INSERT HERE
END

I assume what I said, as your way of doing things can overbook a flight, as it will insert a new row when there are 10 tickets max and you are booking 20.

Can't find file executable in your configured search path for gnc gcc compiler

For that you need to install binary of GNU GCC compiler, which comes with MinGW package. You can download MinGW( and put it under C:/ ) and later you have to download gnu -c, c++ related Binaries, so select required package and install them(in the MinGW ). Then in the Code::Blocks, go to Setting, Compiler, ToolChain Executable. In that you will find Path, there set C:/MinGW. Then mentioned error will be vanished.

What's the use of session.flush() in Hibernate

As rightly said in above answers, by calling flush() we force hibernate to execute the SQL commands on Database. But do understand that changes are not "committed" yet. So after doing flush and before doing commit, if you access DB directly (say from SQL prompt) and check the modified rows, you will NOT see the changes.

This is same as opening 2 SQL command sessions. And changes done in 1 session are not visible to others until committed.

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

JavaScript single line 'if' statement - best syntax, this alternative?

As a lot of people have said, if you're looking for an actual 1 line if then:

    if (Boolean_expression) do.something();

is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):

    (Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();

ALSO:

    var something = (Boolean_expression) ? trueValueHardware : falseATRON;

However, I saw one very cool example. Shouts to @Peter-Oslson for &&

    (Boolean_expression) && do.something();

Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan

Add left/right horizontal padding to UILabel

Swift 5

Create below class file and set it to your label as custom class name through storyboard. That's it.

class PaddingLabel: UILabel {

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)//CGRect.inset(by:)
        super.drawText(in: rect.inset(by: insets))
    }
}

Check a collection size with JSTL

You can use like this

${fn:length(numList)}

Resource files not found from JUnit test cases

This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.

You can verify that by checking your effective POM using this command

mvn help:effective-pom

    <finalName>name</finalName>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.

    <resources>
        <resource>
            <directory>/home/josh/desktop/app_resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>/home/josh/desktop/test_resources</directory>
        </testResource>
    </testResources>

How to test an Internet connection with bash?

I've written scripts before that simply use telnet to connect to port 80, then transmit the text:

HTTP/1.0 GET /index.html

followed by two CR/LF sequences.

Provided you get back some form of HTTP response, you can generally assume the site is functioning.

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

I've had this problem. See The Python "Connection Reset By Peer" Problem.

You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.

You can (sometimes) correct this with a time.sleep(0.01) placed strategically.

"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.

How do you know if Tomcat Server is installed on your PC

In order to make

     http://localhost:8080

work, tomcat has to be started first. You can check server.xml file in conf folder for the port information. You can search if tomcat is installed on your machine. Just go to start and then type tomcat. If it is installed it will give you the directory where it is installed. Then you can select that path and run it from command prompt. Example if tomcat is installed in C:\Programfile\tomcat. You need to set this path in command prompt,go to bin folder and startup. Example: C:\Programfile\tomcat\bin\startup. Else you can also run it by directly going to the path and run startup batch file.

scp from Linux to Windows

For all, who has installed GiT completly with "Git Bash": You can just write:

scp login@ip_addres:/location/to/folders/file.tar .

(with space and DOT at the end to copy to current location). Than just add certificate (y), write password and that's all.

Bootstrap 4 Dropdown Menu not working?

It's an issue with popper.js file. What I found at the official site was that bundle files include popper in itself but not jquery. I managed to fix it by adding link to these files:

bootstrap.bundle.js
bootstrap.bundle.min.js

I removed popper.js however since it comes within the bundle file.

Convert named list to vector with values only

Use unlist with use.names = FALSE argument.

unlist(myList, use.names=FALSE)

Loop through files in a directory using PowerShell

Other answers are great, I just want to add... a different approach usable in PowerShell: Install GNUWin32 utils and use grep to view the lines / redirect the output to file http://gnuwin32.sourceforge.net/

This overwrites the new file every time:

grep "step[49]" logIn.log > logOut.log 

This appends the log output, in case you overwrite the logIn file and want to keep the data:

grep "step[49]" logIn.log >> logOut.log 

Note: to be able to use GNUWin32 utils globally you have to add the bin folder to your system path.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

Guys in my case none of the solutions above worked.

I had to delete the files within the Project workspace:

  • .project
  • .classpath

And the folder:

  • .settings

Then I copied the ones from a similar project that was working before. This managed to fix my broken project.

Of course do not use this method before trying the previous alternatives!.

How to return dictionary keys as a list in Python?

Python >= 3.5 alternative: unpack into a list literal [*newdict]

New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:

>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]

Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.

Adding .keys() i.e [*newdict.keys()] might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).

The *iterable syntax is similar to doing list(iterable) and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.


Though equivalent to list(newdict) with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:

%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop

%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop

%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop

with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).


In a similar fashion, you can create tuples and sets of dictionary keys:

>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}

beware of the trailing comma in the tuple case!

VS 2017 Git Local Commit DB.lock error on every commit

if you are using an IDE like visual studio and it is open while you sending commands close IDE and try again

git add .

and other commands, it will workout

CodeIgniter - how to catch DB errors?

Use it

    $this->db->_error_message(); 

It is better for finding error.After completing your site. Close the error messages using it

    $db['default']['db_debug'] = FALSE;

You will change it in your config folder's database.php

How can I delete Docker's images?

The reason for the error is that even though the image did not have any tag, there still exists a container created on that image which might be in the exited state. So you need to ensure that you have stopped and deleted all containers created on those images. The following command helps you in removing all containers that are not running:

docker rm `docker ps -aq --no-trunc --filter "status=exited"`

Now this removes all the dangling non-intermediate <none> images:

docker rmi `docker images --filter 'dangling=true' -q --no-trunc`

Note: To stops all running containers:

docker stop `docker ps -q`

What is the difference between Scala's case class and class?

No one mentioned that case classes have val constructor parameters yet this is also the default for regular classes (which I think is an inconsistency in the design of Scala). Dario implied such where he noted they are "immutable".

Note you can override the default by prepending the each constructor argument with var for case classes. However, making case classes mutable causes their equals and hashCode methods to be time variant.[1]

sepp2k already mentioned that case classes automatically generate equals and hashCode methods.

Also no one mentioned that case classes automatically create a companion object with the same name as the class, which contains apply and unapply methods. The apply method enables constructing instances without prepending with new. The unapply extractor method enables the pattern matching that others mentioned.

Also the compiler optimizes the speed of match-case pattern matching for case classes[2].

[1] Case Classes Are Cool

[2] Case Classes and Extractors, pg 15.

Determine the process pid listening on a certain port

netstat -nlp should tell you the PID of what's listening on which port.

Check if a time is between two times (time DataType)

select * from dbMaster oMaster  where ((CAST(GETDATE() as time)) between  (CAST(oMaster.DateFrom as time))  and  
(CAST(oMaster.DateTo as time)))

Please check this

How do I format a date with Dart?

This will work too:

DateTime today = new DateTime.now();
String dateSlug ="${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
print(dateSlug);

Angular - ui-router get previous state

In the following example i created a decorator (runs only once per app at configuration phase) and adds an extra property to $state service, so this approach does not add global variables to $rootscope and does not require to add any extra dependency to other services than $state.

In my example i needed to redirect a user to the index page when he was already signed in and when he was not to redirect him to the previous "protected" page after sign in.

The only unknown services (for you) that i use are authenticationFactory and appSettings:

  • authenticationFactory just administrates the user login. In this case i use only a method to identify if the user is logged in or not.
  • appSettings are constants just for not use strings everywhere. appSettings.states.login and appSettings.states.register contain the name of the state for the login and register url.

Then in any controller/service etc you need to inject $state service and you can access current and previous url like this:

  • Current: $state.current.name
  • Previous: $state.previous.route.name

From the Chrome console:

var injector = angular.element(document.body).injector();
var $state = injector.get("$state");
$state.current.name;
$state.previous.route.name;

Implementation:

(I'm using angular-ui-router v0.2.17 and angularjs v1.4.9)

(function(angular) {
    "use strict";

    function $stateDecorator($delegate, $injector, $rootScope, appSettings) {
        function decorated$State() {
            var $state = $delegate;
            $state.previous = undefined;
            $rootScope.$on("$stateChangeSuccess", function (ev, to, toParams, from, fromParams) {
                $state.previous = { route: from, routeParams: fromParams }
            });

            $rootScope.$on("$stateChangeStart", function (event, toState/*, toParams, fromState, fromParams*/) {
                var authenticationFactory = $injector.get("authenticationFactory");
                if ((toState.name === appSettings.states.login || toState.name === appSettings.states.register) && authenticationFactory.isUserLoggedIn()) {
                    event.preventDefault();
                    $state.go(appSettings.states.index);
                }
            });

            return $state;
        }

        return decorated$State();
    }

    $stateDecorator.$inject = ["$delegate", "$injector", "$rootScope", "appSettings"];

    angular
        .module("app.core")
        .decorator("$state", $stateDecorator);
})(angular);

Retrieving the last record in each group - MySQL

You can group by counting and also get the last item of group like:

SELECT 
    user,
    COUNT(user) AS count,
    MAX(id) as last
FROM request 
GROUP BY user

Format a datetime into a string with milliseconds

Probably like this :

import datetime
now = datetime.datetime.now()
now.strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]  
# [:-3] => Removing the 3 last characters as %f is for microsecs.

How to convert byte array to string

You can do it without dealing with encoding by using BlockCopy:

char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);

Removing an item from a select box

Remove an option:

_x000D_
_x000D_
$("#selectBox option[value='option1']").remove();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

Add an option:

_x000D_
_x000D_
$("#selectBox").append('<option value="option5">option5</option>');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

Show SOME invisible/whitespace characters in Eclipse

I use Checkstlye plugin for such a purpose. In Checkstyle configuration, I add special regexp rules to detect lines with TABs and then mark such lines as checkstyle ERROR, which is clearly visible in Eclipse editor. Works fine.

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

Sort a Custom Class List<T>

You can use linq:

var q = from tag in Week orderby Convert.ToDateTime(tag.date) select tag;
List<cTag> Sorted = q.ToList()

What does "-ne" mean in bash?

"not equal" So in this case, $RESULT is tested to not be equal to zero.

However, the test is done numerically, not alphabetically:

n1 -ne n2     True if the integers n1 and n2 are not algebraically equal.

compared to:

s1 != s2      True if the strings s1 and s2 are not identical.

What does a just-in-time (JIT) compiler do?

In the beginning, a compiler was responsible for turning a high-level language (defined as higher level than assembler) into object code (machine instructions), which would then be linked (by a linker) into an executable.

At one point in the evolution of languages, compilers would compile a high-level language into pseudo-code, which would then be interpreted (by an interpreter) to run your program. This eliminated the object code and executables, and allowed these languages to be portable to multiple operating systems and hardware platforms. Pascal (which compiled to P-Code) was one of the first; Java and C# are more recent examples. Eventually the term P-Code was replaced with bytecode, since most of the pseudo-operations are a byte long.

A Just-In-Time (JIT) compiler is a feature of the run-time interpreter, that instead of interpreting bytecode every time a method is invoked, will compile the bytecode into the machine code instructions of the running machine, and then invoke this object code instead. Ideally the efficiency of running object code will overcome the inefficiency of recompiling the program every time it runs.

Quickest way to compare two generic lists for differences

Use Except:

var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();

I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach.

If you want to combine these, you could create a method with the above and then a return statement:

return !firstNotSecond.Any() && !secondNotFirst.Any();

One point to note is that there is a difference in results between the original code in the question and the solution here: any duplicate elements which are only in one list will only be reported once with my code, whereas they'd be reported as many times as they occur in the original code.

For example, with lists of [1, 2, 2, 2, 3] and [1], the "elements in list1 but not list2" result in the original code would be [2, 2, 2, 3]. With my code it would just be [2, 3]. In many cases that won't be an issue, but it's worth being aware of.

Convert String to Uri

I am just using the java.net package. Here you can do the following:

...
import java.net.URI;
...

String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);

Clang vs GCC - which produces faster binaries?

Basically speaking, the answer is: it depends. There are many many benchmarks focusing on different kinds of application.

My benchmark on my app is: gcc > icc > clang.

There are rare IO, but many CPU float and data structure operations.

compile flags is -Wall -g -DNDEBUG -O3.

https://github.com/zhangyafeikimi/ml-pack/blob/master/gbdt/profile/benchmark

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Great explanation here:
https://www.cuelogic.com/blog/using-framelayout-for-designing-xml-layouts-in-android

LinearLayout arranges elements side by side either horizontally or vertically.

RelativeLayout helps you arrange your UI elements based on specific rules. You can specify rules like: align this to parent’s left edge, place this to the left/right of this elements etc.

AbsoluteLayout is for absolute positioning i.e. you can specify exact co-ordinates where the view should go.

FrameLayout allows placements of views along Z-axis. That means that you can stack your view elements one above the other.