问:
How to perform doubleclick?
I know, there are a lot of questions like this. But every answer i read, did not helped me.. So i ask here.

I want to perform a mouse double click. Before that i have already set the cursor to the correct position:

```<code>  Cursor.Position = new System.Drawing.Point(2225, 154);
</code>```

I already used almost every class i found here, and no one helped me. (The cursor was set, but no double click were performed..)

Hope anyone can help me. Thanks!

Greets

edit:
the class i used:

```<code>using System;
using System.Runtime.InteropServices;

namespace AutoClicker
{

    public class MouseSimulator
    {

      public void test_Click(System.Drawing.Point p)
           {
            //Move the mouse to the button position

            //Perform button click.
            INPUT structInput = new INPUT();
            structInput.type = SendInputEventType.InputMouse;
            structInput.mkhi.mi.dwFlags = MouseEventFlags.ABSOLUTE | MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP;
            structInput.mkhi.mi.dx = p.X;
            structInput.mkhi.mi.dy = p.Y;
            uint i = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
        }

        [DllImport("user32.dll")]
        static extern IntPtr GetMessageExtraInfo();

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);

        [Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004,
            MIDDLEDOWN = 0x00000020,
            MIDDLEUP = 0x00000040,
            MOVE = 0x00000001,
            ABSOLUTE = 0x00008000,
            RIGHTDOWN = 0x00000008,
            RIGHTUP = 0x00000010
        }

        /// <summary>
        /// The event type contained in the union field
        /// </summary>
        enum SendInputEventType : int
        {
            /// <summary>
            /// Contains Mouse event data
            /// </summary>
            InputMouse,
            /// <summary>
            /// Contains Keyboard event data
            /// </summary>
            InputKeyboard,
            /// <summary>
            /// Contains Hardware event data
            /// </summary>
            InputHardware
        }

        /// <summary>
        /// The mouse data structure
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        struct MouseInputData
        {
            /// <summary>
            /// The x value, if ABSOLUTE is passed in the flag then this is an actual X and Y value
            /// otherwise it is a delta from the last position
            /// </summary>
            public int dx;
            /// <summary>
            /// The y value, if ABSOLUTE is passed in the flag then this is an actual X and Y value
            /// otherwise it is a delta from the last position
            /// </summary>
            public int dy;
            /// <summary>
            /// Wheel event data, X buttons
            /// </summary>
            public uint mouseData;
            /// <summary>
            /// ORable field with the various flags about buttons and nature of event
            /// </summary>
            public MouseEventFlags dwFlags;
            /// <summary>
            /// The timestamp for the event, if zero then the system will provide
            /// </summary>
            public uint time;
            /// <summary>
            /// Additional data obtained by calling app via GetMessageExtraInfo
            /// </summary>
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct KEYBDINPUT
        {
            public ushort wVk;
            public ushort wScan;
            public uint dwFlags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct HARDWAREINPUT
        {
            public int uMsg;
            public short wParamL;
            public short wParamH;
        }

        /// <summary>
        /// Captures the union of the three three structures.
        /// </summary>
        [StructLayout(LayoutKind.Explicit)]
        struct MouseKeybdhardwareInputUnion
        {
            /// <summary>
            /// The Mouse Input Data
            /// </summary>
            [FieldOffset(0)]
            public MouseInputData mi;

            /// <summary>
            /// The Keyboard input data
            /// </summary>
            [FieldOffset(0)]
            public KEYBDINPUT ki;

            /// <summary>
            /// The hardware input data
            /// </summary>
            [FieldOffset(0)]
            public HARDWAREINPUT hi;
        }

        /// <summary>
        /// The Data passed to SendInput in an array.
        /// </summary>
        /// <remarks>Contains a union field type specifies what it contains </remarks>
        [StructLayout(LayoutKind.Sequential)]
        struct INPUT
        {
            /// <summary>
            /// The actual data type contained in the union Field
            /// </summary>
            public SendInputEventType type;
            public MouseKeybdhardwareInputUnion mkhi;
        }
    }

}
</code>```

and i used it like this:

```<code>System.Drawing.Point p = new System.Drawing.Point(2225, 154);
        Cursor.Position = p;
        MouseSimulator ms = new MouseSimulator();
        ms.test_Click(p);
</code>```

答:
If you need ti simulate the double click, you need to send 4 INPUT using SendInput():

```<code>public void test_Click(System.Drawing.Point p) {
    //Move the mouse to the button position

    //Perform button click.
    INPUT down = new INPUT();
    down.type = SendInputEventType.InputMouse;
    down.mkhi.mi.dx = p.X;
    down.mkhi.mi.dy = p.Y;
    down.mkhi.mi.dwFlags = MouseEventFlags.LEFTDOWN;

    INPUT up = new INPUT();
    up.type = SendInputEventType.InputMouse;
    up.mkhi.mi.dx = p.X;
    up.mkhi.mi.dy = p.Y;
    up.mkhi.mi.dwFlags = MouseEventFlags.LEFTUP;

    INPUT[] dbl = {down, up, down, up};

    SendInput(4, dbl, Marshal.SizeOf(down));
}
</code>```

Also, define SendInput() as follows:

```<code>static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
</code>```

Title: How to perform doubleclick?

Body:
I know, there are a lot of questions like this. But every answer i read, did not helped me.. So i ask here.

I want to perform a mouse double click. Before that i have already set the cursor to the correct position:

  Cursor.Position = new System.Drawing.Point(2225, 154);

I already used almost every class i found here, and no one helped me. (The cursor was set, but no double click were performed..)

Hope anyone can help me. Thanks!

Greets

edit:
the class i used:

using System;
using System.Runtime.InteropServices;

namespace AutoClicker
{

    public class MouseSimulator
    {

      public void test_Click(System.Drawing.Point p)
           {
            //Move the mouse to the button position

            //Perform button click.
            INPUT structInput = new INPUT();
            structInput.type = SendInputEventType.InputMouse;
            structInput.mkhi.mi.dwFlags = MouseEventFlags.ABSOLUTE | MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP;
            structInput.mkhi.mi.dx = p.X;
            structInput.mkhi.mi.dy = p.Y;
            uint i = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
        }

        [DllImport("user32.dll")]
        static extern IntPtr GetMessageExtraInfo();

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);

        [Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004,
            MIDDLEDOWN = 0x00000020,
            MIDDLEUP = 0x00000040,
            MOVE = 0x00000001,
            ABSOLUTE = 0x00008000,
            RIGHTDOWN = 0x00000008,
            RIGHTUP = 0x00000010
        }

        ///
        /// The event type contained in the union field
        ///
        enum SendInputEventType : int
        {
            ///
            /// Contains Mouse event data
            ///
            InputMouse,
            ///
            /// Contains Keyboard event data
            ///
            InputKeyboard,
            ///
            /// Contains Hardware event data
            ///
            InputHardware
        }

        ///
        /// The mouse data structure
        ///
        [StructLayout(LayoutKind.Sequential)]
        struct MouseInputData
        {
            ///
            /// The x value, if ABSOLUTE is passed in the flag then this is an actual X and Y value
            /// otherwise it is a delta from the last position
            ///
            public int dx;
            ///
            /// The y value, if ABSOLUTE is passed in the flag then this is an actual X and Y value
            /// otherwise it is a delta from the last position
            ///
            public int dy;
            ///
            /// Wheel event data, X buttons
            ///
            public uint mouseData;
            ///
            /// ORable field with the various flags about buttons and nature of event
            ///
            public MouseEventFlags dwFlags;
            ///
            /// The timestamp for the event, if zero then the system will provide
            ///
            public uint time;
            ///
            /// Additional data obtained by calling app via GetMessageExtraInfo
            ///
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct KEYBDINPUT
        {
            public ushort wVk;
            public ushort wScan;
            public uint dwFlags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct HARDWAREINPUT
        {
            public int uMsg;
            public short wParamL;
            public short wParamH;
        }

        ///
        /// Captures the union of the three three structures.
        ///
        [StructLayout(LayoutKind.Explicit)]
        struct MouseKeybdhardwareInputUnion
        {
            ///
            /// The Mouse Input Data
            ///
            [FieldOffset(0)]
            public MouseInputData mi;

            ///
            /// The Keyboard input data
            ///
            [FieldOffset(0)]
            public KEYBDINPUT ki;

            ///
            /// The hardware input data
            ///
            [FieldOffset(0)]
            public HARDWAREINPUT hi;
        }

        ///
        /// The Data passed to SendInput in an array.
        ///
        /// <remarks>Contains a union field type specifies what it contains </remarks>
        [StructLayout(LayoutKind.Sequential)]
        struct INPUT
        {
            ///
            /// The actual data type contained in the union Field
            ///
            public SendInputEventType type;
            public MouseKeybdhardwareInputUnion mkhi;
        }
    }

}

and i used it like this:

System.Drawing.Point p = new System.Drawing.Point(2225, 154);
        Cursor.Position = p;
        MouseSimulator ms = new MouseSimulator();
        ms.test_Click(p);

Body:
If you need ti simulate the double click, you need to send 4 INPUT using SendInput():

public void test_Click(System.Drawing.Point p) {
    //Move the mouse to the button position

    //Perform button click.
    INPUT down = new INPUT();
    down.type = SendInputEventType.InputMouse;
    down.mkhi.mi.dx = p.X;
    down.mkhi.mi.dy = p.Y;
    down.mkhi.mi.dwFlags = MouseEventFlags.LEFTDOWN;

    INPUT up = new INPUT();
    up.type = SendInputEventType.InputMouse;
    up.mkhi.mi.dx = p.X;
    up.mkhi.mi.dy = p.Y;
    up.mkhi.mi.dwFlags = MouseEventFlags.LEFTUP;

    INPUT[] dbl = {down, up, down, up};

    SendInput(4, dbl, Marshal.SizeOf(down));
}

Also, define SendInput() as follows:

static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);


来源: stackexchange

问:
Using Boyer–Moore algorithms in 64 bit processes
Im in the process of making an memory scanner app similar to cheat engine, but would like to do it in c#, as an test project...
so, i was using a lib that makes use of https://github.com/Adversities/Cheatool
which uses Boyer–Moore.

the process detection is working..and in 32 bit processes i can find Array of bytes like `

60 8A DD 01 48 00 00 BC 88 01 04 02 00 01 44 D0 30 60 8C DD 01 46 AD
  1F 00 2A 12 10 00 00 29

` correctly if i look for them using the Boyer–Moore method...

but for some reason i cant find them in 64 bit processes.

how can i update the methods found in the dll lib and my app to accommodate 64 bit processes as well?
now, as im quite new to c#, and like experimenting, i drafted an test app:

code of Testing application:

```<code>   using System;
using System.Diagnostics;

using System.Linq;

using System.Threading.Tasks;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using System.Threading;

namespace MemTester
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Memory Addres Tester [?] (PID: ?)";

            //Console.Write("Process to open => ");
            //string process = Console.ReadLine();
            string process = " ";
            int ppid = 0;
            while (ppid == 0)
            {
                Console.Write("Process PID to open as int=> ");
                string ppid2 = Console.ReadLine();
                if ((ppid2 == "") || (ppid2 == null) || (ppid2.Length < 2))
                { ppid2 = "0"; }
                ppid = Convert.ToInt32(ppid2);
            }
            while (true)
            {
                Console.Write("Value to scan => ");
                string aob = Console.ReadLine();
                if (aob == "exit") break;

                MeMory(process, aob, ppid);
            }
        }
        public abstract class Manager
        {
            [DllImport("KERNEL32.DLL", SetLastError = true)]
            public static extern bool WriteProcessMemory(
                IntPtr process, IntPtr address, byte[] buffer, uint size, ref uint written);

            [DllImport("KERNEL32.DLL")]
            public static extern bool VirtualProtectEx(IntPtr process, IntPtr address,
                uint size, uint access, out uint oldProtect);

            [DllImport("KERNEL32.DLL")]
            public static extern int CloseHandle(IntPtr objectHandle);

            [DllImport("KERNEL32.DLL")]
            public static extern IntPtr OpenProcess(uint access, bool inheritHandler, uint processId);

            [Flags]
            public enum Protection
            {
                PEReadWrite = 0x40,
                PReadWrite = 0x04
            }

            [Flags]
            public enum Access
            {
                Synchronize = 0x100000,
                StandardRightsRequired = 0x000F0000,
                AllAccess = StandardRightsRequired | Synchronize | 0xFFFF
            }
        }
        public abstract class Reader
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct MEMORY_BASIC_INFORMATION
            {
                public IntPtr BaseAddress;
                public IntPtr AllocationBase;
                public uint AllocationProtect;
                public uint RegionSize;
                public uint State;
                public uint Protect;
                public uint Type;
            }

            [DllImport("KERNEL32.DLL")]
            public static extern int VirtualQueryEx(IntPtr hProcess,
                IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);

            [DllImport("KERNEL32.DLL", SetLastError = true)]
            public static extern bool ReadProcessMemory(
                IntPtr process, IntPtr address, byte[] buffer, uint size, ref uint read);

            public List<MEMORY_BASIC_INFORMATION> MemoryRegion = new List<MEMORY_BASIC_INFORMATION>();
        }
        public class BoyerMoore : Reader
        {
            private IntPtr _processHandle;

            public BoyerMoore(IntPtr processHandle)
            {
                _processHandle = processHandle;
            }

            private void MemInfo(bool unwritable)
            {
                IntPtr Addy = new IntPtr();

                while (true)
                {
                    MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION();

                    int MemDump = VirtualQueryEx(_processHandle, Addy, out memInfo, Marshal.SizeOf(memInfo));

                    if (MemDump == 0) break;

                    if ((memInfo.State & 0x1000) != 0)
                    {
                        if (unwritable && (memInfo.Protect & 0xCC) != 0)
                            MemoryRegion.Add(memInfo);
                        else
                            MemoryRegion.Add(memInfo);
                    }

                    Addy = new IntPtr(memInfo.BaseAddress.ToInt32() + (int)memInfo.RegionSize);
                }
            }

            private void BoyerAlgo(IntPtr baseAddress, byte[] memoryBrick, byte[] pattern, ref List<IntPtr> addresses)
            {
                int offSet = 0;
                while ((offSet = Array.IndexOf(memoryBrick, pattern[0], offSet)) != -1)
                {
                    if (pattern.Length > 1)
                        for (int i = 1; i < pattern.Length; i++)
                        {
                            if (memoryBrick.Length <= offSet + pattern.Length
                                || pattern[i] != memoryBrick[offSet + i]) break;

                            if (i == pattern.Length - 1)
                                addresses.Add(new IntPtr((int)baseAddress + offSet));
                        }
                    else addresses.Add(new IntPtr((int)baseAddress + offSet));
                    offSet++;
                }
            }

            private void BoyerAlgo(IntPtr baseAddress, byte[] memoryBrick, string pattern, ref List<IntPtr> addresses)
            {
                int offSet = 0;
                string[] aob = pattern.Split(' ');
                List<int> bytesPos = new List<int>();

                for (int i = 0; i < aob.Length; i++)
                    if (aob[i] != "??")
                        bytesPos.Add(i);

                if (bytesPos.Count != 0)
                    while ((offSet = Array.IndexOf(memoryBrick, (byte)Convert.ToInt32(aob[bytesPos[0]], 16), offSet)) != -1)
                    {
                        if (bytesPos.Count > 1)
                            for (int i = 1; i < bytesPos.Count; i++)
                            {
                                if (memoryBrick.Length <= offSet + pattern.Length
                                    || (byte)Convert.ToInt32(aob[bytesPos[i]], 16)
                                    != memoryBrick[(offSet - bytesPos[0]) + bytesPos[i]]) break;

                                if (i == bytesPos.Count - 1)
                                    if (aob[0] == "??")
                                        addresses.Add(new IntPtr((int)baseAddress + (offSet - bytesPos[0])));
                                    else addresses.Add(new IntPtr((int)baseAddress + offSet));
                            }
                        else
                            addresses.Add(new IntPtr((int)baseAddress + (offSet - bytesPos[0])));
                        offSet++;
                    }
                else
                    for (int i = 0; i < memoryBrick.Length; i++)
                        addresses.Add(new IntPtr((int)baseAddress + i));
            }

            public CancellationTokenSource cancelToken { get; set; } = new CancellationTokenSource();

            public Task<IntPtr[]> AoByte(string pattern, bool unwritable = false)
            {
                if (!pattern.Contains("?"))
                {
                    byte[] buff = pattern.Split(' ').Select(by =>
                    (byte)Convert.ToInt32(by, 16)).ToArray();

                    return Task.Run(() => { return GeneralScan(buff, unwritable); }, cancelToken.Token);
                }
                else return Task.Run(() => { return WCScan(pattern, unwritable); }, cancelToken.Token);
            }

            private IntPtr[] GeneralScan(byte[] buff, bool unwritable)
            {
                MemInfo(unwritable);

                List<IntPtr> addresses = new List<IntPtr>();

                for (int i = 0; i < MemoryRegion.Count; i++)
                {
                    uint read = 0;
                    byte[] wholeMemory = new byte[MemoryRegion[i].RegionSize];

                    ReadProcessMemory(_processHandle, MemoryRegion[i].BaseAddress, wholeMemory,
                        MemoryRegion[i].RegionSize, ref read);

                    BoyerAlgo(MemoryRegion[i].BaseAddress, wholeMemory, buff, ref addresses);
                }
                return addresses.ToArray();
            }

            private IntPtr[] WCScan(string pattern, bool unwritable)
            {
                MemInfo(unwritable);

                List<IntPtr> addresses = new List<IntPtr>();

                for (int i = 0; i < MemoryRegion.Count; i++)
                {
                    uint read = 0;
                    byte[] wholeMemory = new byte[MemoryRegion[i].RegionSize];

                    ReadProcessMemory(_processHandle, MemoryRegion[i].BaseAddress, wholeMemory,
                        MemoryRegion[i].RegionSize, ref read);

                    BoyerAlgo(MemoryRegion[i].BaseAddress, wholeMemory, pattern, ref addresses);
                }
                return addresses.ToArray();
            }
        }

        public class MeMorybox : Manager
        {

            public BoyerMoore BoyerScan { get; set; }

            IntPtr _processHandle;

            public MeMorybox(Process process)
            {
                _processHandle = OpenProcess((uint)Access.AllAccess, false, (uint)process.Id);

                BoyerScan = new BoyerMoore(_processHandle);

            }

            ~MeMorybox()
            {
                CloseHandle(_processHandle);
            }

        }

        static void MeMory(string process, string aob, int ppid)
        {
            //Process[] processList = Process.GetProcessesByName(process);
            Process p = Process.GetProcessById(ppid); ;

            MeMorybox notepad = new MeMorybox(p);

            Console.WriteLine("Hex value of pid:"+p.Id.ToString("x8"));

            var addresses = notepad.BoyerScan.AoByte(aob).GetAwaiter().GetResult();

        Console.WriteLine(addresses.Length + " hits found for pid:"+ppid);

        Console.WriteLine();
    }
}
</code>```

testing for flash process..
  firefox..<32 bit process>
  chrome..<64 bit process>
  url to test: https://apps.facebook.com/candycrushsoda

array of byte to search as test:60 ?? ?? ?? ?? ?? ?? ?? ?? 01 ?? ?? 00 01 44 ?? ?? ?? ?? ?? ?? ?? ?? ?? 00 2A 12 10 00 00 29

it should give 1 result

in firefox--Flashplayerplugin it works fine,

in chrome--one of the processes containing module pepflashplayer.dll it >gives no result, as chrome is a 64 bit process.

To verify i double checked by using cheatengine, in both cases the aob is found correctly

答:
I tried your code and for me, when inspecting a 64 bit process it produced arithmetic overflow on the line :

```<code>      Addy = new IntPtr(memInfo.BaseAddress.ToInt32() + (int) memInfo.RegionSize);
</code>```

(Try it for yourself, turn on Build / Advanced.../ Check for arithmetic... in the project settings)

It looks like VirtualQueryEx may fill in MEMORY_BASIC_INFORMATION.BaseAddress with Int32.MaxValue() when querying 64 bit processes.

I think the easiest way to make it compatible with both 32 and 64 bit processes would be to target only 64 bit architecture and write your code accordingly, if you can afford that.
I suggest you try the following:

Change the project's platform target to x64

Update MEMORY_BASIC_INFORMATION so that it maps to the 64 bit version of the struct (the bottom one in Remarks), instead of the other one.  https://msdn.microsoft.com/en-us/library/windows/desktop/aa366775(v=vs.85).aspx

After that update the code to use 64 bit arithmetic whereever it uses BaseAddress or RegionSize (e.g make them IntPtr and use .ToInt64() instead of .ToInt32())

ContentLicense: CC BY-SA 3.0

Body:
Im in the process of making an memory scanner app similar to cheat engine, but would like to do it in c#, as an test project...
so, i was using a lib that makes use of https://github.com/Adversities/Cheatool
which uses Boyer–Moore.

the process detection is working..and in 32 bit processes i can find Array of bytes like `

60 8A DD 01 48 00 00 BC 88 01 04 02 00 01 44 D0 30 60 8C DD 01 46 AD
  1F 00 2A 12 10 00 00 29

` correctly if i look for them using the Boyer–Moore method...

but for some reason i cant find them in 64 bit processes.

how can i update the methods found in the dll lib and my app to accommodate 64 bit processes as well?
now, as im quite new to c#, and like experimenting, i drafted an test app:

code of Testing application:

   using System;
using System.Diagnostics;

using System.Linq;

using System.Threading.Tasks;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using System.Threading;

namespace MemTester
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Memory Addres Tester [?] (PID: ?)";

            //Console.Write("Process to open => ");
            //string process = Console.ReadLine();
            string process = " ";
            int ppid = 0;
            while (ppid == 0)
            {
                Console.Write("Process PID to open as int=> ");
                string ppid2 = Console.ReadLine();
                if ((ppid2 == "") || (ppid2 == null) || (ppid2.Length < 2))
                { ppid2 = "0"; }
                ppid = Convert.ToInt32(ppid2);
            }
            while (true)
            {
                Console.Write("Value to scan => ");
                string aob = Console.ReadLine();
                if (aob == "exit") break;

                MeMory(process, aob, ppid);
            }
        }
        public abstract class Manager
        {
            [DllImport("KERNEL32.DLL", SetLastError = true)]
            public static extern bool WriteProcessMemory(
                IntPtr process, IntPtr address, byte[] buffer, uint size, ref uint written);

            [DllImport("KERNEL32.DLL")]
            public static extern bool VirtualProtectEx(IntPtr process, IntPtr address,
                uint size, uint access, out uint oldProtect);

            [DllImport("KERNEL32.DLL")]
            public static extern int CloseHandle(IntPtr objectHandle);

            [DllImport("KERNEL32.DLL")]
            public static extern IntPtr OpenProcess(uint access, bool inheritHandler, uint processId);

            [Flags]
            public enum Protection
            {
                PEReadWrite = 0x40,
                PReadWrite = 0x04
            }

            [Flags]
            public enum Access
            {
                Synchronize = 0x100000,
                StandardRightsRequired = 0x000F0000,
                AllAccess = StandardRightsRequired | Synchronize | 0xFFFF
            }
        }
        public abstract class Reader
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct MEMORY_BASIC_INFORMATION
            {
                public IntPtr BaseAddress;
                public IntPtr AllocationBase;
                public uint AllocationProtect;
                public uint RegionSize;
                public uint State;
                public uint Protect;
                public uint Type;
            }

            [DllImport("KERNEL32.DLL")]
            public static extern int VirtualQueryEx(IntPtr hProcess,
                IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);

            [DllImport("KERNEL32.DLL", SetLastError = true)]
            public static extern bool ReadProcessMemory(
                IntPtr process, IntPtr address, byte[] buffer, uint size, ref uint read);

            public List<MEMORY_BASIC_INFORMATION> MemoryRegion = new List<MEMORY_BASIC_INFORMATION>();
        }
        public class BoyerMoore : Reader
        {
            private IntPtr _processHandle;

            public BoyerMoore(IntPtr processHandle)
            {
                _processHandle = processHandle;
            }

            private void MemInfo(bool unwritable)
            {
                IntPtr Addy = new IntPtr();

                while (true)
                {
                    MEMORY_BASIC_INFORMATION memInfo = new MEMORY_BASIC_INFORMATION();

                    int MemDump = VirtualQueryEx(_processHandle, Addy, out memInfo, Marshal.SizeOf(memInfo));

                    if (MemDump == 0) break;

                    if ((memInfo.State & 0x1000) != 0)
                    {
                        if (unwritable && (memInfo.Protect & 0xCC) != 0)
                            MemoryRegion.Add(memInfo);
                        else
                            MemoryRegion.Add(memInfo);
                    }

                    Addy = new IntPtr(memInfo.BaseAddress.ToInt32() + (int)memInfo.RegionSize);
                }
            }

            private void BoyerAlgo(IntPtr baseAddress, byte[] memoryBrick, byte[] pattern, ref List<IntPtr> addresses)
            {
                int offSet = 0;
                while ((offSet = Array.IndexOf(memoryBrick, pattern[0], offSet)) != -1)
                {
                    if (pattern.Length > 1)
                        for (int i = 1; i < pattern.Length; i++)
                        {
                            if (memoryBrick.Length <= offSet + pattern.Length
                                || pattern[i] != memoryBrick[offSet + i]) break;

                            if (i == pattern.Length - 1)
                                addresses.Add(new IntPtr((int)baseAddress + offSet));
                        }
                    else addresses.Add(new IntPtr((int)baseAddress + offSet));
                    offSet++;
                }
            }

            private void BoyerAlgo(IntPtr baseAddress, byte[] memoryBrick, string pattern, ref List<IntPtr> addresses)
            {
                int offSet = 0;
                string[] aob = pattern.Split(' ');
                List<int> bytesPos = new List<int>();

                for (int i = 0; i < aob.Length; i++)
                    if (aob[i] != "??")
                        bytesPos.Add(i);

                if (bytesPos.Count != 0)
                    while ((offSet = Array.IndexOf(memoryBrick, (byte)Convert.ToInt32(aob[bytesPos[0]], 16), offSet)) != -1)
                    {
                        if (bytesPos.Count > 1)
                            for (int i = 1; i < bytesPos.Count; i++)
                            {
                                if (memoryBrick.Length <= offSet + pattern.Length
                                    || (byte)Convert.ToInt32(aob[bytesPos[i]], 16)
                                    != memoryBrick[(offSet - bytesPos[0]) + bytesPos[i]]) break;

                                if (i == bytesPos.Count - 1)
                                    if (aob[0] == "??")
                                        addresses.Add(new IntPtr((int)baseAddress + (offSet - bytesPos[0])));
                                    else addresses.Add(new IntPtr((int)baseAddress + offSet));
                            }
                        else
                            addresses.Add(new IntPtr((int)baseAddress + (offSet - bytesPos[0])));
                        offSet++;
                    }
                else
                    for (int i = 0; i < memoryBrick.Length; i++)
                        addresses.Add(new IntPtr((int)baseAddress + i));
            }

            public CancellationTokenSource cancelToken { get; set; } = new CancellationTokenSource();

            public Task<IntPtr[]> AoByte(string pattern, bool unwritable = false)
            {
                if (!pattern.Contains("?"))
                {
                    byte[] buff = pattern.Split(' ').Select(by =>
                    (byte)Convert.ToInt32(by, 16)).ToArray();

                    return Task.Run(() => { return GeneralScan(buff, unwritable); }, cancelToken.Token);
                }
                else return Task.Run(() => { return WCScan(pattern, unwritable); }, cancelToken.Token);
            }

            private IntPtr[] GeneralScan(byte[] buff, bool unwritable)
            {
                MemInfo(unwritable);

                List<IntPtr> addresses = new List<IntPtr>();

                for (int i = 0; i < MemoryRegion.Count; i++)
                {
                    uint read = 0;
                    byte[] wholeMemory = new byte[MemoryRegion[i].RegionSize];

                    ReadProcessMemory(_processHandle, MemoryRegion[i].BaseAddress, wholeMemory,
                        MemoryRegion[i].RegionSize, ref read);

                    BoyerAlgo(MemoryRegion[i].BaseAddress, wholeMemory, buff, ref addresses);
                }
                return addresses.ToArray();
            }

            private IntPtr[] WCScan(string pattern, bool unwritable)
            {
                MemInfo(unwritable);

                List<IntPtr> addresses = new List<IntPtr>();

                for (int i = 0; i < MemoryRegion.Count; i++)
                {
                    uint read = 0;
                    byte[] wholeMemory = new byte[MemoryRegion[i].RegionSize];

                    ReadProcessMemory(_processHandle, MemoryRegion[i].BaseAddress, wholeMemory,
                        MemoryRegion[i].RegionSize, ref read);

                    BoyerAlgo(MemoryRegion[i].BaseAddress, wholeMemory, pattern, ref addresses);
                }
                return addresses.ToArray();
            }
        }

        public class MeMorybox : Manager
        {

            public BoyerMoore BoyerScan { get; set; }

            IntPtr _processHandle;

            public MeMorybox(Process process)
            {
                _processHandle = OpenProcess((uint)Access.AllAccess, false, (uint)process.Id);

                BoyerScan = new BoyerMoore(_processHandle);

            }

            ~MeMorybox()
            {
                CloseHandle(_processHandle);
            }

        }

        static void MeMory(string process, string aob, int ppid)
        {
            //Process[] processList = Process.GetProcessesByName(process);
            Process p = Process.GetProcessById(ppid); ;

            MeMorybox notepad = new MeMorybox(p);

            Console.WriteLine("Hex value of pid:"+p.Id.ToString("x8"));

            var addresses = notepad.BoyerScan.AoByte(aob).GetAwaiter().GetResult();

        Console.WriteLine(addresses.Length + " hits found for pid:"+ppid);

        Console.WriteLine();
    }
}

testing for flash process..
  firefox..<32 bit process>
  chrome..<64 bit process>
  url to test: https://apps.facebook.com/candycrushsoda

array of byte to search as test:60 ?? ?? ?? ?? ?? ?? ?? ?? 01 ?? ?? 00 01 44 ?? ?? ?? ?? ?? ?? ?? ?? ?? 00 2A 12 10 00 00 29

it should give 1 result

in firefox--Flashplayerplugin it works fine,

in chrome--one of the processes containing module pepflashplayer.dll it >gives no result, as chrome is a 64 bit process.

To verify i double checked by using cheatengine, in both cases the aob is found correctly

Body:
I tried your code and for me, when inspecting a 64 bit process it produced arithmetic overflow on the line :

      Addy = new IntPtr(memInfo.BaseAddress.ToInt32() + (int) memInfo.RegionSize);

(Try it for yourself, turn on Build / Advanced.../ Check for arithmetic... in the project settings)

It looks like VirtualQueryEx may fill in MEMORY_BASIC_INFORMATION.BaseAddress with Int32.MaxValue() when querying 64 bit processes.

I think the easiest way to make it compatible with both 32 and 64 bit processes would be to target only 64 bit architecture and write your code accordingly, if you can afford that.
I suggest you try the following:

Change the project's platform target to x64

Update MEMORY_BASIC_INFORMATION so that it maps to the 64 bit version of the struct (the bottom one in Remarks), instead of the other one.  https://msdn.microsoft.com/en-us/library/windows/desktop/aa366775(v=vs.85).aspx

After that update the code to use 64 bit arithmetic whereever it uses BaseAddress or RegionSize (e.g make them IntPtr and use .ToInt64() instead of .ToInt32())


问:
Apollo (GraphQL) fetch more than one element in a query
Can I fetch more than one element in a GraphQL query? I have many products list data and I want to fetch, for example, three products in my component. I have an array of needed product IDs, can I pass it to query? This is my query for one product:

```<code>query ProductInCartQuery($id: ID!){
  Product(id: $id) {
   id
   name
   price
 }
}
</code>```

But I don't think I can just put it in a function and execute it for example three times for three products.

答:
For adding the product ids to the query you could define a input type. See the cheat sheet.

So the query on the client could look like:

query ProductsInCartQuery($productIds: ProductIds!) {
  Products(productIds: $productIds) {
    id
    name
    price
  }
}```
</div>
</div>
</p>

<p>On the server you define the schema with the <code>input</code> type as follows:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>input ProductIds {
  ids: [ID!]
}

type Query {
  Products(productIds: ProductIds!) {
    id
    name
    price
  }
}

schema {
  query: Query
}</code>```

Body:
Can I fetch more than one element in a GraphQL query? I have many products list data and I want to fetch, for example, three products in my component. I have an array of needed product IDs, can I pass it to query? This is my query for one product:

query ProductInCartQuery($id: ID!){
  Product(id: $id) {
   id
   name
   price
 }
}

But I don't think I can just put it in a function and execute it for example three times for three products.

Body:
For adding the product ids to the query you could define a input type. See the cheat sheet.

So the query on the client could look like:

query ProductsInCartQuery($productIds: ProductIds!) {
  Products(productIds: $productIds) {
    id
    name
    price
  }
}

On the server you define the schema with the input type as follows:

input ProductIds {
  ids: [ID!]
}

type Query {
  Products(productIds: ProductIds!) {
    id
    name
    price
  }
}

schema {
  query: Query
}


问:
why `write_through=True` is necessary when write a zipped csv?
Using csvreader against a gzipped file in Python

```<code>with gzip.open('test2.csv.gz', 'w') as f:
    #csv_w = csv.writer(io.TextIOWrapper(f, write_through=False)) # write empty csv.gz file
    csv_w = csv.writer(io.TextIOWrapper(f, write_through=True)) # ok
    csv_w.writerow(['a', 'b', 'c'])
    csv_w.writerow([1,2,3])
    csv_w.writerow([4,5,6])
</code>```

https://docs.python.org/3/library/io.html

If write_through is True, calls to write() are guaranteed not to be
  buffered: any data written on the TextIOWrapper object is immediately
  handled to its underlying binary buffer.

Question> I want to buffered write and set write_through=False. However, it will generate empty csv.gz file. But, it works if I switch to write_through=True.

Any reason why only write_through=True is supported here?

Python version: 3.5

答:
In order to compact the file, GZ has to find patterns in the file. The compression formula used by GZ analyses the file in question, if it doesn't exist, it outputs nothing from what I can tell. You can read more about how DEFLATE works here

Setting the "write_through" flag to True, it flushes the buffer to disk, from there GZ can read it.  If you don't, then the CSV writer keeps the information in a local buffer that's not accessible to gzip.

I hope that helps.

If you want to write to a file directly, you can do the following, removing the need for the io buffer.

```<code>gzip.open('test2.csv.gz', 'wt', newline='') as f:
  csv_w = csv.writer(f) # ok
</code>```

Body:
Using csvreader against a gzipped file in Python

with gzip.open('test2.csv.gz', 'w') as f:
    #csv_w = csv.writer(io.TextIOWrapper(f, write_through=False)) # write empty csv.gz file
    csv_w = csv.writer(io.TextIOWrapper(f, write_through=True)) # ok
    csv_w.writerow(['a', 'b', 'c'])
    csv_w.writerow([1,2,3])
    csv_w.writerow([4,5,6])

https://docs.python.org/3/library/io.html

If write_through is True, calls to write() are guaranteed not to be
  buffered: any data written on the TextIOWrapper object is immediately
  handled to its underlying binary buffer.

Question> I want to buffered write and set write_through=False. However, it will generate empty csv.gz file. But, it works if I switch to write_through=True.

Any reason why only write_through=True is supported here?

Python version: 3.5

Body:
In order to compact the file, GZ has to find patterns in the file. The compression formula used by GZ analyses the file in question, if it doesn't exist, it outputs nothing from what I can tell. You can read more about how DEFLATE works here

Setting the "write_through" flag to True, it flushes the buffer to disk, from there GZ can read it.  If you don't, then the CSV writer keeps the information in a local buffer that's not accessible to gzip.

I hope that helps.

If you want to write to a file directly, you can do the following, removing the need for the io buffer.

gzip.open('test2.csv.gz', 'wt', newline='') as f:
  csv_w = csv.writer(f) # ok


问:
Exception – Could not load file or assembly 'System.Web.Mvc, Version=4.0.0.1…'
There is a problem – only when I request one single controller – I get the exception:

Could not load file or assembly 'System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040

It's strange because in my config file I see that the version is 4.0.0.0 and and all the other controllers are fine and only when I upload the application on the server this thing happens.

答:
You maybe can reference ASP.NET MVC as reference to GAC, but it can happens that different developers have different version of MVC installed.

Remove references to ASP:NET MVC and add ASP.NET MVC as nuget package.

ContentLicense: CC BY-SA 4.0


问:
NEST: Update source filter
I have a method that takes a query as parameter like:

public ISearchResponse<Object> SearchComponent(SearchDescriptor<Object> query)
{
  ...
}
```
<p>In this query I want to add a source filter like:</p>
<pre class="lang-cs prettyprint-override"><code>public ISearchResponse<Object> SearchComponent(SearchDescriptor<Object> query)
{
    query = query.Source(sf =>
                    sf.Exclude(e => e
                        .Field("SomeField")
                        ));
    ...
}
</code>```

But what happens if the query already have a source filter? This filter will override that filter right? How can I update the existing queries source filter?

答:
This seems to work but it's not the most beautiful solution. Anyone that can come up with a better alternative?</p>

```<code>public ISearchResponse<Object> SearchComponent(ISearchRequest query)
{
    var excludeFields = new List<string>();
    excludeFields.Add("SomeField");

    if (query.Source == null)
    {
        query.Source = new SourceFilter {Include = "*", Exclude = excludeFields.ToArray()};
    }
    else if (query.Source.Exclude == null)
    {
        query.Source.Exclude = excludeFields.ToArray();
    }
    else
    {
        query.Source.Exclude.And(excludeFields.ToArray());
    }
    ...
}
</code>```

Title: NEST: Update source filter

Body:
I have a method that takes a query as parameter like:

public ISearchResponse<Object> SearchComponent(SearchDescriptor<Object> query)
{
  ...
}

In this query I want to add a source filter like:

public ISearchResponse<Object> SearchComponent(SearchDescriptor<Object> query)
{
    query = query.Source(sf =>
                    sf.Exclude(e => e
                        .Field("SomeField")
                        ));
    ...
}

But what happens if the query already have a source filter? This filter will override that filter right? How can I update the existing queries source filter?

Body:
This seems to work but it's not the most beautiful solution. Anyone that can come up with a better alternative?

public ISearchResponse<Object> SearchComponent(ISearchRequest query)
{
    var excludeFields = new List<string>();
    excludeFields.Add("SomeField");

    if (query.Source == null)
    {
        query.Source = new SourceFilter {Include = "*", Exclude = excludeFields.ToArray()};
    }
    else if (query.Source.Exclude == null)
    {
        query.Source.Exclude = excludeFields.ToArray();
    }
    else
    {
        query.Source.Exclude.And(excludeFields.ToArray());
    }
    ...
}


问:
WebResource Hell - resource cannot be found
Marked a javascript file as "Embedded resource"

Added WebResource attribute to my AssemblyInfo class

Now i'm trying to output the embedded javascript to my master page. All I'm getting is a "Web Resource not found" from the web resource url.

Project Assembly Name:

```<code>CompanyProduct
</code>```

Project Default Namespace:

```<code>Company.Product.Web
</code>```

Javascript file located:

Library/navigation.js

AssemblyInfo:

```<code>[assembly: WebResource("CompanyProduct.Library.navigation.js", "text/javascript")]
</code>```

Code in master page:

```<code>Page.ClientScript.RegisterClientScriptInclude("NavigationScript", Page.ClientScript.GetWebResourceUrl(this.GetType(), "CompanyProduct.Library.navigation.js"));
</code>```

Server Error in '/' Application.

 The resource cannot be found.

 Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

 Requested URL: /WebResource.axd

Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

答:
this blog is two years old now... but I I spent days on trying to get this to work.  Trying to get an embedded js file to actually give me a WebResource.asx query string that would work.  The final piece that seems to get glossed over here is that the file you have embedded HAS to be in the same physical directory structure as the controls code-behind that you are calling GetWebResourceUrl() from.  If you've placed the embedded file in a folder called "scripts", then called GetWebResourceUrl() from the master page which is NOT found in "scripts", the ResourceURL returned will point to the wrong location... thus ALWAYS returning a 404.

if you are using the MasterPage as the type for the first param then it will never work.  GetWebResourceUrl(typeof(MasterPage),...  I guess the real key here is that you have to drop the embedded resource into the same location that you are going to use as the type for the first parameter of the ResourceURL.  After 3 days of wrestling with this thing, it finally found my Resource.

OwnerDisplayName: Naeem

ContentLicense: CC BY-SA 2.5

Body:
Marked a javascript file as "Embedded resource"

Added WebResource attribute to my AssemblyInfo class

Now i'm trying to output the embedded javascript to my master page. All I'm getting is a "Web Resource not found" from the web resource url.

Project Assembly Name:

CompanyProduct

Project Default Namespace:

Company.Product.Web

Javascript file located:

Library/navigation.js

AssemblyInfo:

[assembly: WebResource("CompanyProduct.Library.navigation.js", "text/javascript")]

Code in master page:

Page.ClientScript.RegisterClientScriptInclude("NavigationScript", Page.ClientScript.GetWebResourceUrl(this.GetType(), "CompanyProduct.Library.navigation.js"));

Server Error in '/' Application.

 The resource cannot be found.

 Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

 Requested URL: /WebResource.axd

Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

LastEditorDisplayName: onnodb


问:
Get current Topic
How can I get the current Post? I'm trying to redirect to my current post where im sending my vote but this method that i created redirects to Oldest Post created by this user.

```<code>public function ScoreAction(Request $request){

    $em = $this->getDoctrine()->getManager();

    $idPoster = $request->request->get('id_posterUser');
    $positive= $request->request->get('positive');
    $negative= $request->request->get('negative');

    $user=  $em->getRepository(User::class)->findOneById($idPoster);

    $topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());

    $score = $usuari->getReputation();

    if ($positive!= null) {
        $score = $score + 1;
    }
    if($negative!= null){
         $score = $score - 1;
    }

    $user->setReputation($score );
    $em->persist($user);
    $em->flush();

     $redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));

return $this->redirect($redirect);

}
</code>```

Edit: Added my Solution.

Solution :

```<code> public function ScoreAction(Request $request){

        $em = $this->getDoctrine()->getManager();

        $idTopic = $request->request->get('id_topic');

        $idPoster = $request->request->get('id_poster');

        $positive= $request->request->get('positive');
        $negative= $request->request->get('negatiu');

        $user=  $em->getRepository(User::class)->findOneById($idPoster);

        $topic = $em->getRepository(Topic::class)->findOneById($idTopic);

        $score= $user->getReputation();

        if ($positive!= null) {
            $score= $score+ 1;
        }
        if($negative!= null){
             $score= $score- 1;
        }

        $user->setReputation($score);
        $em->persist($user);
        $em->flush();

        $redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));

        return $this->redirect($redirect);
    }
</code>```

答:
You are searching topic by user:

```<code>$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());
</code>```

findOneByUser - builds query WHERE user.id = :user_id LIMIT 1

For get the last Topic you need to add ordering.

```<code>$topic = $em->getRepository(Topic::class)->findOneBy(
    array('user' => $user),
    array('id' => 'desc')
);
</code>```

Title: Get current Topic

Body:
How can I get the current Post? I'm trying to redirect to my current post where im sending my vote but this method that i created redirects to Oldest Post created by this user.

public function ScoreAction(Request $request){

    $em = $this->getDoctrine()->getManager();

    $idPoster = $request->request->get('id_posterUser');
    $positive= $request->request->get('positive');
    $negative= $request->request->get('negative');

    $user=  $em->getRepository(User::class)->findOneById($idPoster);

    $topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());

    $score = $usuari->getReputation();

    if ($positive!= null) {
        $score = $score + 1;
    }
    if($negative!= null){
         $score = $score - 1;
    }

    $user->setReputation($score );
    $em->persist($user);
    $em->flush();

     $redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));

return $this->redirect($redirect);

}

Edit: Added my Solution.

Solution :

 public function ScoreAction(Request $request){

        $em = $this->getDoctrine()->getManager();

        $idTopic = $request->request->get('id_topic');

        $idPoster = $request->request->get('id_poster');

        $positive= $request->request->get('positive');
        $negative= $request->request->get('negatiu');

        $user=  $em->getRepository(User::class)->findOneById($idPoster);

        $topic = $em->getRepository(Topic::class)->findOneById($idTopic);

        $score= $user->getReputation();

        if ($positive!= null) {
            $score= $score+ 1;
        }
        if($negative!= null){
             $score= $score- 1;
        }

        $user->setReputation($score);
        $em->persist($user);
        $em->flush();

        $redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));

        return $this->redirect($redirect);
    }

Body:
You are searching topic by user:

$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());

findOneByUser - builds query WHERE user.id = :user_id LIMIT 1

For get the last Topic you need to add ordering.

$topic = $em->getRepository(Topic::class)->findOneBy(
    array('user' => $user),
    array('id' => 'desc')
);


问:
jQuerty UI range slider bug after change min value
I have one slider in my page, with this code

```<code><div id="sale-price-range" class="price-range" data-min="200000" data-max="2000000" data-unit="R$" data-min-field="precoMinVenda" data-max-field="precoMaxVenda" data-increment="100000"></div>
</code>```

My js code is:

```<code>// Price Range
$(".price-range").each(function() {

    var dataMin = $(this).attr('data-min');
    var dataMax = $(this).attr('data-max');
    var dataUnit = $(this).attr('data-unit');
    var minField = $(this).attr('data-min-field');
    var maxField = $(this).attr('data-max-field');
    var increment = $(this).attr('data-increment');

    $(this).append( "<input type='text' class='first-slider-value' name='"+minField+"' val=''/><input type='text' class='second-slider-value' name='"+maxField+"'/>" );

    $(this).slider({
        range: true,
        min: 0,
        max: dataMax,
        step: increment,
        values: [ dataMin, dataMax ],

        slide: function( event, ui ) {
            event = event;
            if(ui.value < dataMin) {
                return false;
            }
            $(this).find( ".first-slider-value" ).val( dataUnit + " " + ui.values[ 0 ].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
            $(this).find( ".second-slider-value" ).val( dataUnit + " " + ui.values[ 1 ].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
        },
        stop: function(event,ui) {
            if(ui.value >= dataMin) {
                postAjaxSearch();
            }
        }
    });
     $(this).find( ".first-slider-value" ).val( dataUnit + " " + $( this ).slider( "values", 0 ).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
     $(this).find( ".second-slider-value" ).val( dataUnit + " " +  $( this ).slider( "values", 1 ).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
});
</code>```

It works very well, but if I try to change
    min: 0,
To
    min: dataMin,

My slider stop to work (I can't drag it). It continues to call postAjaxSearch();, but it doesn't change max/min value neither move the slider-handle.

Why do I need to change min to dataMin?
Because my slider start from 0, but the slider-handle move from dataMin from dataMax. The range betweem dataMin and 0 is on page, but can't move there. I don't want this, the slider should start from dataMin.

Work, but with this space on left (min: 0)
No space, but doesn't work (min: dataMin)

答:
I had the same exact problem, I solved it by using parseInt() on the min value

```<code>$("#price-slider").slider({
        range: true,
        min: parseInt(price_min),
        max: price_max,
        values: [price_min, price_max],
        slide: function (event, ui) {
            $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
        }
    });
</code>```

I have no idea why this works, it would seem logical that both extremes would work the same but apparently they don't.

Body:
I have one slider in my page, with this code

My js code is:

// Price Range
$(".price-range").each(function() {

    var dataMin = $(this).attr('data-min');
    var dataMax = $(this).attr('data-max');
    var dataUnit = $(this).attr('data-unit');
    var minField = $(this).attr('data-min-field');
    var maxField = $(this).attr('data-max-field');
    var increment = $(this).attr('data-increment');

    $(this).append( "<input type='text' class='first-slider-value' name='"+minField+"' val=''/><input type='text' class='second-slider-value' name='"+maxField+"'/>" );

    $(this).slider({
        range: true,
        min: 0,
        max: dataMax,
        step: increment,
        values: [ dataMin, dataMax ],

        slide: function( event, ui ) {
            event = event;
            if(ui.value < dataMin) {
                return false;
            }
            $(this).find( ".first-slider-value" ).val( dataUnit + " " + ui.values[ 0 ].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
            $(this).find( ".second-slider-value" ).val( dataUnit + " " + ui.values[ 1 ].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
        },
        stop: function(event,ui) {
            if(ui.value >= dataMin) {
                postAjaxSearch();
            }
        }
    });
     $(this).find( ".first-slider-value" ).val( dataUnit + " " + $( this ).slider( "values", 0 ).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
     $(this).find( ".second-slider-value" ).val( dataUnit + " " +  $( this ).slider( "values", 1 ).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.") );
});

It works very well, but if I try to change
    min: 0,
To
    min: dataMin,

My slider stop to work (I can't drag it). It continues to call postAjaxSearch();, but it doesn't change max/min value neither move the slider-handle.

Why do I need to change min to dataMin?
Because my slider start from 0, but the slider-handle move from dataMin from dataMax. The range betweem dataMin and 0 is on page, but can't move there. I don't want this, the slider should start from dataMin.

Work, but with this space on left (min: 0)
No space, but doesn't work (min: dataMin)

Body:
I had the same exact problem, I solved it by using parseInt() on the min value

$("#price-slider").slider({
        range: true,
        min: parseInt(price_min),
        max: price_max,
        values: [price_min, price_max],
        slide: function (event, ui) {
            $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
        }
    });

I have no idea why this works, it would seem logical that both extremes would work the same but apparently they don't.


问:
how can I write a query (SQL Server) that, based on a table, it can return all the tables that it references?
I have a massive procedure which does a ton of deletes. The issue is that:

There are missing tables from this delete (that need to be deleted)

I'm having a hard time with the order of the deletes.

I'm wondering if there is a way to build a query in which I give it a table name and then it shows me all the tables I need to delete from before deleting this table. Anyone can give me a hand?

答:
shows me all the tables I need to delete from before deleting this table

Look at foreign key relationships.  But if there are none defined, you're just going to have to roll up your sleeves and analyze the stored procedure.


问:
Linux as a USB UVC device
What is needed for making a Linux device (Raspberry Pi) behave like a UVC device for another computer? Essentially, I would like to use output from ffmpeg to behave like a webcam input for another computer.</p>

答:
You will roughly need an USB OTG capable RPi, the RPi 3 is not capable of that.
Then you will need a custom kernel driver that emulates the UVC Driver of a real device, I am not aware of any project that does this directly.

The easiest way I can think of would be to stream the recorded images via RTMP instead of trying to emulate UVC as that is not a small feat.

Title: Linux as a USB UVC device


问:
Docusign - sign here tabs appear multiple times
This is with the Rest api. We trying to use the same anchor text values in all the documents we have in an envelope. We also may have several different server templates being applied to an envelope. We found out, to our dismay, that Docusign applies the anchor tags wherever it sees the anchor text and this means that if we have 3 server templates in the envelope, that the processing will create the anchor tags 3 times for each anchor text that it finds in each document. This means that the user will need to click three times to officially sign a document. What would be the quickest way to alleviate this problem?

-Here is the json

```<code> "compositeTemplates": [
{
  "compositeTemplateId": "1",
  "serverTemplates": [
    {
      "sequence": "1",
      "templateId": "61323293-7f78-4e2b-a296-0c084db16f19"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the  document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "1",
    "name": "C:\\Temp\\Docusign\\Package\\Canyonlands-ViewOnly.docx",
    "fileExtension": ".docx",
    "order": "1",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "1"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "2",
  "serverTemplates": [
    {
      "sequence": "2",
      "templateId": "14da6be4-c719-47d9-b183-da13295f86d5"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "60059128",
    "name": "C:\\Temp\\Docusign\\Package\\e AKA.docx",
    "fileExtension": ".docx",
    "order": "2",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "2"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "3",
  "serverTemplates": [
    {
      "sequence": "3",
      "templateId": "6b1a11c6-9719-424b-b983-4b278a467dd6"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour  consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "85586460",
    "name": "C:\\Temp\\Docusign\\Package\\e Equity Disbursement Instructions.docx",
    "fileExtension": ".docx",
    "order": "3",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "3"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "4",
  "serverTemplates": [
    {
      "sequence": "4",
      "templateId": "61323293-7f78-4e2b-a296-0c084db16f19"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the  document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "4",
    "name": "C:\\Temp\\Docusign\\Package\\EightDocument.docx",
    "fileExtension": ".docx",
    "order": "4",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "4"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "5",
  "inlineTemplates": [
    {
      "sequence": "3",
      "documents": [
        {
          "documentId": "5",
          "name": "C:\\Temp\\Docusign\\Package\\FifthDocument.docx",
          "fileExtension": ".docx",
          "order": "5",
          "documentFields": [
            {
              "name": "DMSID",
              "value": "5"
            }
          ],
          "documentBase64": "[Document:Base64Array]"
        },
        {
          "documentId": "6",
          "name": "C:\\Temp\\Docusign\\Package\\FirstDocument.docx",
          "fileExtension": ".docx",
          "order": "6",
          "documentFields": [
            {
              "name": "DMSID",
              "value": "6"
            }
          ],
          "documentBase64": "[Document:Base64Array]"
        },
        {
          "documentId": "7",
          "name": "C:\\Temp\\Docusign\\Package\\FourthDocument.docx",
          "fileExtension": ".docx",
          "order": "7",
          "documentFields": [
            {
              "name": "DMSID",
              "value": "7"
            }
          ],
          "documentBase64": "[Document:Base64Array]"
        }
      ],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ]
}
</code>```

答:
Create the Envelope with status=created

Use the listRecipients api to retrieve all the tabs.

Use the DeleteRecipientTabs api to delete the tabs in the envelope. You can Delete multiple tabs in a single call.

Use the createRecipientTabs api to create the new Anchor tabs.

Use the UpdateEnvelope api to mark the Envelope status as Sent.

Body:
This is with the Rest api. We trying to use the same anchor text values in all the documents we have in an envelope. We also may have several different server templates being applied to an envelope. We found out, to our dismay, that Docusign applies the anchor tags wherever it sees the anchor text and this means that if we have 3 server templates in the envelope, that the processing will create the anchor tags 3 times for each anchor text that it finds in each document. This means that the user will need to click three times to officially sign a document. What would be the quickest way to alleviate this problem?

-Here is the json

 "compositeTemplates": [
{
  "compositeTemplateId": "1",
  "serverTemplates": [
    {
      "sequence": "1",
      "templateId": "61323293-7f78-4e2b-a296-0c084db16f19"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the  document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "1",
    "name": "C:\\Temp\\Docusign\\Package\\Canyonlands-ViewOnly.docx",
    "fileExtension": ".docx",
    "order": "1",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "1"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "2",
  "serverTemplates": [
    {
      "sequence": "2",
      "templateId": "14da6be4-c719-47d9-b183-da13295f86d5"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "60059128",
    "name": "C:\\Temp\\Docusign\\Package\\e AKA.docx",
    "fileExtension": ".docx",
    "order": "2",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "2"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "3",
  "serverTemplates": [
    {
      "sequence": "3",
      "templateId": "6b1a11c6-9719-424b-b983-4b278a467dd6"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour  consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "85586460",
    "name": "C:\\Temp\\Docusign\\Package\\e Equity Disbursement Instructions.docx",
    "fileExtension": ".docx",
    "order": "3",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "3"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "4",
  "serverTemplates": [
    {
      "sequence": "4",
      "templateId": "61323293-7f78-4e2b-a296-0c084db16f19"
    }
  ],
  "inlineTemplates": [
    {
      "sequence": "2",
      "documents": [],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the  document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ],
  "document": {
    "documentId": "4",
    "name": "C:\\Temp\\Docusign\\Package\\EightDocument.docx",
    "fileExtension": ".docx",
    "order": "4",
    "documentFields": [
      {
        "name": "DMSID",
        "value": "4"
      }
    ],
    "documentBase64": "[Document:Base64Array]"
  }
},
{
  "compositeTemplateId": "5",
  "inlineTemplates": [
    {
      "sequence": "3",
      "documents": [
        {
          "documentId": "5",
          "name": "C:\\Temp\\Docusign\\Package\\FifthDocument.docx",
          "fileExtension": ".docx",
          "order": "5",
          "documentFields": [
            {
              "name": "DMSID",
              "value": "5"
            }
          ],
          "documentBase64": "[Document:Base64Array]"
        },
        {
          "documentId": "6",
          "name": "C:\\Temp\\Docusign\\Package\\FirstDocument.docx",
          "fileExtension": ".docx",
          "order": "6",
          "documentFields": [
            {
              "name": "DMSID",
              "value": "6"
            }
          ],
          "documentBase64": "[Document:Base64Array]"
        },
        {
          "documentId": "7",
          "name": "C:\\Temp\\Docusign\\Package\\FourthDocument.docx",
          "fileExtension": ".docx",
          "order": "7",
          "documentFields": [
            {
              "name": "DMSID",
              "value": "7"
            }
          ],
          "documentBase64": "[Document:Base64Array]"
        }
      ],
      "recipients": {
        "signers": [
          {
            "name": "Kathy Lori",
            "email": "kathylori@xxx.com",
            "recipientId": "1",
            "accessCode": "12345",
            "customFields": [],
            "routingOrder": "1",
            "note": "",
            "roleName": "Customer_SellerName",
            "emailNotification": {
              "emailSubject": "Please sign the document(s) (Lori)",
              "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
              "supportedLanguage": "en"
            }
          }
        ],
        "certifiedDeliveries": []
      },
      "customFields": {
        "textCustomFields": [
          {
            "name": "EnvelopeInfo",
            "value": "my data"
          }
        ]
      }
    }
  ]
}


问:
react-router scroll to top on every transition
I have an issue when navigating into another page, its position will remain like the page before. So it won't scroll to top automatically.
I've also tried to use window.scrollTo(0, 0) on onChange router. I've also used scrollBehavior to fix this issue but it didn't work. Any suggestions about this?

答:
For react-router v4, here is a create-react-app that achieves the scroll restoration: http://router-scroll-top.surge.sh/.

To achieve this you can create decorate the Route component and leverage lifecycle methods:

```<code>import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';

class ScrollToTopRoute extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.path === this.props.location.pathname && this.props.location.pathname !== prevProps.location.pathname) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    const { component: Component, ...rest } = this.props;

    return <Route {...rest} render={props => (<Component {...props} />)} />;
  }
}

export default withRouter(ScrollToTopRoute);
</code>```

On the componentDidUpdate we can check when the location pathname changes and match it to the path prop and, if those satisfied, restore the window scroll.

What is cool about this approach, is that we can have routes that restore scroll and routes that don't restore scroll.

Here is an App.js example of how you can use the above:

```<code>import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Lorem from 'react-lorem-component';
import ScrollToTopRoute from './ScrollToTopRoute';
import './App.css';

const Home = () => (
  <div className="App-page">
    <h2>Home</h2>
    <Lorem count={12} seed={12} />
  </div>
);

const About = () => (
  <div className="App-page">
    <h2>About</h2>
    <Lorem count={30} seed={4} />
  </div>
);

const AnotherPage = () => (
  <div className="App-page">
    <h2>This is just Another Page</h2>
    <Lorem count={12} seed={45} />
  </div>
);

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <div className="App-header">
            <ul className="App-nav">
              <li><Link to="/">Home</Link></li>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/another-page">Another Page</Link></li>
            </ul>
          </div>
          <Route exact path="/" component={Home} />
          <ScrollToTopRoute path="/about" component={About} />
          <ScrollToTopRoute path="/another-page" component={AnotherPage} />
        </div>
      </Router>
    );
  }
}

export default App;
</code>```

From the code above, what is interesting to point out is that only when navigating to /about or /another-page the scroll to top action will be preformed. However when going on / no scroll restore will happen.

The whole codebase can be found here: https://github.com/rizedr/react-router-scroll-top

Body:
For react-router v4, here is a create-react-app that achieves the scroll restoration: http://router-scroll-top.surge.sh/.

To achieve this you can create decorate the Route component and leverage lifecycle methods:

import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';

class ScrollToTopRoute extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.path === this.props.location.pathname && this.props.location.pathname !== prevProps.location.pathname) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    const { component: Component, ...rest } = this.props;

    return <Route {...rest} render={props => (<Component {...props} />)} />;
  }
}

export default withRouter(ScrollToTopRoute);

On the componentDidUpdate we can check when the location pathname changes and match it to the path prop and, if those satisfied, restore the window scroll.

What is cool about this approach, is that we can have routes that restore scroll and routes that don't restore scroll.

Here is an App.js example of how you can use the above:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Lorem from 'react-lorem-component';
import ScrollToTopRoute from './ScrollToTopRoute';
import './App.css';

const Home = () => (
  <div className="App-page">
    <h2>Home</h2>
    <Lorem count={12} seed={12} />
  </div>
);

const About = () => (
  <div className="App-page">
    <h2>About</h2>
    <Lorem count={30} seed={4} />
  </div>
);

const AnotherPage = () => (
  <div className="App-page">
    <h2>This is just Another Page</h2>
    <Lorem count={12} seed={45} />
  </div>
);

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <div className="App-header">
            <ul className="App-nav">
              <li><Link to="/">Home</Link></li>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/another-page">Another Page</Link></li>
            </ul>
          </div>
          <Route exact path="/" component={Home} />
          <ScrollToTopRoute path="/about" component={About} />
          <ScrollToTopRoute path="/another-page" component={AnotherPage} />
        </div>
      </Router>
    );
  }
}

export default App;

From the code above, what is interesting to point out is that only when navigating to /about or /another-page the scroll to top action will be preformed. However when going on / no scroll restore will happen.

The whole codebase can be found here: https://github.com/rizedr/react-router-scroll-top


问:
Created contacts not showing up on HTC Evo
I'm writing a program that imports our contacts into the Contacts db on the phone so they show up in the Contacts app, are available for caller id to draw from, etc. I've got it working the way we want on the emulator and the Motorola Droid. When I go to Menu --> View, I can see our application with a check box next to it, and when it's checked, our contacts show up fine.

However, when I try the same thing on the HTC Evo, the contacts don't show up in People, and I don't have our application listed in the View menu. The contacts show up when I do a search within People, and when the contact calls the phone, their contact info shows up fine.

The contacts I'm testing our application with aren't in the phone already ;-) They're special test cases with unique names; that's how I'm able to determine they are actually coming from our app.

I sort of get the feeling this is a HTC Sense issue, but I don't have a way to confirm that right now. If anyone has any ideas, I'd love to hear them.

答:
I have the same issue with an app that does contact sync using the Android 2.x API.  The contacts I've added don't appear in the Sense contacts app or the Motoblur contacts app.  They appear in the emulator's default (ie Google) contacts app, though.

I know that the problem with motoblur is that (per moto's website) the blur contacts API is based off of the old Contacts API found in Android 1.x, and not the new 2.x ContactsContract API.  It's possible that HTC does the same, though I've not been able to find any confirmation of that despite a little bit of googling.


问:
C# - Selenium - Retry Attribute not working with Selenium timeout
I have the following custom RetryAttribute taken from this post: NUnit retry dynamic attribute. It works fine but when I get a timeout error in Selenium it doesn´t work.

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            wait.Until(ExpectedConditions.ElementToBeClickable(element));
</code>```

Retry custom attribute:

```<code>/// <summary>
/// RetryDynamicAttribute may be applied to test case in order
/// to run it multiple times based on app setting.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryDynamicAttribute : RetryAttribute {
    private const int DEFAULT_TRIES = 1;
    static Lazy<int> numberOfRetries = new Lazy<int>(() => {
        int count = 0;
        return int.TryParse(ConfigurationManager.AppSettings["retryTest"], out count) ? count : DEFAULT_TRIES;
    });

    public RetryDynamicAttribute() :
        base(numberOfRetries.Value) {
    }
}
</code>```

And then apply the custom attribute.

```<code>[Test]
[RetryDynamic]
public void Test() {
    //....
}
</code>```

How can this be solved?

答:
According to documentation here

NUnit Docs Retry Attribute

If a test has an unexpected exception, an error result is returned and
  it is not retried. Only assertion failures can trigger a retry. To
  convert an unexpected exception into an assertion failure, see the
  ThrowsConstraint.

emphasis mine.

The related ThrowsNothingConstraint simply asserts that the delegate
  does not throw an exception.

You need to catch the exception and cause a failed assertion if an exception was not expected.

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
Assert.That(() => {
         wait.Until(ExpectedConditions.ElementToBeClickable(element));
     }, Throws.Nothing);
</code>```

So the above code simply says execute the action and it should not expect an exception. If an exception is thrown then it is a failed assertion. The retry will execute if attribute is applied to the test.

Body:
I have the following custom RetryAttribute taken from this post: NUnit retry dynamic attribute. It works fine but when I get a timeout error in Selenium it doesn´t work.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            wait.Until(ExpectedConditions.ElementToBeClickable(element));

Retry custom attribute:

///
/// RetryDynamicAttribute may be applied to test case in order
/// to run it multiple times based on app setting.
///
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryDynamicAttribute : RetryAttribute {
    private const int DEFAULT_TRIES = 1;
    static Lazy<int> numberOfRetries = new Lazy<int>(() => {
        int count = 0;
        return int.TryParse(ConfigurationManager.AppSettings["retryTest"], out count) ? count : DEFAULT_TRIES;
    });

    public RetryDynamicAttribute() :
        base(numberOfRetries.Value) {
    }
}

And then apply the custom attribute.

[Test]
[RetryDynamic]
public void Test() {
    //....
}

How can this be solved?

Body:
According to documentation here

NUnit Docs Retry Attribute

If a test has an unexpected exception, an error result is returned and
  it is not retried. Only assertion failures can trigger a retry. To
  convert an unexpected exception into an assertion failure, see the
  ThrowsConstraint.

emphasis mine.

The related ThrowsNothingConstraint simply asserts that the delegate
  does not throw an exception.

You need to catch the exception and cause a failed assertion if an exception was not expected.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
Assert.That(() => {
         wait.Until(ExpectedConditions.ElementToBeClickable(element));
     }, Throws.Nothing);

So the above code simply says execute the action and it should not expect an exception. If an exception is thrown then it is a failed assertion. The retry will execute if attribute is applied to the test.