Programs & Examples On #Keyboard hook

Global keyboard capture in C# application

Here's my code that works:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace SnagFree.TrayApp.Core
{
    class GlobalKeyboardHookEventArgs : HandledEventArgs
    {
        public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
        public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

        public GlobalKeyboardHookEventArgs(
            GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
            GlobalKeyboardHook.KeyboardState keyboardState)
        {
            KeyboardData = keyboardData;
            KeyboardState = keyboardState;
        }
    }

    //Based on https://gist.github.com/Stasonix
    class GlobalKeyboardHook : IDisposable
    {
        public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

        public GlobalKeyboardHook()
        {
            _windowsHookHandle = IntPtr.Zero;
            _user32LibraryHandle = IntPtr.Zero;
            _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

            _user32LibraryHandle = LoadLibrary("User32");
            if (_user32LibraryHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }



            _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
            if (_windowsHookHandle == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // because we can unhook only in the same thread, not in garbage collector thread
                if (_windowsHookHandle != IntPtr.Zero)
                {
                    if (!UnhookWindowsHookEx(_windowsHookHandle))
                    {
                        int errorCode = Marshal.GetLastWin32Error();
                        throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                    }
                    _windowsHookHandle = IntPtr.Zero;

                    // ReSharper disable once DelegateSubtraction
                    _hookProc -= LowLevelKeyboardProc;
                }
            }

            if (_user32LibraryHandle != IntPtr.Zero)
            {
                if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _user32LibraryHandle = IntPtr.Zero;
            }
        }

        ~GlobalKeyboardHook()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private IntPtr _windowsHookHandle;
        private IntPtr _user32LibraryHandle;
        private HookProc _hookProc;

        delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll")]
        private static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool FreeLibrary(IntPtr hModule);

        /// <summary>
        /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
        /// You would install a hook procedure to monitor the system for certain types of events. These events are
        /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
        /// </summary>
        /// <param name="idHook">hook type</param>
        /// <param name="lpfn">hook procedure</param>
        /// <param name="hMod">handle to application instance</param>
        /// <param name="dwThreadId">thread identifier</param>
        /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

        /// <summary>
        /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
        /// </summary>
        /// <param name="hhk">handle to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        public static extern bool UnhookWindowsHookEx(IntPtr hHook);

        /// <summary>
        /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
        /// A hook procedure can call this function either before or after processing the hook information.
        /// </summary>
        /// <param name="hHook">handle to current hook</param>
        /// <param name="code">hook code passed to hook procedure</param>
        /// <param name="wParam">value passed to hook procedure</param>
        /// <param name="lParam">value passed to hook procedure</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("USER32", SetLastError = true)]
        static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

        [StructLayout(LayoutKind.Sequential)]
        public struct LowLevelKeyboardInputEvent
        {
            /// <summary>
            /// A virtual-key code. The code must be a value in the range 1 to 254.
            /// </summary>
            public int VirtualCode;

            /// <summary>
            /// A hardware scan code for the key. 
            /// </summary>
            public int HardwareScanCode;

            /// <summary>
            /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
            /// </summary>
            public int Flags;

            /// <summary>
            /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
            /// </summary>
            public int TimeStamp;

            /// <summary>
            /// Additional information associated with the message. 
            /// </summary>
            public IntPtr AdditionalInformation;
        }

        public const int WH_KEYBOARD_LL = 13;
        //const int HC_ACTION = 0;

        public enum KeyboardState
        {
            KeyDown = 0x0100,
            KeyUp = 0x0101,
            SysKeyDown = 0x0104,
            SysKeyUp = 0x0105
        }

        public const int VkSnapshot = 0x2c;
        //const int VkLwin = 0x5b;
        //const int VkRwin = 0x5c;
        //const int VkTab = 0x09;
        //const int VkEscape = 0x18;
        //const int VkControl = 0x11;
        const int KfAltdown = 0x2000;
        public const int LlkhfAltdown = (KfAltdown >> 8);

        public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            bool fEatKeyStroke = false;

            var wparamTyped = wParam.ToInt32();
            if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
            {
                object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
                LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

                var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }

            return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
        }
    }
}

Usage:

using System;
using System.Windows.Forms;

namespace SnagFree.TrayApp.Core
{
    internal class Controller : IDisposable
    {
        private GlobalKeyboardHook _globalKeyboardHook;

        public void SetupKeyboardHooks()
        {
            _globalKeyboardHook = new GlobalKeyboardHook();
            _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
        }

        private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
        {
            //Debug.WriteLine(e.KeyboardData.VirtualCode);

            if (e.KeyboardData.VirtualCode != GlobalKeyboardHook.VkSnapshot)
                return;

            // seems, not needed in the life.
            //if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.SysKeyDown &&
            //    e.KeyboardData.Flags == GlobalKeyboardHook.LlkhfAltdown)
            //{
            //    MessageBox.Show("Alt + Print Screen");
            //    e.Handled = true;
            //}
            //else

            if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
            {
                MessageBox.Show("Print Screen");
                e.Handled = true;
            }
        }

        public void Dispose()
        {
            _globalKeyboardHook?.Dispose();
        }
    }
}

What does "@" mean in Windows batch scripts

The @ disables echo for that one command. Without it, the echo start eclipse.exe line would print both the intended start eclipse.exe and the echo start eclipse.exe line.

The echo off turns off the by-default command echoing.

So @echo off silently turns off command echoing, and only output the batch author intended to be written is actually written.

Difference between drop table and truncate table?

The answers here match up to the question, but I'm going to answer the question you didn't ask. "Should I use truncate or delete?" If you are removing all rows from a table, you'll typically want to truncate, since it's much much faster. Why is it much faster? At least in the case of Oracle, it resets the high water mark. This is basically a dereferencing of the data and allows the db to reuse it for something else.

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

I personally wouldn't try grabbing it inside of the view. I'm not amazing at Laravel, but I would imagine you'd need to send your route to a controller, and then within the controller, pass the variable (via an array) into your view, using something like $url = Request::url();.

One way of doing it anyway.

EDIT: Actually look at the method above, probably a better way.

How do you properly return multiple values from a Promise?

Whatever you return from a promise will be wrapped into a promise to be unwrapped at the next .then() stage.

It becomes interesting when you need to return one or more promise(s) alongside one or more synchronous value(s) such as;

Promise.resolve([Promise.resolve(1), Promise.resolve(2), 3, 4])
       .then(([p1,p2,n1,n2]) => /* p1 and p2 are still promises */);

In these cases it would be essential to use Promise.all() to get p1 and p2 promises unwrapped at the next .then() stage such as

Promise.resolve(Promise.all([Promise.resolve(1), Promise.resolve(2), 3, 4]))
       .then(([p1,p2,n1,n2]) => /* p1 is 1, p2 is 2, n1 is 3 and n2 is 4 */);

Model backing a DB Context has changed; Consider Code First Migrations

This happens when your table structure and model class no longer in sync. You need to update the table structure according to the model class or vice versa -- this is when your data is important and must not be deleted. If your data structure has changed and the data isn't important to you, you can use the DropCreateDatabaseIfModelChanges feature (formerly known as 'RecreateDatabaseIfModelChanges' feature) by adding the following code in your Global.asax.cs:

Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());

Run your application again.

As the name implies, this will drop your database and recreate according to your latest model class (or classes) -- provided you believe the table structure definitions in your model classes are the most current and latest; otherwise change the property definitions of your model classes instead.

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

Convert String into a Class Object

Class.forName(nameString).newInstance();

Convert array of strings into a string in Java

Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:

String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);

Produces:

a-b-1

How to redirect on another page and pass parameter in url from table?

Bind the button, this is done with jQuery:

$("#my-table input[type='button']").click(function(){
    var parameter = $(this).val();
    window.location = "http://yoursite.com/page?variable=" + parameter;
});

Function to Calculate a CRC16 Checksum

crcany will generate efficient C code for any CRC, and includes a library of over one hundred known CRC definitions.

Efficient CRC code uses tables instead of bit-wise calculations. crcany generates both byte-wise routines and word-wise routines, the latter tuned to the architecture they are generated on. Word-wise is the fastest. Byte-wise is still much faster than bit-wise, but the implementation is more easily portable over architectures.

You do not seem to have a protocol definition with a specific CRC definition that you need to match. In this case, you can pick any 16-bit CRC in the catalog, and you will get good performance.

If you have a relatively low bit error rate, e.g. single digit number of errors per packet, and you want to maximize your error detection performance, you would need to look at the packet size you are applying the CRC to, assuming that that is constant or bounded, and look at the performance of the best polynomials in Philip Koopman's extensive research. The classic CRCs, such as the CCITT/Kermit 16-bit CRC or the X.25 16-bit CRC are not the best performers.

One of the good 16-bit performers in Koopman's tables that is also in the catalog of CRCs used in practice is CRC-16/DNP. It has very good performance detecting up to 6-bit errors in a packet. Following is the code generated by crcany for that CRC definition. This code assumes a little-endian architecture for the word-wise calculation, e.g. Intel x86 and x86-64, and it assumes that uintmax_t is 64 bits. crcany can be used to generate alternative code for big-endian and other word sizes.

crc16dnp.h:

// The _bit, _byte, and _word routines return the CRC of the len bytes at mem,
// applied to the previous CRC value, crc. If mem is NULL, then the other
// arguments are ignored, and the initial CRC, i.e. the CRC of zero bytes, is
// returned. Those routines will all return the same result, differing only in
// speed and code complexity. The _rem routine returns the CRC of the remaining
// bits in the last byte, for when the number of bits in the message is not a
// multiple of eight. The low bits bits of the low byte of val are applied to
// crc. bits must be in 0..8.

#include <stddef.h>

// Compute the CRC a bit at a time.
unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len);

// Compute the CRC of the low bits bits in val.
unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits);

// Compute the CRC a byte at a time.
unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len);

// Compute the CRC a word at a time.
unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len);

crc16dnp.c:

#include <stdint.h>
#include "crc16dnp.h"

// This code assumes that unsigned is 4 bytes.

unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc = ~crc;
    crc &= 0xffff;
    while (len--) {
        crc ^= *data++;
        for (unsigned k = 0; k < 8; k++)
            crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    }
    crc ^= 0xffff;
    return crc;
}

unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits) {
    crc = ~crc;
    crc &= 0xffff;
    val &= (1U << bits) - 1;
    crc ^= val;
    while (bits--)
        crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    crc ^= 0xffff;
    return crc;
}

#define table_byte table_word[0]

static unsigned short const table_word[][256] = {
   {0xed35, 0xdb6b, 0x8189, 0xb7d7, 0x344d, 0x0213, 0x58f1, 0x6eaf, 0x12bc, 0x24e2,
    0x7e00, 0x485e, 0xcbc4, 0xfd9a, 0xa778, 0x9126, 0x5f5e, 0x6900, 0x33e2, 0x05bc,
    0x8626, 0xb078, 0xea9a, 0xdcc4, 0xa0d7, 0x9689, 0xcc6b, 0xfa35, 0x79af, 0x4ff1,
    0x1513, 0x234d, 0xc49a, 0xf2c4, 0xa826, 0x9e78, 0x1de2, 0x2bbc, 0x715e, 0x4700,
    0x3b13, 0x0d4d, 0x57af, 0x61f1, 0xe26b, 0xd435, 0x8ed7, 0xb889, 0x76f1, 0x40af,
    0x1a4d, 0x2c13, 0xaf89, 0x99d7, 0xc335, 0xf56b, 0x8978, 0xbf26, 0xe5c4, 0xd39a,
    0x5000, 0x665e, 0x3cbc, 0x0ae2, 0xbe6b, 0x8835, 0xd2d7, 0xe489, 0x6713, 0x514d,
    0x0baf, 0x3df1, 0x41e2, 0x77bc, 0x2d5e, 0x1b00, 0x989a, 0xaec4, 0xf426, 0xc278,
    0x0c00, 0x3a5e, 0x60bc, 0x56e2, 0xd578, 0xe326, 0xb9c4, 0x8f9a, 0xf389, 0xc5d7,
    0x9f35, 0xa96b, 0x2af1, 0x1caf, 0x464d, 0x7013, 0x97c4, 0xa19a, 0xfb78, 0xcd26,
    0x4ebc, 0x78e2, 0x2200, 0x145e, 0x684d, 0x5e13, 0x04f1, 0x32af, 0xb135, 0x876b,
    0xdd89, 0xebd7, 0x25af, 0x13f1, 0x4913, 0x7f4d, 0xfcd7, 0xca89, 0x906b, 0xa635,
    0xda26, 0xec78, 0xb69a, 0x80c4, 0x035e, 0x3500, 0x6fe2, 0x59bc, 0x4b89, 0x7dd7,
    0x2735, 0x116b, 0x92f1, 0xa4af, 0xfe4d, 0xc813, 0xb400, 0x825e, 0xd8bc, 0xeee2,
    0x6d78, 0x5b26, 0x01c4, 0x379a, 0xf9e2, 0xcfbc, 0x955e, 0xa300, 0x209a, 0x16c4,
    0x4c26, 0x7a78, 0x066b, 0x3035, 0x6ad7, 0x5c89, 0xdf13, 0xe94d, 0xb3af, 0x85f1,
    0x6226, 0x5478, 0x0e9a, 0x38c4, 0xbb5e, 0x8d00, 0xd7e2, 0xe1bc, 0x9daf, 0xabf1,
    0xf113, 0xc74d, 0x44d7, 0x7289, 0x286b, 0x1e35, 0xd04d, 0xe613, 0xbcf1, 0x8aaf,
    0x0935, 0x3f6b, 0x6589, 0x53d7, 0x2fc4, 0x199a, 0x4378, 0x7526, 0xf6bc, 0xc0e2,
    0x9a00, 0xac5e, 0x18d7, 0x2e89, 0x746b, 0x4235, 0xc1af, 0xf7f1, 0xad13, 0x9b4d,
    0xe75e, 0xd100, 0x8be2, 0xbdbc, 0x3e26, 0x0878, 0x529a, 0x64c4, 0xaabc, 0x9ce2,
    0xc600, 0xf05e, 0x73c4, 0x459a, 0x1f78, 0x2926, 0x5535, 0x636b, 0x3989, 0x0fd7,
    0x8c4d, 0xba13, 0xe0f1, 0xd6af, 0x3178, 0x0726, 0x5dc4, 0x6b9a, 0xe800, 0xde5e,
    0x84bc, 0xb2e2, 0xcef1, 0xf8af, 0xa24d, 0x9413, 0x1789, 0x21d7, 0x7b35, 0x4d6b,
    0x8313, 0xb54d, 0xefaf, 0xd9f1, 0x5a6b, 0x6c35, 0x36d7, 0x0089, 0x7c9a, 0x4ac4,
    0x1026, 0x2678, 0xa5e2, 0x93bc, 0xc95e, 0xff00},
   {0x740f, 0xdf41, 0x6fea, 0xc4a4, 0x43c5, 0xe88b, 0x5820, 0xf36e, 0x1b9b, 0xb0d5,
    0x007e, 0xab30, 0x2c51, 0x871f, 0x37b4, 0x9cfa, 0xab27, 0x0069, 0xb0c2, 0x1b8c,
    0x9ced, 0x37a3, 0x8708, 0x2c46, 0xc4b3, 0x6ffd, 0xdf56, 0x7418, 0xf379, 0x5837,
    0xe89c, 0x43d2, 0x8726, 0x2c68, 0x9cc3, 0x378d, 0xb0ec, 0x1ba2, 0xab09, 0x0047,
    0xe8b2, 0x43fc, 0xf357, 0x5819, 0xdf78, 0x7436, 0xc49d, 0x6fd3, 0x580e, 0xf340,
    0x43eb, 0xe8a5, 0x6fc4, 0xc48a, 0x7421, 0xdf6f, 0x379a, 0x9cd4, 0x2c7f, 0x8731,
    0x0050, 0xab1e, 0x1bb5, 0xb0fb, 0xdf24, 0x746a, 0xc4c1, 0x6f8f, 0xe8ee, 0x43a0,
    0xf30b, 0x5845, 0xb0b0, 0x1bfe, 0xab55, 0x001b, 0x877a, 0x2c34, 0x9c9f, 0x37d1,
    0x000c, 0xab42, 0x1be9, 0xb0a7, 0x37c6, 0x9c88, 0x2c23, 0x876d, 0x6f98, 0xc4d6,
    0x747d, 0xdf33, 0x5852, 0xf31c, 0x43b7, 0xe8f9, 0x2c0d, 0x8743, 0x37e8, 0x9ca6,
    0x1bc7, 0xb089, 0x0022, 0xab6c, 0x4399, 0xe8d7, 0x587c, 0xf332, 0x7453, 0xdf1d,
    0x6fb6, 0xc4f8, 0xf325, 0x586b, 0xe8c0, 0x438e, 0xc4ef, 0x6fa1, 0xdf0a, 0x7444,
    0x9cb1, 0x37ff, 0x8754, 0x2c1a, 0xab7b, 0x0035, 0xb09e, 0x1bd0, 0x6f20, 0xc46e,
    0x74c5, 0xdf8b, 0x58ea, 0xf3a4, 0x430f, 0xe841, 0x00b4, 0xabfa, 0x1b51, 0xb01f,
    0x377e, 0x9c30, 0x2c9b, 0x87d5, 0xb008, 0x1b46, 0xabed, 0x00a3, 0x87c2, 0x2c8c,
    0x9c27, 0x3769, 0xdf9c, 0x74d2, 0xc479, 0x6f37, 0xe856, 0x4318, 0xf3b3, 0x58fd,
    0x9c09, 0x3747, 0x87ec, 0x2ca2, 0xabc3, 0x008d, 0xb026, 0x1b68, 0xf39d, 0x58d3,
    0xe878, 0x4336, 0xc457, 0x6f19, 0xdfb2, 0x74fc, 0x4321, 0xe86f, 0x58c4, 0xf38a,
    0x74eb, 0xdfa5, 0x6f0e, 0xc440, 0x2cb5, 0x87fb, 0x3750, 0x9c1e, 0x1b7f, 0xb031,
    0x009a, 0xabd4, 0xc40b, 0x6f45, 0xdfee, 0x74a0, 0xf3c1, 0x588f, 0xe824, 0x436a,
    0xab9f, 0x00d1, 0xb07a, 0x1b34, 0x9c55, 0x371b, 0x87b0, 0x2cfe, 0x1b23, 0xb06d,
    0x00c6, 0xab88, 0x2ce9, 0x87a7, 0x370c, 0x9c42, 0x74b7, 0xdff9, 0x6f52, 0xc41c,
    0x437d, 0xe833, 0x5898, 0xf3d6, 0x3722, 0x9c6c, 0x2cc7, 0x8789, 0x00e8, 0xaba6,
    0x1b0d, 0xb043, 0x58b6, 0xf3f8, 0x4353, 0xe81d, 0x6f7c, 0xc432, 0x7499, 0xdfd7,
    0xe80a, 0x4344, 0xf3ef, 0x58a1, 0xdfc0, 0x748e, 0xc425, 0x6f6b, 0x879e, 0x2cd0,
    0x9c7b, 0x3735, 0xb054, 0x1b1a, 0xabb1, 0x00ff},
   {0x7c67, 0x65df, 0x4f17, 0x56af, 0x1a87, 0x033f, 0x29f7, 0x304f, 0xb1a7, 0xa81f,
    0x82d7, 0x9b6f, 0xd747, 0xceff, 0xe437, 0xfd8f, 0xaa9e, 0xb326, 0x99ee, 0x8056,
    0xcc7e, 0xd5c6, 0xff0e, 0xe6b6, 0x675e, 0x7ee6, 0x542e, 0x4d96, 0x01be, 0x1806,
    0x32ce, 0x2b76, 0x9cec, 0x8554, 0xaf9c, 0xb624, 0xfa0c, 0xe3b4, 0xc97c, 0xd0c4,
    0x512c, 0x4894, 0x625c, 0x7be4, 0x37cc, 0x2e74, 0x04bc, 0x1d04, 0x4a15, 0x53ad,
    0x7965, 0x60dd, 0x2cf5, 0x354d, 0x1f85, 0x063d, 0x87d5, 0x9e6d, 0xb4a5, 0xad1d,
    0xe135, 0xf88d, 0xd245, 0xcbfd, 0xf008, 0xe9b0, 0xc378, 0xdac0, 0x96e8, 0x8f50,
    0xa598, 0xbc20, 0x3dc8, 0x2470, 0x0eb8, 0x1700, 0x5b28, 0x4290, 0x6858, 0x71e0,
    0x26f1, 0x3f49, 0x1581, 0x0c39, 0x4011, 0x59a9, 0x7361, 0x6ad9, 0xeb31, 0xf289,
    0xd841, 0xc1f9, 0x8dd1, 0x9469, 0xbea1, 0xa719, 0x1083, 0x093b, 0x23f3, 0x3a4b,
    0x7663, 0x6fdb, 0x4513, 0x5cab, 0xdd43, 0xc4fb, 0xee33, 0xf78b, 0xbba3, 0xa21b,
    0x88d3, 0x916b, 0xc67a, 0xdfc2, 0xf50a, 0xecb2, 0xa09a, 0xb922, 0x93ea, 0x8a52,
    0x0bba, 0x1202, 0x38ca, 0x2172, 0x6d5a, 0x74e2, 0x5e2a, 0x4792, 0x29c0, 0x3078,
    0x1ab0, 0x0308, 0x4f20, 0x5698, 0x7c50, 0x65e8, 0xe400, 0xfdb8, 0xd770, 0xcec8,
    0x82e0, 0x9b58, 0xb190, 0xa828, 0xff39, 0xe681, 0xcc49, 0xd5f1, 0x99d9, 0x8061,
    0xaaa9, 0xb311, 0x32f9, 0x2b41, 0x0189, 0x1831, 0x5419, 0x4da1, 0x6769, 0x7ed1,
    0xc94b, 0xd0f3, 0xfa3b, 0xe383, 0xafab, 0xb613, 0x9cdb, 0x8563, 0x048b, 0x1d33,
    0x37fb, 0x2e43, 0x626b, 0x7bd3, 0x511b, 0x48a3, 0x1fb2, 0x060a, 0x2cc2, 0x357a,
    0x7952, 0x60ea, 0x4a22, 0x539a, 0xd272, 0xcbca, 0xe102, 0xf8ba, 0xb492, 0xad2a,
    0x87e2, 0x9e5a, 0xa5af, 0xbc17, 0x96df, 0x8f67, 0xc34f, 0xdaf7, 0xf03f, 0xe987,
    0x686f, 0x71d7, 0x5b1f, 0x42a7, 0x0e8f, 0x1737, 0x3dff, 0x2447, 0x7356, 0x6aee,
    0x4026, 0x599e, 0x15b6, 0x0c0e, 0x26c6, 0x3f7e, 0xbe96, 0xa72e, 0x8de6, 0x945e,
    0xd876, 0xc1ce, 0xeb06, 0xf2be, 0x4524, 0x5c9c, 0x7654, 0x6fec, 0x23c4, 0x3a7c,
    0x10b4, 0x090c, 0x88e4, 0x915c, 0xbb94, 0xa22c, 0xee04, 0xf7bc, 0xdd74, 0xc4cc,
    0x93dd, 0x8a65, 0xa0ad, 0xb915, 0xf53d, 0xec85, 0xc64d, 0xdff5, 0x5e1d, 0x47a5,
    0x6d6d, 0x74d5, 0x38fd, 0x2145, 0x0b8d, 0x1235},
   {0xf917, 0x3bff, 0x31be, 0xf356, 0x253c, 0xe7d4, 0xed95, 0x2f7d, 0x0c38, 0xced0,
    0xc491, 0x0679, 0xd013, 0x12fb, 0x18ba, 0xda52, 0x5e30, 0x9cd8, 0x9699, 0x5471,
    0x821b, 0x40f3, 0x4ab2, 0x885a, 0xab1f, 0x69f7, 0x63b6, 0xa15e, 0x7734, 0xb5dc,
    0xbf9d, 0x7d75, 0xfa20, 0x38c8, 0x3289, 0xf061, 0x260b, 0xe4e3, 0xeea2, 0x2c4a,
    0x0f0f, 0xcde7, 0xc7a6, 0x054e, 0xd324, 0x11cc, 0x1b8d, 0xd965, 0x5d07, 0x9fef,
    0x95ae, 0x5746, 0x812c, 0x43c4, 0x4985, 0x8b6d, 0xa828, 0x6ac0, 0x6081, 0xa269,
    0x7403, 0xb6eb, 0xbcaa, 0x7e42, 0xff79, 0x3d91, 0x37d0, 0xf538, 0x2352, 0xe1ba,
    0xebfb, 0x2913, 0x0a56, 0xc8be, 0xc2ff, 0x0017, 0xd67d, 0x1495, 0x1ed4, 0xdc3c,
    0x585e, 0x9ab6, 0x90f7, 0x521f, 0x8475, 0x469d, 0x4cdc, 0x8e34, 0xad71, 0x6f99,
    0x65d8, 0xa730, 0x715a, 0xb3b2, 0xb9f3, 0x7b1b, 0xfc4e, 0x3ea6, 0x34e7, 0xf60f,
    0x2065, 0xe28d, 0xe8cc, 0x2a24, 0x0961, 0xcb89, 0xc1c8, 0x0320, 0xd54a, 0x17a2,
    0x1de3, 0xdf0b, 0x5b69, 0x9981, 0x93c0, 0x5128, 0x8742, 0x45aa, 0x4feb, 0x8d03,
    0xae46, 0x6cae, 0x66ef, 0xa407, 0x726d, 0xb085, 0xbac4, 0x782c, 0xf5cb, 0x3723,
    0x3d62, 0xff8a, 0x29e0, 0xeb08, 0xe149, 0x23a1, 0x00e4, 0xc20c, 0xc84d, 0x0aa5,
    0xdccf, 0x1e27, 0x1466, 0xd68e, 0x52ec, 0x9004, 0x9a45, 0x58ad, 0x8ec7, 0x4c2f,
    0x466e, 0x8486, 0xa7c3, 0x652b, 0x6f6a, 0xad82, 0x7be8, 0xb900, 0xb341, 0x71a9,
    0xf6fc, 0x3414, 0x3e55, 0xfcbd, 0x2ad7, 0xe83f, 0xe27e, 0x2096, 0x03d3, 0xc13b,
    0xcb7a, 0x0992, 0xdff8, 0x1d10, 0x1751, 0xd5b9, 0x51db, 0x9333, 0x9972, 0x5b9a,
    0x8df0, 0x4f18, 0x4559, 0x87b1, 0xa4f4, 0x661c, 0x6c5d, 0xaeb5, 0x78df, 0xba37,
    0xb076, 0x729e, 0xf3a5, 0x314d, 0x3b0c, 0xf9e4, 0x2f8e, 0xed66, 0xe727, 0x25cf,
    0x068a, 0xc462, 0xce23, 0x0ccb, 0xdaa1, 0x1849, 0x1208, 0xd0e0, 0x5482, 0x966a,
    0x9c2b, 0x5ec3, 0x88a9, 0x4a41, 0x4000, 0x82e8, 0xa1ad, 0x6345, 0x6904, 0xabec,
    0x7d86, 0xbf6e, 0xb52f, 0x77c7, 0xf092, 0x327a, 0x383b, 0xfad3, 0x2cb9, 0xee51,
    0xe410, 0x26f8, 0x05bd, 0xc755, 0xcd14, 0x0ffc, 0xd996, 0x1b7e, 0x113f, 0xd3d7,
    0x57b5, 0x955d, 0x9f1c, 0x5df4, 0x8b9e, 0x4976, 0x4337, 0x81df, 0xa29a, 0x6072,
    0x6a33, 0xa8db, 0x7eb1, 0xbc59, 0xb618, 0x74f0},
   {0x3108, 0x120e, 0x7704, 0x5402, 0xbd10, 0x9e16, 0xfb1c, 0xd81a, 0x6441, 0x4747,
    0x224d, 0x014b, 0xe859, 0xcb5f, 0xae55, 0x8d53, 0x9b9a, 0xb89c, 0xdd96, 0xfe90,
    0x1782, 0x3484, 0x518e, 0x7288, 0xced3, 0xedd5, 0x88df, 0xabd9, 0x42cb, 0x61cd,
    0x04c7, 0x27c1, 0x2955, 0x0a53, 0x6f59, 0x4c5f, 0xa54d, 0x864b, 0xe341, 0xc047,
    0x7c1c, 0x5f1a, 0x3a10, 0x1916, 0xf004, 0xd302, 0xb608, 0x950e, 0x83c7, 0xa0c1,
    0xc5cb, 0xe6cd, 0x0fdf, 0x2cd9, 0x49d3, 0x6ad5, 0xd68e, 0xf588, 0x9082, 0xb384,
    0x5a96, 0x7990, 0x1c9a, 0x3f9c, 0x01b2, 0x22b4, 0x47be, 0x64b8, 0x8daa, 0xaeac,
    0xcba6, 0xe8a0, 0x54fb, 0x77fd, 0x12f7, 0x31f1, 0xd8e3, 0xfbe5, 0x9eef, 0xbde9,
    0xab20, 0x8826, 0xed2c, 0xce2a, 0x2738, 0x043e, 0x6134, 0x4232, 0xfe69, 0xdd6f,
    0xb865, 0x9b63, 0x7271, 0x5177, 0x347d, 0x177b, 0x19ef, 0x3ae9, 0x5fe3, 0x7ce5,
    0x95f7, 0xb6f1, 0xd3fb, 0xf0fd, 0x4ca6, 0x6fa0, 0x0aaa, 0x29ac, 0xc0be, 0xe3b8,
    0x86b2, 0xa5b4, 0xb37d, 0x907b, 0xf571, 0xd677, 0x3f65, 0x1c63, 0x7969, 0x5a6f,
    0xe634, 0xc532, 0xa038, 0x833e, 0x6a2c, 0x492a, 0x2c20, 0x0f26, 0x507c, 0x737a,
    0x1670, 0x3576, 0xdc64, 0xff62, 0x9a68, 0xb96e, 0x0535, 0x2633, 0x4339, 0x603f,
    0x892d, 0xaa2b, 0xcf21, 0xec27, 0xfaee, 0xd9e8, 0xbce2, 0x9fe4, 0x76f6, 0x55f0,
    0x30fa, 0x13fc, 0xafa7, 0x8ca1, 0xe9ab, 0xcaad, 0x23bf, 0x00b9, 0x65b3, 0x46b5,
    0x4821, 0x6b27, 0x0e2d, 0x2d2b, 0xc439, 0xe73f, 0x8235, 0xa133, 0x1d68, 0x3e6e,
    0x5b64, 0x7862, 0x9170, 0xb276, 0xd77c, 0xf47a, 0xe2b3, 0xc1b5, 0xa4bf, 0x87b9,
    0x6eab, 0x4dad, 0x28a7, 0x0ba1, 0xb7fa, 0x94fc, 0xf1f6, 0xd2f0, 0x3be2, 0x18e4,
    0x7dee, 0x5ee8, 0x60c6, 0x43c0, 0x26ca, 0x05cc, 0xecde, 0xcfd8, 0xaad2, 0x89d4,
    0x358f, 0x1689, 0x7383, 0x5085, 0xb997, 0x9a91, 0xff9b, 0xdc9d, 0xca54, 0xe952,
    0x8c58, 0xaf5e, 0x464c, 0x654a, 0x0040, 0x2346, 0x9f1d, 0xbc1b, 0xd911, 0xfa17,
    0x1305, 0x3003, 0x5509, 0x760f, 0x789b, 0x5b9d, 0x3e97, 0x1d91, 0xf483, 0xd785,
    0xb28f, 0x9189, 0x2dd2, 0x0ed4, 0x6bde, 0x48d8, 0xa1ca, 0x82cc, 0xe7c6, 0xc4c0,
    0xd209, 0xf10f, 0x9405, 0xb703, 0x5e11, 0x7d17, 0x181d, 0x3b1b, 0x8740, 0xa446,
    0xc14c, 0xe24a, 0x0b58, 0x285e, 0x4d54, 0x6e52},
   {0xffb8, 0x4a5f, 0xd90f, 0x6ce8, 0xb2d6, 0x0731, 0x9461, 0x2186, 0x6564, 0xd083,
    0x43d3, 0xf634, 0x280a, 0x9ded, 0x0ebd, 0xbb5a, 0x8779, 0x329e, 0xa1ce, 0x1429,
    0xca17, 0x7ff0, 0xeca0, 0x5947, 0x1da5, 0xa842, 0x3b12, 0x8ef5, 0x50cb, 0xe52c,
    0x767c, 0xc39b, 0x0e3a, 0xbbdd, 0x288d, 0x9d6a, 0x4354, 0xf6b3, 0x65e3, 0xd004,
    0x94e6, 0x2101, 0xb251, 0x07b6, 0xd988, 0x6c6f, 0xff3f, 0x4ad8, 0x76fb, 0xc31c,
    0x504c, 0xe5ab, 0x3b95, 0x8e72, 0x1d22, 0xa8c5, 0xec27, 0x59c0, 0xca90, 0x7f77,
    0xa149, 0x14ae, 0x87fe, 0x3219, 0x51c5, 0xe422, 0x7772, 0xc295, 0x1cab, 0xa94c,
    0x3a1c, 0x8ffb, 0xcb19, 0x7efe, 0xedae, 0x5849, 0x8677, 0x3390, 0xa0c0, 0x1527,
    0x2904, 0x9ce3, 0x0fb3, 0xba54, 0x646a, 0xd18d, 0x42dd, 0xf73a, 0xb3d8, 0x063f,
    0x956f, 0x2088, 0xfeb6, 0x4b51, 0xd801, 0x6de6, 0xa047, 0x15a0, 0x86f0, 0x3317,
    0xed29, 0x58ce, 0xcb9e, 0x7e79, 0x3a9b, 0x8f7c, 0x1c2c, 0xa9cb, 0x77f5, 0xc212,
    0x5142, 0xe4a5, 0xd886, 0x6d61, 0xfe31, 0x4bd6, 0x95e8, 0x200f, 0xb35f, 0x06b8,
    0x425a, 0xf7bd, 0x64ed, 0xd10a, 0x0f34, 0xbad3, 0x2983, 0x9c64, 0xee3b, 0x5bdc,
    0xc88c, 0x7d6b, 0xa355, 0x16b2, 0x85e2, 0x3005, 0x74e7, 0xc100, 0x5250, 0xe7b7,
    0x3989, 0x8c6e, 0x1f3e, 0xaad9, 0x96fa, 0x231d, 0xb04d, 0x05aa, 0xdb94, 0x6e73,
    0xfd23, 0x48c4, 0x0c26, 0xb9c1, 0x2a91, 0x9f76, 0x4148, 0xf4af, 0x67ff, 0xd218,
    0x1fb9, 0xaa5e, 0x390e, 0x8ce9, 0x52d7, 0xe730, 0x7460, 0xc187, 0x8565, 0x3082,
    0xa3d2, 0x1635, 0xc80b, 0x7dec, 0xeebc, 0x5b5b, 0x6778, 0xd29f, 0x41cf, 0xf428,
    0x2a16, 0x9ff1, 0x0ca1, 0xb946, 0xfda4, 0x4843, 0xdb13, 0x6ef4, 0xb0ca, 0x052d,
    0x967d, 0x239a, 0x4046, 0xf5a1, 0x66f1, 0xd316, 0x0d28, 0xb8cf, 0x2b9f, 0x9e78,
    0xda9a, 0x6f7d, 0xfc2d, 0x49ca, 0x97f4, 0x2213, 0xb143, 0x04a4, 0x3887, 0x8d60,
    0x1e30, 0xabd7, 0x75e9, 0xc00e, 0x535e, 0xe6b9, 0xa25b, 0x17bc, 0x84ec, 0x310b,
    0xef35, 0x5ad2, 0xc982, 0x7c65, 0xb1c4, 0x0423, 0x9773, 0x2294, 0xfcaa, 0x494d,
    0xda1d, 0x6ffa, 0x2b18, 0x9eff, 0x0daf, 0xb848, 0x6676, 0xd391, 0x40c1, 0xf526,
    0xc905, 0x7ce2, 0xefb2, 0x5a55, 0x846b, 0x318c, 0xa2dc, 0x173b, 0x53d9, 0xe63e,
    0x756e, 0xc089, 0x1eb7, 0xab50, 0x3800, 0x8de7},
   {0xc20e, 0x9d6c, 0x7cca, 0x23a8, 0xf2ff, 0xad9d, 0x4c3b, 0x1359, 0xa3ec, 0xfc8e,
    0x1d28, 0x424a, 0x931d, 0xcc7f, 0x2dd9, 0x72bb, 0x01ca, 0x5ea8, 0xbf0e, 0xe06c,
    0x313b, 0x6e59, 0x8fff, 0xd09d, 0x6028, 0x3f4a, 0xdeec, 0x818e, 0x50d9, 0x0fbb,
    0xee1d, 0xb17f, 0x08ff, 0x579d, 0xb63b, 0xe959, 0x380e, 0x676c, 0x86ca, 0xd9a8,
    0x691d, 0x367f, 0xd7d9, 0x88bb, 0x59ec, 0x068e, 0xe728, 0xb84a, 0xcb3b, 0x9459,
    0x75ff, 0x2a9d, 0xfbca, 0xa4a8, 0x450e, 0x1a6c, 0xaad9, 0xf5bb, 0x141d, 0x4b7f,
    0x9a28, 0xc54a, 0x24ec, 0x7b8e, 0x1a95, 0x45f7, 0xa451, 0xfb33, 0x2a64, 0x7506,
    0x94a0, 0xcbc2, 0x7b77, 0x2415, 0xc5b3, 0x9ad1, 0x4b86, 0x14e4, 0xf542, 0xaa20,
    0xd951, 0x8633, 0x6795, 0x38f7, 0xe9a0, 0xb6c2, 0x5764, 0x0806, 0xb8b3, 0xe7d1,
    0x0677, 0x5915, 0x8842, 0xd720, 0x3686, 0x69e4, 0xd064, 0x8f06, 0x6ea0, 0x31c2,
    0xe095, 0xbff7, 0x5e51, 0x0133, 0xb186, 0xeee4, 0x0f42, 0x5020, 0x8177, 0xde15,
    0x3fb3, 0x60d1, 0x13a0, 0x4cc2, 0xad64, 0xf206, 0x2351, 0x7c33, 0x9d95, 0xc2f7,
    0x7242, 0x2d20, 0xcc86, 0x93e4, 0x42b3, 0x1dd1, 0xfc77, 0xa315, 0x3e41, 0x6123,
    0x8085, 0xdfe7, 0x0eb0, 0x51d2, 0xb074, 0xef16, 0x5fa3, 0x00c1, 0xe167, 0xbe05,
    0x6f52, 0x3030, 0xd196, 0x8ef4, 0xfd85, 0xa2e7, 0x4341, 0x1c23, 0xcd74, 0x9216,
    0x73b0, 0x2cd2, 0x9c67, 0xc305, 0x22a3, 0x7dc1, 0xac96, 0xf3f4, 0x1252, 0x4d30,
    0xf4b0, 0xabd2, 0x4a74, 0x1516, 0xc441, 0x9b23, 0x7a85, 0x25e7, 0x9552, 0xca30,
    0x2b96, 0x74f4, 0xa5a3, 0xfac1, 0x1b67, 0x4405, 0x3774, 0x6816, 0x89b0, 0xd6d2,
    0x0785, 0x58e7, 0xb941, 0xe623, 0x5696, 0x09f4, 0xe852, 0xb730, 0x6667, 0x3905,
    0xd8a3, 0x87c1, 0xe6da, 0xb9b8, 0x581e, 0x077c, 0xd62b, 0x8949, 0x68ef, 0x378d,
    0x8738, 0xd85a, 0x39fc, 0x669e, 0xb7c9, 0xe8ab, 0x090d, 0x566f, 0x251e, 0x7a7c,
    0x9bda, 0xc4b8, 0x15ef, 0x4a8d, 0xab2b, 0xf449, 0x44fc, 0x1b9e, 0xfa38, 0xa55a,
    0x740d, 0x2b6f, 0xcac9, 0x95ab, 0x2c2b, 0x7349, 0x92ef, 0xcd8d, 0x1cda, 0x43b8,
    0xa21e, 0xfd7c, 0x4dc9, 0x12ab, 0xf30d, 0xac6f, 0x7d38, 0x225a, 0xc3fc, 0x9c9e,
    0xefef, 0xb08d, 0x512b, 0x0e49, 0xdf1e, 0x807c, 0x61da, 0x3eb8, 0x8e0d, 0xd16f,
    0x30c9, 0x6fab, 0xbefc, 0xe19e, 0x0038, 0x5f5a},
   {0x4a8f, 0x5c9d, 0x66ab, 0x70b9, 0x12c7, 0x04d5, 0x3ee3, 0x28f1, 0xfa1f, 0xec0d,
    0xd63b, 0xc029, 0xa257, 0xb445, 0x8e73, 0x9861, 0x66d6, 0x70c4, 0x4af2, 0x5ce0,
    0x3e9e, 0x288c, 0x12ba, 0x04a8, 0xd646, 0xc054, 0xfa62, 0xec70, 0x8e0e, 0x981c,
    0xa22a, 0xb438, 0x123d, 0x042f, 0x3e19, 0x280b, 0x4a75, 0x5c67, 0x6651, 0x7043,
    0xa2ad, 0xb4bf, 0x8e89, 0x989b, 0xfae5, 0xecf7, 0xd6c1, 0xc0d3, 0x3e64, 0x2876,
    0x1240, 0x0452, 0x662c, 0x703e, 0x4a08, 0x5c1a, 0x8ef4, 0x98e6, 0xa2d0, 0xb4c2,
    0xd6bc, 0xc0ae, 0xfa98, 0xec8a, 0xfbeb, 0xedf9, 0xd7cf, 0xc1dd, 0xa3a3, 0xb5b1,
    0x8f87, 0x9995, 0x4b7b, 0x5d69, 0x675f, 0x714d, 0x1333, 0x0521, 0x3f17, 0x2905,
    0xd7b2, 0xc1a0, 0xfb96, 0xed84, 0x8ffa, 0x99e8, 0xa3de, 0xb5cc, 0x6722, 0x7130,
    0x4b06, 0x5d14, 0x3f6a, 0x2978, 0x134e, 0x055c, 0xa359, 0xb54b, 0x8f7d, 0x996f,
    0xfb11, 0xed03, 0xd735, 0xc127, 0x13c9, 0x05db, 0x3fed, 0x29ff, 0x4b81, 0x5d93,
    0x67a5, 0x71b7, 0x8f00, 0x9912, 0xa324, 0xb536, 0xd748, 0xc15a, 0xfb6c, 0xed7e,
    0x3f90, 0x2982, 0x13b4, 0x05a6, 0x67d8, 0x71ca, 0x4bfc, 0x5dee, 0x653e, 0x732c,
    0x491a, 0x5f08, 0x3d76, 0x2b64, 0x1152, 0x0740, 0xd5ae, 0xc3bc, 0xf98a, 0xef98,
    0x8de6, 0x9bf4, 0xa1c2, 0xb7d0, 0x4967, 0x5f75, 0x6543, 0x7351, 0x112f, 0x073d,
    0x3d0b, 0x2b19, 0xf9f7, 0xefe5, 0xd5d3, 0xc3c1, 0xa1bf, 0xb7ad, 0x8d9b, 0x9b89,
    0x3d8c, 0x2b9e, 0x11a8, 0x07ba, 0x65c4, 0x73d6, 0x49e0, 0x5ff2, 0x8d1c, 0x9b0e,
    0xa138, 0xb72a, 0xd554, 0xc346, 0xf970, 0xef62, 0x11d5, 0x07c7, 0x3df1, 0x2be3,
    0x499d, 0x5f8f, 0x65b9, 0x73ab, 0xa145, 0xb757, 0x8d61, 0x9b73, 0xf90d, 0xef1f,
    0xd529, 0xc33b, 0xd45a, 0xc248, 0xf87e, 0xee6c, 0x8c12, 0x9a00, 0xa036, 0xb624,
    0x64ca, 0x72d8, 0x48ee, 0x5efc, 0x3c82, 0x2a90, 0x10a6, 0x06b4, 0xf803, 0xee11,
    0xd427, 0xc235, 0xa04b, 0xb659, 0x8c6f, 0x9a7d, 0x4893, 0x5e81, 0x64b7, 0x72a5,
    0x10db, 0x06c9, 0x3cff, 0x2aed, 0x8ce8, 0x9afa, 0xa0cc, 0xb6de, 0xd4a0, 0xc2b2,
    0xf884, 0xee96, 0x3c78, 0x2a6a, 0x105c, 0x064e, 0x6430, 0x7222, 0x4814, 0x5e06,
    0xa0b1, 0xb6a3, 0x8c95, 0x9a87, 0xf8f9, 0xeeeb, 0xd4dd, 0xc2cf, 0x1021, 0x0633,
    0x3c05, 0x2a17, 0x4869, 0x5e7b, 0x644d, 0x725f}
};

unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

// This code assumes that integers are stored little-endian.

unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len && ((ptrdiff_t)data & 0x7)) {
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
        len--;
    }
    if (len >= 8) {
        do {
            uintmax_t word = crc ^ *(uintmax_t const *)data;
            crc = table_word[7][word & 0xff] ^
                  table_word[6][(word >> 8) & 0xff] ^
                  table_word[5][(word >> 16) & 0xff] ^
                  table_word[4][(word >> 24) & 0xff] ^
                  table_word[3][(word >> 32) & 0xff] ^
                  table_word[2][(word >> 40) & 0xff] ^
                  table_word[1][(word >> 48) & 0xff] ^
                  table_word[0][word >> 56];
            data += 8;
            len -= 8;
        } while (len >= 8);
    }
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

Merge trunk to branch in Subversion

Last revision merged from trunk to branch can be found by running this command inside the working copy directory:

svn log -v --stop-on-copy

Calculate distance in meters when you know longitude and latitude in java

In C++ it is done like this:

#define LOCAL_PI 3.1415926535897932385 

double ToRadians(double degrees) 
{
  double radians = degrees * LOCAL_PI / 180;
  return radians;
}

double DirectDistance(double lat1, double lng1, double lat2, double lng2) 
{
  double earthRadius = 3958.75;
  double dLat = ToRadians(lat2-lat1);
  double dLng = ToRadians(lng2-lng1);
  double a = sin(dLat/2) * sin(dLat/2) + 
             cos(ToRadians(lat1)) * cos(ToRadians(lat2)) * 
             sin(dLng/2) * sin(dLng/2);
  double c = 2 * atan2(sqrt(a), sqrt(1-a));
  double dist = earthRadius * c;
  double meterConversion = 1609.00;
  return dist * meterConversion;
}

Eclipse copy/paste entire line keyboard shortcut

Just another approach:

1) Alt+Up and Alt+Down (or Alt+Down and Alt+Up, order does not matter)
2) Ctrl+C

But of course vim's "yy" is the fastest :)

Does C# have an equivalent to JavaScript's encodeURIComponent()?

System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.

PHP Warning: Unknown: failed to open stream

Experienced the same error, for me it was caused because on my Mac I have changed the DocumentRoot to my users Sites directory.

To fix it, I ran the recursive command to ensure that the Apache service has read permissions.

sudo chmod -R 755 ~/Sites

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

Explode PHP string by new line

this php function explode string by newline

Attention : new line in Windows is \r\n and in Linux and Unix is \n
this function change all new lines to linux mode then split it.
pay attention that empty lines will be ignored

function splitNewLine($text) {
    $code=preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$text)));
    return explode("\n",$code);
}

example

$a="\r\n\r\n\n\n\r\rsalam\r\nman khobam\rto chi\n\rche khabar\n\r\n\n\r\r\n\nbashe baba raftam\r\n\r\n\r\n\r\n";
print_r( splitNewLine($a) );

output

Array
(
    [0] => salam
    [1] => man khobam
    [2] => to chi
    [3] => che khabar
    [4] => bashe baba raftam
)

How do I unload (reload) a Python module?

I got a lot of trouble trying to reload something inside Sublime Text, but finally I could wrote this utility to reload modules on Sublime Text based on the code sublime_plugin.py uses to reload modules.

This below accepts you to reload modules from paths with spaces on their names, then later after reloading you can just import as you usually do.

def reload_module(full_module_name):
    """
        Assuming the folder `full_module_name` is a folder inside some
        folder on the python sys.path, for example, sys.path as `C:/`, and
        you are inside the folder `C:/Path With Spaces` on the file 
        `C:/Path With Spaces/main.py` and want to re-import some files on
        the folder `C:/Path With Spaces/tests`

        @param full_module_name   the relative full path to the module file
                                  you want to reload from a folder on the
                                  python `sys.path`
    """
    import imp
    import sys
    import importlib

    if full_module_name in sys.modules:
        module_object = sys.modules[full_module_name]
        module_object = imp.reload( module_object )

    else:
        importlib.import_module( full_module_name )

def run_tests():
    print( "\n\n" )
    reload_module( "Path With Spaces.tests.semantic_linefeed_unit_tests" )
    reload_module( "Path With Spaces.tests.semantic_linefeed_manual_tests" )

    from .tests import semantic_linefeed_unit_tests
    from .tests import semantic_linefeed_manual_tests

    semantic_linefeed_unit_tests.run_unit_tests()
    semantic_linefeed_manual_tests.run_manual_tests()

if __name__ == "__main__":
    run_tests()

If you run for the first time, this should load the module, but if later you can again the method/function run_tests() it will reload the tests files. With Sublime Text (Python 3.3.6) this happens a lot because its interpreter never closes (unless you restart Sublime Text, i.e., the Python3.3 interpreter).

How should a model be structured in MVC?

In Web-"MVC" you can do whatever you please.

The original concept (1) described the model as the business logic. It should represent the application state and enforce some data consistency. That approach is often described as "fat model".

Most PHP frameworks follow a more shallow approach, where the model is just a database interface. But at the very least these models should still validate the incoming data and relations.

Either way, you're not very far off if you separate the SQL stuff or database calls into another layer. This way you only need to concern yourself with the real data/behaviour, not with the actual storage API. (It's however unreasonable to overdo it. You'll e.g. never be able to replace a database backend with a filestorage if that wasn't designed ahead.)

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

Accessing a class' member variables in Python?

You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

To set a class variable (a.k.a. static member), use

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.

Converting String to Int with Swift

My solution is to have a general extension for string to int conversion.

extension String {

 // default: it is a number suitable for your project if the string is not an integer

    func toInt(default: Int) -> Int {
        if let result = Int(self) {
            return result
        }
        else {
            return default  
        }
    }

}

How do I serialize an object and save it to a file in Android?

I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:

Option1:

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();

Option2:

SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();

Option 2 is twice quicker than option 1

The option 2 inconvenience is that you have to make specific code for read:

Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
    events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

You can just pass your URL,

NSURL *url = [NSURL URLWithString:@"http://www.myurl.com/1.png"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (data) {
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                    yourimageview.image = image;
            });
        }
    }
}];
[task resume];

Removing the remembered login and password list in SQL Server Management Studio

Another answer here also mentions since 2012 you can remove Remove cached login via How to remove cached server names from the Connect to Server dialog?. Just confirmed this delete in MRU list works fine in 2016 and 2017.

SQL Server Management Studio 2017 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\14.0\SqlStudio.bin

SQL Server Management Studio 2016 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin

SQL Server Management Studio 2014 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\12.0\SqlStudio.bin

SQL Server Management Studio 2012 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\11.0\SqlStudio.bin

SQL Server Management Studio 2008 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin

SQL Server Management Studio 2005 delete the file – same as above answer but the Vista path. C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

These are profile paths for Vista / 7 / 8.

EDIT:

Note, AppData is a hidden folder. You need to show hidden folders in explorer.

EDIT: You can simply press delete from the Server / User name drop down (confirmed to be working for SSMS v18.0). Original source from https://blog.sqlauthority.com/2013/04/17/sql-server-remove-cached-login-from-ssms-connect-dialog-sql-in-sixty-seconds-049/ which mentioned that this feature is available since 2012!

How to check if a python module exists without importing it

Python 3 >= 3.6: ModuleNotFoundError

The ModuleNotFoundError has been introduced in python 3.6 and can be used for this purpose

try:
    import eggs
except ModuleNotFoundError:
    # Error handling
    pass

The error is raised when a module or one of its parents cannot be found. So

try:
    import eggs.sub
except ModuleNotFoundError as err:
    # Error handling
    print(err)

would print a message that looks like No module named 'eggs' if the eggs module cannot be found; but would print something like No module named 'eggs.sub' if only the sub module couldn't be found but the eggs package could be found.

See the documentation of the import system for more info on the ModuleNotFoundError

Regex match everything after question mark?

Try this:

\?(.*)

The parentheses are a capturing group that you can use to extract the part of the string you are interested in.

If the string can contain new lines you may have to use the "dot all" modifier to allow the dot to match the new line character. Whether or not you have to do this, and how to do this, depends on the language you are using. It appears that you forgot to mention the programming language you are using in your question.

Another alternative that you can use if your language supports fixed width lookbehind assertions is:

(?<=\?).*

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

How to refresh the data in a jqGrid?

var newdata= //You call Ajax peticion//

$("#idGrid").clearGridData();

$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");

in event update data table

What does "while True" mean in Python?

True is always True, so while True will loop forever.

The while keyword takes an expression, and loops while the expression is true. True is an expression that is always true.

As a possibly clarifying example, consider the following:

a = 1
result = a == 1

Here, a == 1 will return True, and hence put True into result. Hence,

a = 1
while a == 1:
  ...

is equivalent to:

while True:
  ...

provided you don't alter the value of a inside the while loop.

Convert spark DataFrame column to python list

Let's create the dataframe in question

df_test = spark.createDataFrame(
    [
        (1, 5),
        (2, 9),
        (3, 3),
        (4, 1),
    ],
    ['mvv', 'count']
)
df_test.show()

Which gives

+---+-----+
|mvv|count|
+---+-----+
|  1|    5|
|  2|    9|
|  3|    3|
|  4|    1|
+---+-----+

and then apply rdd.flatMap(f).collect() to get the list

test_list = df_test.select("mvv").rdd.flatMap(list).collect()
print(type(test_list))
print(test_list)

which gives

<type 'list'>
[1, 2, 3, 4]

What is a serialVersionUID and why should I use it?

The docs for java.io.Serializable are probably about as good an explanation as you'll get:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class — serialVersionUID fields are not useful as inherited members.

jQuery detect if textarea is empty

if (!$.trim($("element").val())) {

}

Git: Installing Git in PATH with GitHub client for Windows

Updated for the Github Desktop

Search up "Edit the system environment variables" on windows search

  • Click environmental variable on the bottom right corner

  • Find path under system variables and click edit on it

  • Click new to add a new path

  • add this path: C:\Users\yourUserName\AppData\Local\GitHubDesktop\bin\github.exe

To make sure everything is working fine, open cmd, and type github.exe

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

Pretty-Print JSON in Java

Following the JSON-P 1.0 specs (JSR-353) a more current solution for a given JsonStructure (JsonObject or JsonArray) could look like this:

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

public class PrettyJson {

    private static JsonWriterFactory FACTORY_INSTANCE;

    public static String toString(final JsonStructure status) {

        final StringWriter stringWriter = new StringWriter();

        final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
                .createWriter(stringWriter);

        jsonWriter.write(status);
        jsonWriter.close();

        return stringWriter.toString();
    }

    private static JsonWriterFactory getPrettyJsonWriterFactory() {
        if (null == FACTORY_INSTANCE) {
            final Map<String, Object> properties = new HashMap<>(1);
            properties.put(JsonGenerator.PRETTY_PRINTING, true);
            FACTORY_INSTANCE = Json.createWriterFactory(properties);
        }
        return FACTORY_INSTANCE;
    }

}

Find the greatest number in a list of numbers

You can use the inbuilt function max() with multiple arguments:

print max(1, 2, 3)

or a list:

list = [1, 2, 3]
print max(list)

or in fact anything iterable.

Bash foreach loop

If they all have the same extension (for example .jpg), you can use this:

for picture in  *.jpg ; do
    echo "the next file is $picture"
done

(This solution also works if the filename has spaces)

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Just:

dt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'
dt = datetime.datetime.strptime(dt,format)

So do this:

start_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')
start_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')

end_time = challenge.datetime_end.strftime('%Y %d %m %H %M %S')
end_time = datetime.datetime.strptime(end_time,'%Y %d %m %H %M %S')

and then use start_time and end_time

This declaration has no storage class or type specifier in C++

This is a mistake:

m.check(side);

That code has to go inside a function. Your class definition can only contain declarations and functions.

Classes don't "run", they provide a blueprint for how to make an object.

The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.

How do I assert my exception message with JUnit Test annotation?

I would prefer AssertJ for this.

        assertThatExceptionOfType(ExpectedException.class)
        .isThrownBy(() -> {
            // method call
        }).withMessage("My message");

Refresh page after form submitting

You want a form that self submits? Then you just leave the "action" parameter blank.

like:

<form method="post" action="" />

If you want to process the form with this page, then make sure that you have some mechanism in the form or session data to test whether it was properly submitted and to ensure you're not trying to process the empty form.

You might want another mechanism to decide if the form was filled out and submitted but is invalid. I usually use a hidden input field that matches a session variable to decide whether the user has clicked submit or just loaded the page for the first time. By giving a unique value each time and setting the session data to the same value, you can also avoid duplicate submissions if the user clicks submit twice.

SOAP Action WSDL

I've just spent a while trying to get this to work an have a written a Ruby gem that accesses the API. You can read more on it's project page.

This is working code in Ruby:

require 'savon'
client = Savon::Client.new do
  wsdl.document = "http://realtime.nationalrail.co.uk/LDBWS/wsdl.aspx"
end

response = client.request 'http://thalesgroup.com/RTTI/2012-01-13/ldb/GetDepartureBoard' do

  namespaces = {
    "xmlns:soap" => "http://schemas.xmlsoap.org/soap/envelope/",
    "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
    "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema"
  }

  soap.xml do |xml|
    xml.soap(:Envelope, namespaces) do |xml|
      xml.soap(:Header) do |xml|
        xml.AccessToken do |xml|
          xml.TokenValue('ENTER YOUR TOKEN HERE') 
        end
      end
      xml.soap(:Body) do |xml|
        xml.GetDepartureBoardRequest(xmlns: "http://thalesgroup.com/RTTI/2012-01-13/ldb/types") do |xml|
          xml.numRows(10)
          xml.crs("BHM")
          xml.filterCrs("BHM")
          xml.filterType("to")
        end
      end
    end
  end
end
p response.body

Hope that's helpful for someone!

Issue with adding common code as git submodule: "already exists in the index"

Just to clarify in human language what the error is trying to tell you:

You cannot create a repository in this folder which already tracked in the main repository.

For example: You have a theme folder called AwesomeTheme that's a dedicated repository, you try do dump it directly into your main repository like git submodule add sites/themes and you get this "AwesomeTheme" index already exists.

You just need to make sure there isn't already a sites/themes/AwesomeTheme in the main repository's version tracking so the submodule can be created there.

So to fix, in your main repository if you have an empty sites/theme/AwesomeTheme directory then remove it. If you have already made commits with the sites/theme/AwesomeTheme directory in your main repository you need to purge all history of it with a command like this:

git filter-branch --index-filter \
              'git rm -r --cached --ignore-unmatch sites/theme/AwesomeTheme'     HEAD

Now you can run git submodule add [email protected] sites/themes/AwesomeTheme

Since the main repository has never seen anything (a.k.a index'd) in sites/themes/AwesomeTheme before, it can now create it.

Server configuration is missing in Eclipse

If you're not too attached to your current workspace you can create a new workspace, follow BalusC's steps for server creation, and recreate your project in the new workspace.

I got the same error after installing Eclipse Java EE IDE for Web Developers(Juno) but using the workspace of a much older Eclipse installation. When I created a new workspace I was able to get my Tomcat server running without this error.

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I had the same problem and the issue was that my child component had an @input named formControl.

So I just needed to change from:

<my-component [formControl]="formControl"><my-component/>

to:

<my-component [control]="control"><my-component/>

ts:

@Input()
control:FormControl;

"Please try running this command again as Root/Administrator" error when trying to install LESS

Re Explosion Pills "An installation can run arbitrary scripts and running it with sudo can be extremely dangerous!"

Seems like using sudo is the wrong way of doing it.

"Change the owner of the files in your /usr/local folder to the current user:"

sudo chown -R $USER /usr/local

Then run the install

node install -g less

Check out:

default select option as blank

I'm using Laravel 5 framework and @Gambi `s answer worked for me as well but with some changes for my project.

I have the option values in a database table and I use them with a foreach statement. But before the statement I have added an option with @Gambit suggested settings and it worked.

Here my exemple:

@isset($keys)
  <select>
    <option  disabled selected value></option>
    @foreach($keys as $key)
      <option>{{$key->value)</option>
    @endforeach
  </select>
@endisset 

I hope this helps someone as well. Keep up the good work!

How to kill a child process by the parent process?

Try something like this:

#include <signal.h>

pid_t child_pid = -1 ; //Global

void kill_child(int sig)
{
    kill(child_pid,SIGKILL);
}

int main(int argc, char *argv[])
{
    signal(SIGALRM,(void (*)(int))kill_child);
    child_pid = fork();
    if (child_pid > 0) {
     /*PARENT*/
        alarm(30);
        /*
         * Do parent's tasks here.
         */
        wait(NULL);
    }
    else if (child_pid == 0){
     /*CHILD*/
        /*
         * Do child's tasks here.
         */
    }
}

Setting Different Bar color in matplotlib Python

I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html

there is no color parameter listed where you might be able to set the colors for your bar graph.

However, the Series.plot() docs state the following at the end of the parameter list:

kwds : keywords
Options to pass to matplotlib plotting method

What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().

If you examine the docs for the matplotlib.pyplot.bar() method here:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.

Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:

import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series(
    [5, 4, 4, 1, 12],
    index = ["AK", "AX", "GA", "SQ", "WN"]
)

#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')

#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')

#Plot the data:
my_colors = 'rgbkymc'  #red, green, blue, black, etc.

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

plt.show()

enter image description here

Note that if there are more bars than colors in your sequence, the colors will repeat.

Simple Vim commands you wish you'd known earlier

:shell to launch a shell console from Vim. Useful when for example you want to test a script without quitting Vim. Simply hit ^d when you done with the shell console, and then you come back to Vim and your edited file.

Emulate a 403 error page

Seen a lot of the answers, but the correct one is to provide the full options for the header function call as per the php manual

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

If you invoke with

header('HTTP/1.0 403 Forbidden', true, 403);

the normal behavior of HTTP 403 as configured with Apache or any other server would follow.

Java constant examples (Create a java file having only constants)

Neither one. Use final class for Constants declare them as public static final and static import all constants wherever necessary.

public final class Constants {

    private Constants() {
            // restrict instantiation
    }

    public static final double PI = 3.14159;
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
}

Usage :

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;//import static Constants.*;

public class Calculations {

        public double getReducedPlanckConstant() {
                return PLANCK_CONSTANT / (2 * PI);
        }
}

See wiki link : http://en.wikipedia.org/wiki/Constant_interface

What does enctype='multipart/form-data' mean?

  • enctype(ENCode TYPE) attribute specifies how the form-data should be encoded when submitting it to the server.
  • multipart/form-data is one of the value of enctype attribute, which is used in form element that have a file upload. multi-part means form data divides into multiple parts and send to server.

Running the new Intel emulator for Android

You have to download the Intel® Hardware Accelerated Execution Manager. Then you will get this message:

Starting emulator for AVD 'test' emulator: device fd:740 HAX is working and emulator runs in fast virt mode

C++ Calling a function from another class

What you should do, is put CallFunction into *.cpp file, where you include B.h.

After edit, files will look like:

B.h:

#pragma once //or other specific to compiler...
using namespace std;

class A 
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }
};

B.cpp

#include "B.h"
void A::CallFunction(){
//use B object here...
}

Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).

So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.

And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).

Force IE10 to run in IE10 Compatibility View?

If you want to set the compatibility mode in the browser itself and not in the html do the following

  1. Open IE 10
  2. Press the ALT Key to bring up the IE Menubar
  3. Click on the Tools menu
  4. Click on compatibility view setting.
  5. Clicks check the box; display all the websites in compatibility view or
  6. Add only the desired websites to the compatibility view

As shown in the image below. The website should then open up with IE 10 Compatibility view.

enter image description here

Calculate correlation for more than two variables?

You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:

http://www.statmethods.net/stats/correlations.html

How to use Python's pip to download and keep the zipped files for a package?

pip wheel is another option you should consider:

pip wheel mypackage -w .\outputdir

It will download packages and their dependencies to a directory (current working directory by default), but it performs the additional step of converting any source packages to wheels.

It conveniently supports requirements files:

pip wheel -r requirements.txt -w .\outputdir

Add the --no-deps argument if you only want the specifically requested packages:

pip wheel mypackage -w .\outputdir --no-deps

How to install mod_ssl for Apache httpd?

I found I needed to enable the SSL module in Apache (obviously prefix commands with sudo if you are not running as root):

a2enmod ssl

then restart Apache:

/etc/init.d/apache2 restart

More details of SSL in Apache for Ubuntu / Debian here.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

I would recommend using rgba(255,255,255,0) because broken (newest) safari thinks that if you are using transparent or rgba(0,0,0,0) in linear-gradent you really mean gray, For more info please head to - What happens in Safari with the transparent color?

Format an Integer using Java String Format

Use %03d in the format specifier for the integer. The 0 means that the number will be zero-filled if it is less than three (in this case) digits.

See the Formatter docs for other modifiers.

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

Make more than one chart in same IPython Notebook cell

Something like this:

import matplotlib.pyplot as plt
... code for plot 1 ...
plt.show()
... code for plot 2...
plt.show()

Note that this will also work if you are using the seaborn package for plotting:

import matplotlib.pyplot as plt
import seaborn as sns
sns.barplot(... code for plot 1 ...) # plot 1
plt.show()
sns.barplot(... code for plot 2 ...) # plot 2
plt.show()

What does $_ mean in PowerShell?

I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_ is similar to x in x => Console.WriteLine(x) anonymous function in C#. Consider following examples:

PowerShell:

1,2,3 | ForEach-Object {Write-Host $_}

Prints:

1
2
3

or

1,2,3 | Where-Object {$_ -gt 1}

Prints:

2
3

And compare this with C# syntax using LINQ:

var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));

Prints:

1
2
3

or

list.Where( _ => _ > 1)
    .ToList()
    .ForEach(s => Console.WriteLine(s));

Prints:

2
3

Update Item to Revision vs Revert to Revision

Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

If you want to undo an earlier change permanently, use Revert to this revision instead.

-- from TSVN help doc

If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

What is the lifetime of a static variable in a C++ function?

FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.

C:\> sample.exe 1 2
Created in foo
Created in if
Destroyed in foo
Destroyed in if

... which is another reason not to rely on the destruction order!

Get the number of rows in a HTML table

var x = document.getElementById("myTable").rows.length;

What is the purpose of the HTML "no-js" class?

Look at the source code in Modernizer, this section:

// Change `no-js` to `js` (independently of the `enableClasses` option)
// Handle classPrefix on this too
if (Modernizr._config.enableJSClass) {
  var reJS = new RegExp('(^|\\s)' + classPrefix + 'no-js(\\s|$)');
  className = className.replace(reJS, '$1' + classPrefix + 'js$2');
}

So basically it search for classPrefix + no-js class and replace it with classPrefix + js.

And the use of that, is styling differently if JavaScript not running in the browser.

How can I simulate mobile devices and debug in Firefox Browser?

I think it's better to use the chrome toggle device toolbar with the chrome inspector. It provides you a user agent switch along with responsive mode. enter image description here

How to copy a java.util.List into another java.util.List

Just use this:

List<SomeBean> newList = new ArrayList<SomeBean>(otherList);

Note: still not thread safe, if you modify otherList from another thread, then you may want to make that otherList (and even newList) a CopyOnWriteArrayList, for instance -- or use a lock primitive, such as ReentrantReadWriteLock to serialize read/write access to whatever lists are concurrently accessed.

Using Tkinter in python to edit the title bar

I found this works:

window = Tk()
window.title('Window')

Maybe this helps?

How to create a cron job using Bash automatically without the interactive editor?

echo "0 * * * * docker system prune --force >/dev/null 2>&1" | sudo tee /etc/cron.daily/dockerprune

How do I compare two strings in Perl?

The obvious subtext of this question is:

why can't you just use == to check if two strings are the same?

Perl doesn't have distinct data types for text vs. numbers. They are both represented by the type "scalar". Put another way, strings are numbers if you use them as such.

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7

Since text and numbers aren't differentiated by the language, we can't simply overload the == operator to do the right thing for both cases. Therefore, Perl provides eq to compare values as text:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true

In short:

  • Perl doesn't have a data-type exclusively for text strings
  • use == or !=, to compare two operands as numbers
  • use eq or ne, to compare two operands as text

There are many other functions and operators that can be used to compare scalar values, but knowing the distinction between these two forms is an important first step.

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Try to add

GRANT USAGE ON SCHEMA public to readonly;

You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.

Cannot connect to the Docker daemon on macOS

Try this to create default.

docker-machine create default

What does 'foo' really mean?

As definition of "Foo" has lot's of meanings:

  • bar, and baz are often compounded together to make such words as foobar, barbaz, and foobaz. www.nationmaster.com/encyclopedia/Metasyntactic-variable

  • Major concepts in CML, usually mapped directly onto XMLElements (to be discussed later). wwmm.ch.cam.ac.uk/blogs/cml/

  • Measurement of the total quantity of pasture in a paddock, expressed in kilograms of pasture dry matter per hectare (kg DM/ha) www.lifetimewool.com.au/glossary.aspx

  • Forward Observation Officer. An artillery officer who remained with infantry and tank battalions to set up observation posts in the front lines from which to observe enemy positions and radio the coordinates of targets to the guns further in the rear. members.fortunecity.com/lniven/definition.htm

  • is the first metasyntactic variable commonly used. It is sometimes combined with bar to make foobar. This suggests that foo may have originated with the World War II slang term fubar, as an acronym for fucked/fouled up beyond all recognition, although the Jargon File makes a pretty good case ... explanation-guide.info/meaning/Metasyntactic-variable.html

  • Foo is a metasyntactic variable used heavily in computer science to represent concepts abstractly and can be used to represent any part of a ... en.wikipedia.org/wiki/FOo

  • Foo is the world of dreams (no its not) in Obert Skye's Leven Thumps series. Although it has many original inhabitants, most of its current dwellers are from Reality, and are known as nits. ... en.wikipedia.org/wiki/Foo (place)

  • Also foo’. Representation of fool (foolish person), in a Mr. T accent en.wiktionary.org/wiki/foo

Resource: google

How to access /storage/emulated/0/

Also you can use Android Debug Bridge (adb) to copy your file from Android device to folder on your PC:

adb pull /storage/emulated/0/AudioRecorder/1436854479696.mp4 <folder_on_your_PC_e.g. c:/temp>

And you can copy from device whole AudioRecorder folder:

adb pull /storage/emulated/0/AudioRecorder <folder_on_your_PC_e.g. c:/temp>

css3 transition animation on load?

Well, this is a tricky one.

The answer is "not really".

CSS isn't a functional layer. It doesn't have any awareness of what happens or when. It's used simply to add a presentational layer to different "flags" (classes, ids, states).

By default, CSS/DOM does not provide any kind of "on load" state for CSS to use. If you wanted/were able to use JavaScript, you'd allocate a class to body or something to activate some CSS.

That being said, you can create a hack for that. I'll give an example here, but it may or may not be applicable to your situation.

We're operating on the assumption that "close" is "good enough":

<html>
<head>
<!-- Reference your CSS here... -->
</head>
<body>
    <!-- A whole bunch of HTML here... -->
    <div class="onLoad">OMG, I've loaded !</div>
</body>
</html>

Here's an excerpt of our CSS stylesheet:

.onLoad
{
    -webkit-animation:bounceIn 2s;
}

We're also on the assumption that modern browsers render progressively, so our last element will render last, and so this CSS will be activated last.

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Had this error with [email protected]

Try to reinstall mysql

brew reinstall [email protected]

This will fix

Angular Directive refresh on parameter change

angular.module('app').directive('conversation', function() {
    return {
        restrict: 'E',
        link: function ($scope, $elm, $attr) {
            $scope.$watch("some_prop", function (newValue, oldValue) {
                  var typeId = $attr.type-id;
                  // Your logic.
            });
        }
    };
}

How can I convert a string to a number in Perl?

Perl really only has three types: scalars, arrays, and hashes. And even that distinction is arguable. ;) The way each variable is treated depends on what you do with it:

% perl -e "print 5.4 . 3.4;"
5.43.4


% perl -e "print '5.4' + '3.4';"
8.8

How to change text color of cmd with windows batch script every 1 second

To have a colorful user experience, I have used this script to execute the whole set of commands. I hope it helps.

@echo off
color 01
timeout /t 2
color 02
timeout /t 2
color 03
timeout /t 2
color 04
timeout /t 2
color 05
timeout /t 2

How to pretty print nested dictionaries?

I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:

def pretty(d, indent=0):
   for key, value in d.items():
      print('\t' * indent + str(key))
      if isinstance(value, dict):
         pretty(value, indent+1)
      else:
         print('\t' * (indent+1) + str(value))

How can I check that two objects have the same set of property names?

If you want to check if both objects have the same properties name, you can do this:

function hasSameProps( obj1, obj2 ) {
  return Object.keys( obj1 ).every( function( prop ) {
    return obj2.hasOwnProperty( prop );
  });
}

var obj1 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] },
    obj2 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] };

console.log(hasSameProps(obj1, obj2));

In this way you are sure to check only iterable and accessible properties of both the objects.

EDIT - 2013.04.26:

The previous function can be rewritten in the following way:

function hasSameProps( obj1, obj2 ) {
    var obj1Props = Object.keys( obj1 ),
        obj2Props = Object.keys( obj2 );

    if ( obj1Props.length == obj2Props.length ) {
        return obj1Props.every( function( prop ) {
          return obj2Props.indexOf( prop ) >= 0;
        });
    }

    return false;
}

In this way we check that both the objects have the same number of properties (otherwise the objects haven't the same properties, and we must return a logical false) then, if the number matches, we go to check if they have the same properties.

Bonus

A possible enhancement could be to introduce also a type checking to enforce the match on every property.

PHP UML Generator

You can use Visual Paradigm for UML. This might not be the best paid (it's US$699) product, just as an option if anyone would like to try. It can create class diagram from PHP and vice versa, and not only PHP, there's a bunch of language you can choose such as C#, C++, Ruby, Java, VB.NET, Python, Objective C, Perl, etc. There's also a trial you can check on.

SVN Commit failed, access forbidden

If the problem lies client side, this could be one of the causes of the error.

On clients TortoiseSVN saves client credentials under

Tortoise settings / saved data / authentication data.

I got the same error trying to commit my files, but my credentials were changed. Clearing this cache here will give you a popup on next commit attempt for re-entering your correct credentials.

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

Remove the project from the server from the Server View. Then run the project under the same server.

The problem is as @BalusC told corrupt of server.xml of tomcat which is configured in the eclipse. So when you do the above process server.xml will be recreated .

How to read existing text files without defining path

There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using Assembly.GetExecutingAssembly().Location and then use Path class to get a directory name.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

If a directory has spaces in, put quotes around it. This includes the program you're calling, not just the arguments

"C:\Program Files\IAR Systems\Embedded Workbench 7.0\430\bin\icc430.exe" "F:\CP001\source\Meter\Main.c" -D Hardware_P20E -D Calibration_code -D _Optical -D _Configuration_TS0382 -o "F:\CP001\Temp\C20EO\Obj\" --no_cse --no_unroll --no_inline --no_code_motion --no_tbaa --debug -D__MSP430F425 -e --double=32 --dlib_config "C:\Program Files\IAR Systems\Embedded Workbench 7.0\430\lib\dlib\dl430fn.h" -Ol --multiplier=16 --segment __data16=DATA16 --segment __data20=DATA20

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

How to prevent line breaks in list items using CSS

If you want to achieve this selectively (ie: only to that particular link), you can use a non-breaking space instead of a normal space:

<li>submit&nbsp;resume</li>

https://en.wikipedia.org/wiki/Non-breaking_space#Encodings

edit: I understand that this is HTML, not CSS as requested by the OP, but some may find it helpful…

Error when trying vagrant up

I know this is old, but I got exactly the same error. Turns out I was missing this step that is clearly in the documentation.

I needed to edit the Vagrantfile to set the config.vm.box equal to the image I had downloaded, hashicorp/precise32. By default it was set to base.

Here's what the documentation says:

Now that the box has been added to Vagrant, we need to configure our project to use it as a base. Open the Vagrantfile and change the contents to the following:

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise32"
end

Reset local repository branch to be just like remote repository HEAD

Setting your branch to exactly match the remote branch can be done in two steps:

git fetch origin
git reset --hard origin/master

Update @2020 (if you have main branch instead of master in remote repo)

git fetch origin
git reset --hard origin/main 

If you want to save your current branch's state before doing this (just in case), you can do:

git commit -a -m "Saving my work, just in case"
git branch my-saved-work

Now your work is saved on the branch "my-saved-work" in case you decide you want it back (or want to look at it later or diff it against your updated branch).

Note that the first example assumes that the remote repo's name is "origin" and that the branch named "master" in the remote repo matches the currently checked-out branch in your local repo.

BTW, this situation that you're in looks an awful lot like a common case where a push has been done into the currently checked out branch of a non-bare repository. Did you recently push into your local repo? If not, then no worries -- something else must have caused these files to unexpectedly end up modified. Otherwise, you should be aware that it's not recommended to push into a non-bare repository (and not into the currently checked-out branch, in particular).

How do I add a Maven dependency in Eclipse?

I have faced the similar issue and fixed by copying the missing Jar files in to .M2 Path,

For example: if you see the error message as Missing artifact tws:axis-client:jar:8.7 then you have to download "axis-client-8.7.jar" file and paste the same in to below location will resolve the issue.

C:\Users\UsernameXXX.m2\repository\tws\axis-client\8.7(Paste axis-client-8.7.jar).

finally, right click on project->Maven->Update Project...Thats it.

happy coding.

How to mount a host directory in a Docker container

Here's an example with a Windows path:

docker run -P -it --name organizr --mount src="/c/Users/MyUserName/AppData/Roaming/DockerConfigs/Organizr",dst=/config,type=bind organizrtools/organizr-v2:latest

As a side note, during all of this hair pulling, having to wrestle with figuring out, and retyping paths over and over and over again, I decided to whip up a small AutoHotkey script to convert a Windows path to a "Docker Windows" formatted path. This way all I have to do is copy any Windows path that I want to use as a mount point to the clipboard, press the "Apps Key" on the keyboard, and it'll format it into a path format that Docker appreciates.

For example:

Copy this to your clipboard:

C:\Users\My PC\AppData\Roaming\DockerConfigs\Organizr

press the Apps Key while the cursor is where you want it on the command-line, and it'll paste this there:

"/c/Users/My PC/AppData/Roaming/DockerConfigs/Organizr"

Saves a lot to time for me. Here it is for anyone else who may find it useful.

; --------------------------------------------------------------------------------------------------------------
;
; Docker Utility: Convert a Windows Formatted Path to a Docker Formatter Path
;                   Useful for (example) when mounting Windows volumes via the command-line.
;
; By:       J. Scott Elblein
; Version:  1.0
; Date:     2/5/2019
;
; Usage:    Cut or Copy the Windows formatted path to the clipboard, press the AppsKey on your keyboard
;           (usually right next to the Windows Key), it'll format it into a 'docker path' and enter it
;           into the active window. Easy example usage would be to copy your intended volume path via
;           Explorer, place the cursor after the "-v" in your Docker command, press the Apps Key and
;           then it'll place the formatted path onto the line for you.
;
; TODO::    I may or may not add anything to this depending on needs. Some ideas are:
;           
;           - Add a tray menu with the ability to do some things, like just replace the unformatted path
;               on the clipboard with the formatted one rather than enter it automatically.
;           - Add 'smarter' handling so the it first confirms that the clipboard text is even a path in
;               the first place. (would need to be able to handle Win + Mac + Linux)
;           - Add command-line handling so the script doesn't need to always be in the tray, you could
;               just pass the Windows path to the script, have it format it, then paste and close.
;               Also, could have it just check for a path on the clipboard upon script startup, if found
;               do it's job, then exit the script.
;           - Add an 'all-in-one' action, to copy the selected Windows path, and then output the result.
;           - Whatever else comes to mind.
;
; --------------------------------------------------------------------------------------------------------------

#NoEnv
SendMode Input
SetWorkingDir %A_ScriptDir%

AppsKey::

    ; Create a new var, store the current clipboard contents (should be a Windows path)
    NewStr := Clipboard

    ; Rip out the first 2 chars (should be a drive letter and colon) & convert the letter to lowercase
    ; NOTE: I could probably replace the following 3 lines with a regexreplace, but atm I'm lazy and in a rush.
    tmpVar := SubStr(NewStr, 1, 2)
    StringLower, tmpVar, tmpVar

    ; Replace the uppercase drive letter and colon with the lowercase drive letter and colon
    NewStr := StrReplace(NewStr, SubStr(NewStr, 1, 2), tmpVar)

    ; Replace backslashes with forward slashes
    NewStr := StrReplace(NewStr,  "\", "/")

    ; Replace all colons with nothing
    NewStr := StrReplace(NewStr, ":", "")

    ; Remove the last char if it's a trailing forward slash
    NewStr :=  RegExReplace(NewStr, "/$")

    ; Append a leading forward slash if not already there
    if RegExMatch(NewStr, "^/") == 0
        NewStr :=  "/" . NewStr

    ; If there are any spaces in the path ... wrap in double quotes
    if RegExMatch(NewStr, " ") > 0
        NewStr :=  """" . NewStr . """"

    ; Send the result to the active window
    SendInput % NewStr 

How to parse JSON in Kotlin?

You can use this library https://github.com/cbeust/klaxon

Klaxon is a lightweight library to parse JSON in Kotlin.

Get IFrame's document, from JavaScript in main document

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

How can I count the number of elements of a given value in a matrix?

This is a very good function file available on Matlab Central File Exchange.

countmember.m link

This function file is totally vectorized and hence very quick. Plus, in comparison to the function being referred to in aioobe's answer, this function doesn't use the accumarray function, which is why this is even compatible with older versions of Matlab. Also, it works for cell arrays as well as numeric arrays.

SOLUTION : You can use this function in conjunction with the built in matlab function, "unique".

occurance_count = countmember(unique(M),M)

occurance_count will be a numeric array with the same size as that of unique(M) and the different values of occurance_count array will correspond to the count of corresponding values (same index) in unique(M).

How do I make a Git commit in the past?

You can always change a date on your computer, make a commit, then change the date back and push.

Convert Datetime column from UTC to local time in select statement

In postgres this works very nicely..Tell the server the time at which the time is saved, 'utc', and then ask it to convert to a specific timezone, in this case 'Brazil/East'

quiz_step_progresses.created_at  at time zone 'utc' at time zone 'Brazil/East'

Get a complete list of timezones with the following select;

select * from pg_timezone_names;

See details here.

https://popsql.com/learn-sql/postgresql/how-to-convert-utc-to-local-time-zone-in-postgresql

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I faced the same problem, the following changes solved my problem.

$(document).ready(function() {
     $('.datatable').dataTable( {
            bSort: false,
            aoColumns: [ { sWidth: "45%" }, { sWidth: "45%" }, { sWidth: "10%", bSearchable: false, bSortable: false } ],
        "scrollY":        "200px",
        "scrollCollapse": true,
        "info":           true,
        "paging":         true
    } );
} );

the aoColumns array describes the width of each column and its sortable properties.

Another thing to mention this error will also appear when you order by a column number that does not exist.

Changing the child element's CSS when the parent is hovered

To change it from css you dont even need to set the child class

.parent > div:nth-child(1) { display:none; }
.parent:hover > div:nth-child(1) { display: block; }

How would I extract a single file (or changes to a file) from a git stash?

Edit: See cambunctious's answer, which is basically what I now prefer because it only uses the changes in the stash, rather than comparing them to your current state. This makes the operation additive, with much less chance of undoing work done since the stash was created.

To do it interactively, you would first do

git diff stash^! -- path/to/relevant/file/in/stash.ext perhaps/another/file.ext > my.patch

...then open the patch file in a text editor, alter as required, then do

git apply < my.patch

cambunctious's answer bypasses the interactivity by piping one command directly to the other, which is fine if you know you want all changes from the stash. You can edit the stash^! to be any commit range that has the cumulative changes you want (but check over the output of the diff first).

If applying the patch/diff fails, you can change the last command to git apply --reject which makes all the changes it can, and leaves .rej files where there are conflicts it can;r resolve. The .rej files can then be applied using wiggle, like so:

wiggle --replace path/to/relevant/file/in/stash.ext path/to/relevant/file/in/stash.ext.rej

This will either resolve the conflict, or give you conflict markers that you'd get from a merge.


Previous solution: There is an easy way to get changes from any branch, including stashes:

$ git checkout --patch stash@{0} path/to/file

You may omit the file spec if you want to patch in many parts. Or omit patch (but not the path) to get all changes to a single file. Replace 0 with the stash number from git stash list, if you have more than one. Note that this is like diff, and offers to apply all differences between the branches. To get changes from only a single commit/stash, have a look at git cherry-pick --no-commit.

Max or Default?

For Entity Framework and Linq to SQL we can achieve this by defining an extension method which modifies an Expression passed to IQueryable<T>.Max(...) method:

static class Extensions
{
    public static TResult MaxOrDefault<T, TResult>(this IQueryable<T> source, 
                                                   Expression<Func<T, TResult>> selector)
        where TResult : struct
    {
        UnaryExpression castedBody = Expression.Convert(selector.Body, typeof(TResult?));
        Expression<Func<T, TResult?>> lambda = Expression.Lambda<Func<T,TResult?>>(castedBody, selector.Parameters);
        return source.Max(lambda) ?? default(TResult);
    }
}

Usage:

int maxId = dbContextInstance.Employees.MaxOrDefault(employee => employee.Id);
// maxId is equal to 0 if there is no records in Employees table

The generated query is identical, it works just like a normal call to IQueryable<T>.Max(...) method, but if there is no records it returns a default value of type T instead of throwing an exeption

How can I make a CSS table fit the screen width?

Set font-size in viewport-width-related units, e.g.:

table { font-size: 0.9vw; }

This will make font unreadable when page is too narrow, but sometimes this is acceptable.

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

What is the difference between a 'closure' and a 'lambda'?

This question is old and got many answers.
Now with Java 8 and Official Lambda that are unofficial closure projects, it revives the question.

The answer in Java context (via Lambdas and closures — what’s the difference?):

"A closure is a lambda expression paired with an environment that binds each of its free variables to a value. In Java, lambda expressions will be implemented by means of closures, so the two terms have come to be used interchangeably in the community."

How to parse JSON using Node.js?

As mentioned in the above answers, We can use JSON.parse() to parse the strings to JSON But before parsing, be sure to parse the correct data or else it might bring your whole application down

it is safe to use it like this

let parsedObj = {}
try {
    parsedObj = JSON.parse(data);
} catch(e) {
    console.log("Cannot parse because data is not is proper json format")
}

IF - ELSE IF - ELSE Structure in Excel

Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:

=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I just encountered this same issue. Turned out the Project URL on the Web property sheet was malformed.

I had just removed a port number, forgot to delete the preceding colon and tried running with: http://localhost:/XYZ

Seems like lots of different issues result in this error message.

Input from the keyboard in command line application

I swear to God.. the solution to this utterly basic problem eluded me for YEARS. It's SO simple.. but there is so much vague / bad information out there; hopefully I can save someone from some of the bottomless rabbit holes that I ended up in...

So then, lets's get a "string" from "the user" via "the console", via stdin, shall we?

[NSString.alloc initWithData:
[NSFileHandle.fileHandleWithStandardInput availableData]
                          encoding:NSUTF8StringEncoding];

if you want it WITHOUT the trailing newline, just add...

[ ... stringByTrimmingCharactersInSet:
                       NSCharacterSet.newlineCharacterSet];

Ta Da! ? ??e?

Escaping regex string

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

Complex JSON nesting of objects and arrays

The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var keyword

You don't have any comments in your JSON, but you should remove the var and start like this:

orders: {

The [{}] notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:

"associatedDrug": {
                "name":"asprin",
                "dose":"",
                "strength":"500 mg"
          }

Also, the empty object labs should be filled with something.

Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse() method, or any other parsing method (please don't use eval)

Update 2 answered:

obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

returns 'aspirin'. It is however better suited for foreaches everywhere

Parsing JSON object in PHP using json_decode

Seems like you forgot the ["value"] or ->value:

echo $data[0]->weather->weatherIconUrl[0]->value;

Eclipse doesn't stop at breakpoints

None of these solutions worked. only changing the workspace worked for me.

IBOutlet and IBAction

The traditional way to flag a method so that it will appear in Interface Builder, and you can drag a connection to it, has been to make the method return type IBAction. However, if you make your method void, instead (IBAction is #define'd to be void), and provide an (id) argument, the method is still visible. This provides extra flexibility, al

All 3 of these are visible from Interface Builder:

-(void) someMethod1:(id) sender; 
-(IBAction) someMethod2; 
-(IBAction) someMethod3:(id) sender;

See Apple's Interface Builder User Guide for details, particularly the section entitled Xcode Integration.

Retrieve column names from java.sql.ResultSet

You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:

ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);

how can I debug a jar at runtime?

Even though it is a runnable jar, you can still run it from a console -- open a terminal window, navigate to the directory containing the jar, and enter "java -jar yourJar.jar". It will run in that terminal window, and sysout and syserr output will appear there, including stack traces from uncaught exceptions. Be sure to have your debug set to true when you compile. And good luck.


Just thought of something else -- if you're on Win7, it often has permission problems with user applications writing files to specific directories. Make sure the directory to which you are writing your output file is one for which you have permissions.

In a future project, if it's big enough, you can use one of the standard logging facilities for 'debug' output; then it will be easy(ier) to redirect it to a file instead of depending on having a console. But for a smaller job like this, this should be fine.

Inserting a text where cursor is using Javascript/jquery

This jQuery plugin gives you a pre-made way of selection/caret manipulation.

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

Java regex email

import java.util.Scanner;

public class CheckingTheEmailPassword {

    public static void main(String[] args) {
        String email = null;
        String password = null;
        Boolean password_valid = false;
        Boolean email_valid = false;

        Scanner input = new Scanner(System.in);
        do {
            System.out.println("Enter your email: ");
            email = input.nextLine();

            System.out.println("Enter your passsword: ");
            password = input.nextLine();

            // checks for words,numbers before @symbol and between "@" and ".".
            // Checks only 2 or 3 alphabets after "."
            if (email.matches("[\\w]+@[\\w]+\\.[a-zA-Z]{2,3}"))
                email_valid = true;
            else
                email_valid = false;

            // checks for NOT words,numbers,underscore and whitespace.
            // checks if special characters present
            if ((password.matches(".*[^\\w\\s].*")) &&
            // checks alphabets present
                    (password.matches(".*[a-zA-Z].*")) &&
                    // checks numbers present
                    (password.matches(".*[0-9].*")) &&
                    // checks length
                    (password.length() >= 8))
                password_valid = true;
            else
                password_valid = false;

            if (password_valid && email_valid)
                System.out.println(" Welcome User!!");
            else {
                if (!email_valid)
                    System.out.println(" Re-enter your email: ");
                if (!password_valid)
                    System.out.println(" Re-enter your password: ");
            }

        } while (!email_valid || !password_valid);

        input.close();

    }

}

How to use the IEqualityComparer

IEquatable<T> can be a much easier way to do this with modern frameworks.

You get a nice simple bool Equals(T other) function and there's no messing around with casting or creating a separate class.

public class Person : IEquatable<Person>
{
    public Person(string name, string hometown)
    {
        this.Name = name;
        this.Hometown = hometown;
    }

    public string Name { get; set; }
    public string Hometown { get; set; }

    // can't get much simpler than this!
    public bool Equals(Person other)
    {
        return this.Name == other.Name && this.Hometown == other.Hometown;
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();  // see other links for hashcode guidance 
    }
}

Note you DO have to implement GetHashCode if using this in a dictionary or with something like Distinct.

PS. I don't think any custom Equals methods work with entity framework directly on the database side (I think you know this because you do AsEnumerable) but this is a much simpler method to do a simple Equals for the general case.

If things don't seem to be working (such as duplicate key errors when doing ToDictionary) put a breakpoint inside Equals to make sure it's being hit and make sure you have GetHashCode defined (with override keyword).

jQuery Mobile how to check if button is disabled?

Faced with the same issue when trying to check if a button is disabled. I've tried a variety of approaches, such as btn.disabled, .is(':disabled'), .attr('disabled'), .prop('disabled'). But no one works for me.

Some, for example .disabled or .is(':disabled') returned undefined and other like .attr('disabled') returned the wrong result - false when the button was actually disabled.

But only one technique works for me: .is('[disabled]') (with square brackets).

So to determine if a button is disabled try this:

$("#myButton").is('[disabled]');

How to enumerate an object's properties in Python?

I think it's worth showing the difference between the various options mentioned - often a picture is worth a thousand words.

>>> from pprint import pprint
>>> import inspect
>>>
>>> class a():
    x = 1               # static class member
    def __init__(self):
        self.y = 2      # static instance member
    @property
    def dyn_prop(self): # dynamic property
        print('DYNPROP WAS HERE')
        return 3
    def test(self):     # function member
        pass
    @classmethod
    def myclassmethod(cls): # class method; static methods behave the same
        pass

>>> i = a()
>>> pprint(i.__dict__)
{'y': 2}
>>> pprint(vars(i))
{'y': 2}
>>> pprint(dir(i))
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'dyn_prop',
 'myclassmethod',
 'test',
 'x',
 'y']
>>> pprint(inspect.getmembers(i))
DYNPROP WAS HERE
[('__class__', <class '__main__.a'>),
 ('__delattr__',
  <method-wrapper '__delattr__' of a object at 0x000001CB891BC7F0>),
 ('__dict__', {'y': 2}),
 ('__dir__', <built-in method __dir__ of a object at 0x000001CB891BC7F0>),
 ('__doc__', None),
 ('__eq__', <method-wrapper '__eq__' of a object at 0x000001CB891BC7F0>),
 ('__format__', <built-in method __format__ of a object at 0x000001CB891BC7F0>),
 ('__ge__', <method-wrapper '__ge__' of a object at 0x000001CB891BC7F0>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of a object at 0x000001CB891BC7F0>),
 ('__gt__', <method-wrapper '__gt__' of a object at 0x000001CB891BC7F0>),
 ('__hash__', <method-wrapper '__hash__' of a object at 0x000001CB891BC7F0>),
 ('__init__',
  <bound method a.__init__ of <__main__.a object at 0x000001CB891BC7F0>>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x000001CB87CA6A70>),
 ('__le__', <method-wrapper '__le__' of a object at 0x000001CB891BC7F0>),
 ('__lt__', <method-wrapper '__lt__' of a object at 0x000001CB891BC7F0>),
 ('__module__', '__main__'),
 ('__ne__', <method-wrapper '__ne__' of a object at 0x000001CB891BC7F0>),
 ('__new__', <built-in method __new__ of type object at 0x00007FFCA630AB50>),
 ('__reduce__', <built-in method __reduce__ of a object at 0x000001CB891BC7F0>),
 ('__reduce_ex__',
  <built-in method __reduce_ex__ of a object at 0x000001CB891BC7F0>),
 ('__repr__', <method-wrapper '__repr__' of a object at 0x000001CB891BC7F0>),
 ('__setattr__',
  <method-wrapper '__setattr__' of a object at 0x000001CB891BC7F0>),
 ('__sizeof__', <built-in method __sizeof__ of a object at 0x000001CB891BC7F0>),
 ('__str__', <method-wrapper '__str__' of a object at 0x000001CB891BC7F0>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x000001CB87CA6A70>),
 ('__weakref__', None),
 ('dyn_prop', 3),
 ('myclassmethod', <bound method a.myclassmethod of <class '__main__.a'>>),
 ('test', <bound method a.test of <__main__.a object at 0x000001CB891BC7F0>>),
 ('x', 1),
 ('y', 2)]

To summarize:

  • vars() and __dict__ only return instance-local properties;
  • dir() returns everything, but only as a list of string member names; dynamic properties are not called;
  • inspect.getmembers() returns everything, as a list of tuples (name, value); it actually runs dynamic properties, and accepts an optional predicate argument that can filter out members by value.

So my common-sense approach is typically to use dir() on the command line, and getmembers() in programs, unless specific performance considerations apply.

Note that, to keep things cleaner, I did not include __slots__ - if present, it was explicitly put there to be queried, and should be used directly. I also did not cover metaclasses, which can get a bit hairy (most people will never use them anyway).

What is the best IDE to develop Android apps in?

If you do android native code development using NDK, give Visual Studio a try. (Not a typo!!!) Check out: http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html

and: http://code.google.com/p/vs-android/

Use Ant for running program with command line arguments

Can you be a bit more specific about what you're trying to do and how you're trying to do it?

If you're attempting to invoke the program using the <exec> task you might do the following:

<exec executable="name-of-executable">
  <arg value="arg0"/>
  <arg value="arg1"/>
</exec>

Partial Dependency (Databases)

Partial Functional Dependency occurs only in relation with composite keys. Partial functional dependency occurs when one or more non key attribute are depending on a part of the primary key.

Example:

Table: Stud_id, Course_id, Stud_name, Course_Name

Where: Primary Key = Stud_id + Course_id

Then: To determine name of student we use only Stud_id, which is part of primary key.

{Stud_id} -> {Stud_Name}

Hence,Stud_name is partially dependent on Stud_id. This is called partial dependency.

How to overlay image with color in CSS?

Use mutple backgorund on the element, and use a linear-gradient as your color overlay by declaring both start and end color-stops as the same value.

Note that layers in a multi-background declaration are read much like they are rendered, top-to-bottom, so put your overlay first, then your bg image:

#header {
  background: 
    linear-gradient(to bottom, rgba(100, 100, 0, 0.5), rgba(100, 100, 0, 0.5)) cover,
    url(../img/bg.jpg) 0 0 no-repeat fixed;
  height: 100%;
  overflow: hidden;
  color: #FFFFFF
}

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Dynamically add properties to a existing object

Consider using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern

You can change the decorator at runtime with one that has different properties when an event occurs.

'heroku' does not appear to be a git repository

Following official Heroku article:

Initialize GIT

$ cd myapp
$ git init

$ git add .
$ git commit -m "my first commit"

Then create (initialize) heroku app with:

$ heroku create YourAppName

Lastly add git remote:

$ heroku git:remote -a YourAppName

Now you can safely deploy your app with:

$ git push heroku master

You should wait for some time and see if you don't get any error/interrupt on console while deploying. For details look at heroku article.

Evaluate expression given as a string

Alternatively, you can use evals from my pander package to capture output and all warnings, errors and other messages along with the raw results:

> pander::evals("5+5")
[[1]]
$src
[1] "5 + 5"

$result
[1] 10

$output
[1] "[1] 10"

$type
[1] "numeric"

$msg
$msg$messages
NULL

$msg$warnings
NULL

$msg$errors
NULL


$stdout
NULL

attr(,"class")
[1] "evals"

How to select unique records by SQL

just use inner join because group by won't work with multiple columns saying not contained in either an aggregate function.

SELECT a.*
FROM yourtable a
INNER JOIN 
  (SELECT yourcolumn,
    MIN(id) as id
  FROM yourtable 
  GROUP BY yourcolumn
) AS b
  ON a.yourcolumn= b.yourcolumn
  AND a.id = b.id;

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

What is the correct way of reading from a TCP socket in C/C++?

This is an article that I always refer to when working with sockets..

THE WORLD OF SELECT()

It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.

Can't Load URL: The domain of this URL isn't included in the app's domains

Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.

I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.

What's the difference between REST & RESTful

REST(REpresentation State Transfer) is an architecture using which WebServices are created.

and

RESTful is way of writing services using the REST architectures. RESTful services exposes the resources to identify the targets to interact with clients.

Any way to select without causing locking in MySQL?

If the table is InnoDB, see http://dev.mysql.com/doc/refman/5.1/en/innodb-consistent-read.html -- it uses consistent-read (no-locking mode) for SELECTs "that do not specify FOR UPDATE or LOCK IN SHARE MODE if the innodb_locks_unsafe_for_binlog option is set and the isolation level of the transaction is not set to SERIALIZABLE. Thus, no locks are set on rows read from the selected table".

Select first and last row from grouped data

Using data.table:

# convert to data.table
setDT(df) 
# order, group, filter
df[order(stopSequence)][, .SD[c(1, .N)], by = id]

   id stopId stopSequence
1:  1      a            1
2:  1      c            3
3:  2      b            1
4:  2      c            4
5:  3      b            1
6:  3      a            3

SSL "Peer Not Authenticated" error with HttpClient 4.1

Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.

  • CA.crt
  • UTNAddTrustServer_CA.crt
  • AddTrustExternalCARoot.crt

Auto Increment after delete in MySQL

There is actually a way to fix that. First you delete the auto_incremented primary key column, and then you add it again, like this:

ALTER TABLE table_name DROP column_name;
ALTER TABLE table_name ADD column_name int not null auto_increment primary key first;

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Yes, all you need to do is call finish() in any Activity you would like to close.

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

require 'date'

current_time = DateTime.now

current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"

current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"

height: 100% for <div> inside <div> with display: table-cell

set height: 100%; and overflow:auto; for div inside .cell

How to display list items on console window in C#

I found this easier to understand:

List<string> names = new List<string> { "One", "Two", "Three", "Four", "Five" };
        for (int i = 0; i < names.Count; i++)
        {
            Console.WriteLine(names[i]);
        }

Directory-tree listing in Python

The one worked with me is kind of a modified version from Saleh's answer elsewhere on this page.

The code is as follows:

dir = 'given_directory_name'
filenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]

Adjust list style image position?

_x000D_
_x000D_
My solution:_x000D_
_x000D_
ul {_x000D_
    line-height: 1.3 !important;_x000D_
    li {_x000D_
        font-size: x-large;_x000D_
        position: relative;_x000D_
        &:before {_x000D_
            content: '';_x000D_
            display: block;_x000D_
            position: absolute;_x000D_
            top: 5px;_x000D_
            left: -25px;_x000D_
            height: 23px;_x000D_
            width: 23px;_x000D_
            background-image: url(../img/list-char.png) !important;_x000D_
            background-size: 23px;_x000D_
            background-repeat: no-repeat;_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How do I concatenate a boolean to a string in Python?

The recommended way is to let str.format handle the casting (docs). Methods with %s substitution may be deprecated eventually (see PEP3101).

>>> answer = True
>>> myvar = "the answer is {}".format(answer)
>>> print(myvar)
the answer is True

In Python 3.6+ you may use literal string interpolation:

 >>> print(f"the answer is {answer}")
the answer is True

CSS selector (id contains part of text)

Try this:

a[id*='Some:Same'][id$='name']

This will get you all a elements with id containing

Some:Same

and have the id ending in

name

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

Setting size for icon in CSS

this works for me try it.

height:1rem;
font-size: 3.75em;

What is REST? Slightly confused

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

The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.

How to get the data-id attribute?

I have a span. I want to take the value of attribute data-txt-lang, which is used defined.

$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});

Android - Package Name convention

http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

If you have a company domain www.example.com

Then you should use:

com.example.region.projectname

If you own a domain name like example.co.uk than it should be:

uk.co.example.region.projectname

If you do not own a domain, you should then use your email address:

for [email protected] it should be:

com.example.name.region.projectname

How to launch an EXE from Web page (asp.net)

How about something like:

<a href="\\DangerServer\Downloads\MyVirusArchive.exe" 
  type="application/octet-stream">Don't download this file!</a>

What does -1 mean in numpy reshape?

The criterion to satisfy for providing the new shape is that 'The new shape should be compatible with the original shape'

numpy allow us to give one of new shape parameter as -1 (eg: (2,-1) or (-1,3) but not (-1, -1)). It simply means that it is an unknown dimension and we want numpy to figure it out. And numpy will figure this by looking at the 'length of the array and remaining dimensions' and making sure it satisfies the above mentioned criteria

Now see the example.

z = np.array([[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12]])
z.shape
(3, 4)

Now trying to reshape with (-1) . Result new shape is (12,) and is compatible with original shape (3,4)

z.reshape(-1)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

Now trying to reshape with (-1, 1) . We have provided column as 1 but rows as unknown . So we get result new shape as (12, 1).again compatible with original shape(3,4)

z.reshape(-1,1)
array([[ 1],
   [ 2],
   [ 3],
   [ 4],
   [ 5],
   [ 6],
   [ 7],
   [ 8],
   [ 9],
   [10],
   [11],
   [12]])

The above is consistent with numpy advice/error message, to use reshape(-1,1) for a single feature; i.e. single column

Reshape your data using array.reshape(-1, 1) if your data has a single feature

New shape as (-1, 2). row unknown, column 2. we get result new shape as (6, 2)

z.reshape(-1, 2)
array([[ 1,  2],
   [ 3,  4],
   [ 5,  6],
   [ 7,  8],
   [ 9, 10],
   [11, 12]])

Now trying to keep column as unknown. New shape as (1,-1). i.e, row is 1, column unknown. we get result new shape as (1, 12)

z.reshape(1,-1)
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]])

The above is consistent with numpy advice/error message, to use reshape(1,-1) for a single sample; i.e. single row

Reshape your data using array.reshape(1, -1) if it contains a single sample

New shape (2, -1). Row 2, column unknown. we get result new shape as (2,6)

z.reshape(2, -1)
array([[ 1,  2,  3,  4,  5,  6],
   [ 7,  8,  9, 10, 11, 12]])

New shape as (3, -1). Row 3, column unknown. we get result new shape as (3,4)

z.reshape(3, -1)
array([[ 1,  2,  3,  4],
   [ 5,  6,  7,  8],
   [ 9, 10, 11, 12]])

And finally, if we try to provide both dimension as unknown i.e new shape as (-1,-1). It will throw an error

z.reshape(-1, -1)
ValueError: can only specify one unknown dimension

Permanently add a directory to PYTHONPATH?

I added permanently in Windows Vista, Python 3.5

System > Control Panel > Advanced system settings > Advanced (tap) Environment Variables > System variables > (if you don't see PYTHONPATH in Variable column) (click) New > Variable name: PYTHONPATH > Variable value:

Please, write the directory in the Variable value. It is details of Blue Peppers' answer.

SQL query: Delete all records from the table except latest N?

Unfortunately for all the answers given by other folks, you can't DELETE and SELECT from a given table in the same query.

DELETE FROM mytable WHERE id NOT IN (SELECT MAX(id) FROM mytable);

ERROR 1093 (HY000): You can't specify target table 'mytable' for update 
in FROM clause

Nor can MySQL support LIMIT in a subquery. These are limitations of MySQL.

DELETE FROM mytable WHERE id NOT IN 
  (SELECT id FROM mytable ORDER BY id DESC LIMIT 1);

ERROR 1235 (42000): This version of MySQL doesn't yet support 
'LIMIT & IN/ALL/ANY/SOME subquery'

The best answer I can come up with is to do this in two stages:

SELECT id FROM mytable ORDER BY id DESC LIMIT n; 

Collect the id's and make them into a comma-separated string:

DELETE FROM mytable WHERE id NOT IN ( ...comma-separated string... );

(Normally interpolating a comma-separate list into an SQL statement introduces some risk of SQL injection, but in this case the values are not coming from an untrusted source, they are known to be integer values from the database itself.)

note: Though this doesn't get the job done in a single query, sometimes a more simple, get-it-done solution is the most effective.

concatenate two database columns into one resultset column

If both Column are numeric Then Use This code

Just Cast Column As Varchar(Size)

Example:

Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

I ran into a problem in the docker node:current-slim (running npm 7.0.9) where npm install appeared to ignore --production, --only=prod and --only=production. I found two work-arounds:

  1. use ci instead (RUN npm ci --only=production) which requires an up-to-date package-lock.json
  2. before npm install, brutally edit the package.json with:

RUN node -e 'const fs = require("fs"); const pkg = JSON.parse(fs.readFileSync("./package.json", "utf-8")); delete pkg.devDependencies; fs.writeFileSync("./package.json", JSON.stringify(pkg), "utf-8");'

This won't edit your working package.json, just the one copied to the docker container. Of course, this shouldn't be necessary, but if it is (as it was for me), there's your hack.

How do I delete a Git branch locally and remotely?

An alternative option to the command line for deleting remote branches is the GitHub branches page.

See for example: https://github.com/angular/angular.js/branches

Found in the Code -> Branches page of a GitHub repository.

I generally prefer command line myself but this GitHub page shows you lots more information about the branches, such as last updated date and user, and number of commits ahead and behind. It is useful when dealing with a large number of branches.

Java 8 NullPointerException in Collectors.toMap

Sorry to reopen an old question, but since it was edited recently saying that the "issue" still remains in Java 11, I felt like I wanted to point out this:

answerList
        .stream()
        .collect(Collectors.toMap(Answer::getId, Answer::getAnswer));

gives you the null pointer exception because the map does not allow null as a value. This makes sense because if you look in a map for the key k and it is not present, then the returned value is already null (see javadoc). So if you were able to put in k the value null, the map would look like it's behaving oddly.

As someone said in the comments, it's pretty easy to solve this by using filtering:

answerList
        .stream()
        .filter(a -> a.getAnswer() != null)
        .collect(Collectors.toMap(Answer::getId, Answer::getAnswer));

in this way no null values will be inserted in the map, and STILL you will get null as the "value" when looking for an id that does not have an answer in the map.

I hope this makes sense to everyone.

How to Validate on Max File Size in Laravel?

According to the documentation:

$validator = Validator::make($request->all(), [
    'file' => 'max:500000',
]);

The value is in kilobytes. I.e. max:10240 = max 10 MB.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

FB OpenGraph og:image not pulling images (possibly https?)

I don't know, if it's only with me but for me og:image does not work and it picks my site logo, even though facebook debugger shows the correct image.

But changing og:image to og:image:url worked for me. Hope this helps anybody else facing similar issue.

Calling a JavaScript function named in a variable

Definitely avoid using eval to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.

For example, if you were to use the eval solutions proposed here, a nefarious user could send a link to their victim that looked like this:

http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}

And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.

So, make sure you never eval untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:

// set up the possible functions:
var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
  func3: function () { alert('Function 3'); },
  func4: function () { alert('Function 4'); },
  func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();

This will fail if the funcToRun variable doesn't point to anything in the myFuncs object, but it won't execute any code.

jQuery UI tabs. How to select a tab based on its id not based on index

Note: Due to changes made to jQuery 1.9 and jQuery UI, this answer is no longer the correct one. Please see @stankovski's answer below.

You need to find the tab's index first (which is just its position in a list) and then specifically select the tab using jQuery UI's provided select event (tabs->select).

var index = $('#tabs ul').index($('#tabId'));
$('#tabs ul').tabs('select', index);

Update: BTW - I do realize that this is (ultimately) still selecting by index. But, it doesn't require that you know the specific position of the tabs (particularly when they are dynamically generated as asked in the question).

Removing time from a Date object?

You can write that for example:

private Date TruncarFecha(Date fechaParametro) throws ParseException {
    String fecha="";
    DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
    fecha =outputFormatter.format(fechaParametro);
    return outputFormatter.parse(fecha);
}

Difference between HashSet and HashMap?

you pretty much answered your own question - hashset doesn't allow duplicate values. it would be trivial to build a hashset using a backing hashmap (and just a check to see if the value already exists). i guess the various java implementations either do that, or implement some custom code to do it more efficiently.

delete all from table

This is deletes the table table_name.

Replace it with the name of the table, which shall be deleted.

DELETE FROM table_name;

Gson library in Android Studio

Use gradle dependencies to get the Gson in your project. Your application build.gradle should look like this-

dependencies {
  implementation 'com.google.code.gson:gson:2.8.2'
}

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

How to format a java.sql Timestamp for displaying?

java.time

I am providing the modern answer. The Timestamp class is a hack on top of the already poorly designed java.util.Date class and is long outdated. I am assuming, though, that you are getting a Timestamp from a legacy API that you cannot afford to upgrade to java.time just now. When you do that, convert it to a modern Instant and do further processing from there.

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(Locale.GERMAN);
    
    Timestamp oldfashionedTimestamp = new Timestamp(1_567_890_123_456L);
    
    ZonedDateTime dateTime = oldfashionedTimestamp.toInstant()
            .atZone(ZoneId.systemDefault());
    String desiredFormat = dateTime.format(formatter);
    
    System.out.println(desiredFormat);

Output in my time zone:

07.09.2019 23:02:03

Pick how long or short of a format you want by specifying FormatStyle.SHORT, .MEDIUM, .LONG or .FULL. Pick your own locale where I put Locale.GERMAN. And pick your desired time zone, for example ZoneId.of("Europe/Oslo"). A Timestamp is a point in time without time zone, so we need a time zone to be able to convert it into year, month, day, hour, minute, etc. If your Timestamp comes from a database value of type timestamp without time zone (generally not recommended, but unfortunately often seen), ZoneId.systemDefault() is likely to give you the correct result. Another and slightly simpler option in this case is instead to convert to a LocalDateTime using oldfashionedTimestamp.toLocalDateTime() and then format the LocalDateTime in the same way as I did with the ZonedDateTime.

How to start rails server?

For rails 3.2.3 and latest version of rails you can start server by:
First install all gem with command: bundle install or bundle.
Then Configure your database to the database.yml.
Create new database: rake db:create
Then start rails server.
rails server orrails s

How to run Nginx within a Docker container without halting?

It is also good idea to use supervisord or runit[1] for service management.

[1] https://github.com/phusion/baseimage-docker

Error: could not find function "%>%"

You need to load a package (like magrittr or dplyr) that defines the function first, then it should work.

install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr")    # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr)    # alternatively, this also loads %>%

The pipe operator %>% was introduced to "decrease development time and to improve readability and maintainability of code."

But everybody has to decide for himself if it really fits his workflow and makes things easier. For more information on magrittr, click here.

Not using the pipe %>%, this code would return the same as your code:

words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words

EDIT: (I am extending my answer due to a very useful comment that was made by @Molx)

Despite being from magrittr, the pipe operator is more commonly used with the package dplyr (which requires and loads magrittr), so whenever you see someone using %>% make sure you shouldn't load dplyr instead.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Find the number of employees in each department - SQL Oracle

select  d.dname
       ,count(e.empno) as count 
from dept d 
left outer join emp e 
  on e.deptno=d.deptno 
group by d.dname;

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

If you're getting this error, you're probably trying to write to wwwroot. By default this is not allowed, for good reason.

Instead, consider storing your files somewhere besides wwwroot. If you just need to serve the files, store them in a folder outside of inetpub and use a virtual directory to make them visible to IIS.

Original answer:


For those running IIS on Windows Server:

By default, the IIS user does not have write permissions for the wwwroot folder. This can be solved by granting full permissions to the IIS_IUSRS user for wwwroot.

  1. Open File Explorer and go to C:/inetpub/
  2. Right click on wwwroot and click on "Properties"
  3. Go to the Security tab and click "Edit..." to edit permissions
  4. Find and select the IIS user. In my case, it was called IIS_IUSRS ([server name]\IIS_IUSRS).
  5. Select the "Allow" checkbox for all permissions.

Keeping ASP.NET Session Open / Alive

[Late to the party...]

Another way to do this without the overhead of an Ajax call or WebService handler is to load a special ASPX page after a given amount of time (i.e., prior to the session state time-out, which is typically 20 minutes):

// Client-side JavaScript
function pingServer() {
    // Force the loading of a keep-alive ASPX page
    var img = new Image(1, 1);
    img.src = '/KeepAlive.aspx';
}

The KeepAlive.aspx page is simply an empty page which does nothing but touch/refresh the Session state:

// KeepAlive.aspx.cs
public partial class KeepSessionAlive: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Refresh the current user session
        Session["refreshTime"] = DateTime.UtcNow;
    }
}

This works by creating an img (image) element and forcing the browser to load its contents from the KeepAlive.aspx page. Loading that page causes the server to touch (update) the Session object, extending the session's expiration sliding time window (typically by another 20 minutes). The actual web page contents are discarded by the browser.

An alternative, and perhaps cleaner, way to do this is to create a new iframe element and load the KeepAlive.aspx page into it. The iframe element is hidden, such as by making it a child element of a hidden div element somewhere on the page.

Activity on the page itself can be detected by intercepting mouse and keyboard actions for the entire page body:

// Called when activity is detected
function activityDetected(evt) {
    ...
}

// Watch for mouse or keyboard activity
function watchForActivity() {
    var opts = { passive: true };
    document.body.addEventListener('mousemove', activityDetected, opts);
    document.body.addEventListener('keydown', activityDetected, opts);
}

I cannot take credit for this idea; see: https://www.codeproject.com/Articles/227382/Alert-Session-Time-out-in-ASP-Net.

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

This is a problem of M2E for Eclipse M2E plugin execution not covered.

To solve this problem, all you got to do is to map the lifecycle it doesn't recognize and instruct M2E to execute it.

You should add this after your plugins, inside the build. This will remove the error and make M2E recognize the goal copy-depencies of maven-dependency-plugin and make the POM work as expected, copying dependencies to folder every time Eclipse build it. If you just want to ignore the error, then you change <execute /> for <ignore />. No need for enclosing your maven-dependency-plugin into pluginManagement, as suggested before.

<pluginManagement>
  <plugins>
    <plugin>
      <groupId>org.eclipse.m2e</groupId>
      <artifactId>lifecycle-mapping</artifactId>
      <version>1.0.0</version>
      <configuration>
        <lifecycleMappingMetadata>
          <pluginExecutions>
            <pluginExecution>
              <pluginExecutionFilter>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <versionRange>[2.0,)</versionRange>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
              </pluginExecutionFilter>
              <action>
                <execute />
              </action>
            </pluginExecution>
          </pluginExecutions>
        </lifecycleMappingMetadata>
      </configuration>
    </plugin>
  </plugins>
</pluginManagement>

MySql Table Insert if not exist otherwise update

Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.

Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.

Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)

Detect click inside/outside of element with single event handler

Instead of using the body you could create a curtain with z-index of 100 (to pick a number) and give the inside element a higher z-index while all other elements have a lower z-index than the curtain.

See working example here: http://jsfiddle.net/Flandre/6JvFk/

jQuery:

$('#curtain').on("click", function(e) {

    $(this).hide();
    alert("clicked ouside of elements that stand out");

});

CSS:

.aboveCurtain
{
    z-index: 200; /* has to have a higher index than the curtain */
    position: relative;
    background-color: pink;
}

#curtain
{
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    background-color: black;
    width: 100%;
    z-index:100;   
    opacity:0.5 /* change opacity to 0 to make it a true glass effect */
}

How to fix curl: (60) SSL certificate: Invalid certificate chain

Using the Safari browser (not Chrome, Firefox or Opera) on Mac OS X 10.9 (Mavericks) visit https://registry.npmjs.org

Screenshot of Safari showing certificate error

Click the Show certificate button and then check the checkbox labelled Always trust. Then click Continue and enter your password if required.

Always trust checkbox

Curl should now work with that URL correctly.

How can I enter latitude and longitude in Google Maps?

First is latitude, second longitude. Different than many constructors in mapbox.

Here are examples of formats that work:

  • Degrees, minutes, and seconds (DMS): 41°24'12.2"N 2°10'26.5"E
  • Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418
  • Decimal degrees (DD): 41.40338, 2.17403

Tips for formatting your coordinates

  • Use the degree symbol instead of “d”.
  • Use periods as decimals, not commas.
    • Incorrect: 41,40338, 2,17403.
    • Correct: 41.40338, 2.17403.
  • List your latitude coordinates before longitude coordinates.
  • Check that the first number in your latitude coordinate is between -90 and 90 and the first number in your longitude coordinate is between -180 and 180.

https://support.google.com/maps/answer/18539

Print array elements on separate lines in Bash?

Using for:

for each in "${alpha[@]}"
do
  echo "$each"
done

Using history; note this will fail if your values contain !:

history -p "${alpha[@]}"

Using basename; note this will fail if your values contain /:

basename -a "${alpha[@]}"

Using shuf; note that results might not come out in order:

shuf -e "${alpha[@]}"

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

document.body.appendChild(i)

In 2019 you can use querySelector for that.

It's supported by most browsers (https://caniuse.com/#search=querySelector)

document.querySelector('body').appendChild(i);

Google Chrome form autofill and its yellow background

This fixes the problem on both Safari and Chrome

if(navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 || navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
window.setInterval(function(){
    $('input:-webkit-autofill').each(function(){
        var clone = $(this).clone(true, true);
        $(this).after(clone).remove();
    });
}, 20);
}

How does origin/HEAD get set?

What moves origin/HEAD "organically"?

  • git clone sets it once to the spot where HEAD is on origin
    • it serves as the default branch to checkout after cloning with git clone

What does HEAD on origin represent?

  • on bare repositories (often repositories “on servers”) it serves as a marker for the default branch, because git clone uses it in such a way
  • on non-bare repositories (local or remote), it reflects the repository’s current checkout

What sets origin/HEAD?

  • git clone fetches and sets it
  • it would make sense if git fetch updates it like any other reference, but it doesn’t
  • git remote set-head origin -a fetches and sets it
    • useful to update the local knowledge of what remote considers the “default branch”

Trivia

  • origin/HEAD can also be set to any other value without contacting the remote: git remote set-head origin <branch>
    • I see no use-case for this, except for testing
  • unfortunately nothing is able to set HEAD on the remote
  • older versions of git did not know which branch HEAD points to on the remote, only which commit hash it finally has: so it just hopefully picked a branch name pointing to the same hash

UIScrollView scroll to bottom programmatically

I found that contentSize doesn't really reflect the actual size of the text, so when trying to scroll to the bottom, it will be a little bit off. The best way to determine the actual content size is actually to use the NSLayoutManager's usedRectForTextContainer: method:

UITextView *textView;
CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;

To determine how much text actually is shown in the UITextView, you can calculate it by subtracting the text container insets from the frame height.

UITextView *textView;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom;

Then it becomes easy to scroll:

// if you want scroll animation, use contentOffset
UITextView *textView;
textView.contentOffset = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);

// if you don't want scroll animation
CGRect scrollBounds = textView.bounds;
scrollBounds.origin = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);
textView.bounds = scrollBounds;

Some numbers for reference on what the different sizes represent for an empty UITextView.

textView.frame.size = (width=246, height=50)
textSize = (width=10, height=16.701999999999998)
textView.contentSize = (width=246, height=33)
textView.textContainerInset = (top=8, left=0, bottom=8, right=0)

How do I simulate placeholder functionality on input date field?

Got the most easiest hack for this problem-use this syntax in your HTML-input-tag

      <input type="text" id="my_element_id" placeholder="select a date" name="my_element_name" onfocus="(this.type='date')" />
      </div>