问:
Check if Capybara::Node::Element has been removed by jQuery.remove()
I'm trying to make the following test:

```<code>it 'remove item from cart' do
  visit cart_path
  button = page.find("a[href='/carts/#{item.id}/remove']")
  card = find_ancestor_with_class(button, '.card')
  button.click
  # check if card has been removed from page
end
</code>```

This test is suppossed to work because the following JS removes the card from page:

```<code>$.ajax({
  url: link,
  method: "GET",
  success: function() {
    $('#alert-modal').modal('show');
    $(button).closest(".card").remove();
  }
});
</code>```

How I verify if the .card html has been removed from page?

答:
To check if something isn't visible on the page you would do

```<code>expect(page).to have_no_css(".card")
</code>```

or

```<code>expect(page).not_to have_css(".card")
</code>```

So overall it becomes

```<code>visit cart_path
click_link(href: "/cars/#{item.id}/remove")
expect(page).not_to have_css(".card")
</code>```

That will only work if all the .card elements are removed. If there would still be other .card elements on the page then base the check on text that you expect to be in the card or other attribute/property on the card element (id, etc), like the items description or whatever would be shown like

```<code>expect(page).not_to have_css(".card", text: item.description)
</code>```

If you deal with the .card elements a lot you could also write a custom Capybara selector to make things easier to read, localize the CSS definition of a "card" etc like

```<code>Capybara.add_selector :card do
  xpath do |content|
    xp = XPath.css('.card')
    xp = xp[XPath.string.n.is(content)] unless content.nil?
    xp
  end
end
</code>```

which should then allow

```<code>expect(page).to have_no_selector(:card)
expect(page).to have_no_selector(:card, item.description)
</code>```

etc.

Body:
I'm trying to make the following test:

it 'remove item from cart' do
  visit cart_path
  button = page.find("a[href='/carts/#{item.id}/remove']")
  card = find_ancestor_with_class(button, '.card')
  button.click
  # check if card has been removed from page
end

This test is suppossed to work because the following JS removes the card from page:

$.ajax({
  url: link,
  method: "GET",
  success: function() {
    $('#alert-modal').modal('show');
    $(button).closest(".card").remove();
  }
});

How I verify if the .card html has been removed from page?

Body:
To check if something isn't visible on the page you would do

expect(page).to have_no_css(".card")

or

expect(page).not_to have_css(".card")

So overall it becomes

visit cart_path
click_link(href: "/cars/#{item.id}/remove")
expect(page).not_to have_css(".card")

That will only work if all the .card elements are removed. If there would still be other .card elements on the page then base the check on text that you expect to be in the card or other attribute/property on the card element (id, etc), like the items description or whatever would be shown like

expect(page).not_to have_css(".card", text: item.description)

If you deal with the .card elements a lot you could also write a custom Capybara selector to make things easier to read, localize the CSS definition of a "card" etc like

Capybara.add_selector :card do
  xpath do |content|
    xp = XPath.css('.card')
    xp = xp[XPath.string.n.is(content)] unless content.nil?
    xp
  end
end

which should then allow

expect(page).to have_no_selector(:card)
expect(page).to have_no_selector(:card, item.description)

etc.


来源: stackexchange

问:
Analyze methods count of an android library
I recently in my project get 65536 error message about dex size and blahblah.<br>
and now I'm trying to reduce my dex size but I don't know exactly wich of my  libraries is adding more size to dex file I just can see hole dex file size in apk analyzer is there a tool or way to analyze dex file and getting information about how many methods this library has and how much adding to my dex file?    </p>

答:
Also if you prefer to check the methods count in advance, you can check this tool:

www.methodscount.com

UPDATE: Not maintained anymore

ContentLicense: CC BY-SA 3.0

Body:
I recently in my project get 65536 error message about dex size and blahblah.

and now I'm trying to reduce my dex size but I don't know exactly wich of my  libraries is adding more size to dex file I just can see hole dex file size in apk analyzer is there a tool or way to analyze dex file and getting information about how many methods this library has and how much adding to my dex file?

ContentLicense: CC BY-SA 4.0


问:
Get the Icon of a file from a windows mobile app
I'm working with C# developing app for windows mobible 6. I need get the icon of a file, but i don't know how to do that =P.

Is there way to get it?

答:
Yes, though it's not painless, and requires using PInvoke. Here's how I do it. (WinApi is a helper static class that contains PInvoke external functions definitions, along with a number of required constants. There was much more in there but I deleted the stuff that had nothing to do with getting icons for files.)

```<code>using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace ExtendedCF {
    public static class WinApi
    {
        #region Icons
        [DllImport("coredll.dll")]
        public static extern bool DestroyIcon(IntPtr hIcon);
        #endregion

        #region SHGetFileInfo
        [DllImport("coredll.dll", CharSet = CharSet.Auto)]
        public static extern int SHGetFileInfo(
          string pszPath,
          int dwFileAttributes,
          out SHFILEINFO psfi,
          uint cbfileInfo,
          SHGFI uFlags);

        [Flags]
        public enum SHGFI : int
        {
            /// <summary>get icon</summary>
            Icon = 0x000000100,
            /// <summary>get display name</summary>
            DisplayName = 0x000000200,
            /// <summary>get type name</summary>
            TypeName = 0x000000400,
            /// <summary>get attributes</summary>
            Attributes = 0x000000800,
            /// <summary>get icon location</summary>
            IconLocation = 0x000001000,
            /// <summary>return exe type</summary>
            ExeType = 0x000002000,
            /// <summary>get system icon index</summary>
            SysIconIndex = 0x000004000,
            /// <summary>put a link overlay on icon</summary>
            LinkOverlay = 0x000008000,
            /// <summary>show icon in selected state</summary>
            Selected = 0x000010000,
            /// <summary>get only specified attributes</summary>
            Attr_Specified = 0x000020000,
            /// <summary>get large icon</summary>
            LargeIcon = 0x000000000,
            /// <summary>get small icon</summary>
            SmallIcon = 0x000000001,
            /// <summary>get open icon</summary>
            OpenIcon = 0x000000002,
            /// <summary>get shell size icon</summary>
            ShellIconSize = 0x000000004,
            /// <summary>pszPath is a pidl</summary>
            PIDL = 0x000000008,
            /// <summary>use passed dwFileAttribute</summary>
            UseFileAttributes = 0x000000010,
            /// <summary>apply the appropriate overlays</summary>
            AddOverlays = 0x000000020,
            /// <summary>Get the index of the overlay in the upper 8 bits of the iIcon</summary>
            OverlayIndex = 0x000000040,
        }

        /// <summary>Maximal Length of unmanaged Windows-Path-strings</summary>
        private const int MAX_PATH = 260;
        /// <summary>Maximal Length of unmanaged Typename</summary>
        private const int MAX_TYPE = 80;

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SHFILEINFO
        {
            public SHFILEINFO(bool dummy)
            {
                hIcon = IntPtr.Zero;
                iIcon = 0;
                dwAttributes = 0;
                szDisplayName = "";
                szTypeName = "";
            }
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_TYPE)]
            public string szTypeName;
        };

        #endregion
    }
    public static class Utils
    {
        #region GetFileIcon and GetFolderIcon
        /// <summary>
        /// Get the associated Icon for a file or application.  Always returns
        /// an icon.  If the filePath is invalid, the default icon for files of such type is returned.
        /// </summary>
        /// <param name="filePath">full path to the file</param>
        /// <param name="bSmall">if true, return the 16x16 icon; otherwise, the 32x32 icon</param>
        /// <returns></returns>
        private static Icon GetIcon(string filePath, bool bFolder, bool bSmall)
        {
            WinApi.SHFILEINFO info = new WinApi.SHFILEINFO(true);
            int cbFileInfo = Marshal.SizeOf(info);
            WinApi.SHGFI flags = WinApi.SHGFI.Icon | WinApi.SHGFI.UseFileAttributes;
            if (bSmall)
                flags |= WinApi.SHGFI.SmallIcon;
            else
                flags |= WinApi.SHGFI.LargeIcon;

            int fileAttributes = 0;
            if (bFolder)
            {
                fileAttributes = (int)FileAttributes.Directory;
            }

            WinApi.SHGetFileInfo(filePath, fileAttributes, out info, (uint)cbFileInfo, flags);
            Icon rv = (Icon)Icon.FromHandle(info.hIcon).Clone();
            WinApi.DestroyIcon(info.hIcon);
            return rv;
        }
        private static Icon GetIcon(string filePath, bool bFolder)
        {
            return GetIcon(filePath, bFolder, false);
        }
        public static Icon GetFileIcon(string filePath)
        {
            return GetIcon(filePath, false);
        }
        public static Icon GetFolderIcon(string folderPath)
        {
            return GetIcon(folderPath, true);
        }
        public static Icon GetFileIcon(string filePath, bool bSmall)
        {
            return GetIcon(filePath, false, bSmall);
        }
        public static Icon GetFolderIcon(string folderPath, bool bSmall)
        {
            return GetIcon(folderPath, true, bSmall);
        }
        #endregion
    }
}
</code>```

OwnerDisplayName: Leandro Galluppi

ContentLicense: CC BY-SA 2.5

Body:
Yes, though it's not painless, and requires using PInvoke. Here's how I do it. (WinApi is a helper static class that contains PInvoke external functions definitions, along with a number of required constants. There was much more in there but I deleted the stuff that had nothing to do with getting icons for files.)

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace ExtendedCF {
    public static class WinApi
    {
        #region Icons
        [DllImport("coredll.dll")]
        public static extern bool DestroyIcon(IntPtr hIcon);
        #endregion

        #region SHGetFileInfo
        [DllImport("coredll.dll", CharSet = CharSet.Auto)]
        public static extern int SHGetFileInfo(
          string pszPath,
          int dwFileAttributes,
          out SHFILEINFO psfi,
          uint cbfileInfo,
          SHGFI uFlags);

        [Flags]
        public enum SHGFI : int
        {
            /// <summary>get icon</summary>
            Icon = 0x000000100,
            /// <summary>get display name</summary>
            DisplayName = 0x000000200,
            /// <summary>get type name</summary>
            TypeName = 0x000000400,
            /// <summary>get attributes</summary>
            Attributes = 0x000000800,
            /// <summary>get icon location</summary>
            IconLocation = 0x000001000,
            /// <summary>return exe type</summary>
            ExeType = 0x000002000,
            /// <summary>get system icon index</summary>
            SysIconIndex = 0x000004000,
            /// <summary>put a link overlay on icon</summary>
            LinkOverlay = 0x000008000,
            /// <summary>show icon in selected state</summary>
            Selected = 0x000010000,
            /// <summary>get only specified attributes</summary>
            Attr_Specified = 0x000020000,
            /// <summary>get large icon</summary>
            LargeIcon = 0x000000000,
            /// <summary>get small icon</summary>
            SmallIcon = 0x000000001,
            /// <summary>get open icon</summary>
            OpenIcon = 0x000000002,
            /// <summary>get shell size icon</summary>
            ShellIconSize = 0x000000004,
            /// <summary>pszPath is a pidl</summary>
            PIDL = 0x000000008,
            /// <summary>use passed dwFileAttribute</summary>
            UseFileAttributes = 0x000000010,
            /// <summary>apply the appropriate overlays</summary>
            AddOverlays = 0x000000020,
            /// <summary>Get the index of the overlay in the upper 8 bits of the iIcon</summary>
            OverlayIndex = 0x000000040,
        }

        /// <summary>Maximal Length of unmanaged Windows-Path-strings</summary>
        private const int MAX_PATH = 260;
        /// <summary>Maximal Length of unmanaged Typename</summary>
        private const int MAX_TYPE = 80;

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SHFILEINFO
        {
            public SHFILEINFO(bool dummy)
            {
                hIcon = IntPtr.Zero;
                iIcon = 0;
                dwAttributes = 0;
                szDisplayName = "";
                szTypeName = "";
            }
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_TYPE)]
            public string szTypeName;
        };

        #endregion
    }
    public static class Utils
    {
        #region GetFileIcon and GetFolderIcon
        /// <summary>
        /// Get the associated Icon for a file or application.  Always returns
        /// an icon.  If the filePath is invalid, the default icon for files of such type is returned.
        /// </summary>
        /// <param name="filePath">full path to the file</param>
        /// <param name="bSmall">if true, return the 16x16 icon; otherwise, the 32x32 icon</param>
        /// <returns></returns>
        private static Icon GetIcon(string filePath, bool bFolder, bool bSmall)
        {
            WinApi.SHFILEINFO info = new WinApi.SHFILEINFO(true);
            int cbFileInfo = Marshal.SizeOf(info);
            WinApi.SHGFI flags = WinApi.SHGFI.Icon | WinApi.SHGFI.UseFileAttributes;
            if (bSmall)
                flags |= WinApi.SHGFI.SmallIcon;
            else
                flags |= WinApi.SHGFI.LargeIcon;

            int fileAttributes = 0;
            if (bFolder)
            {
                fileAttributes = (int)FileAttributes.Directory;
            }

            WinApi.SHGetFileInfo(filePath, fileAttributes, out info, (uint)cbFileInfo, flags);
            Icon rv = (Icon)Icon.FromHandle(info.hIcon).Clone();
            WinApi.DestroyIcon(info.hIcon);
            return rv;
        }
        private static Icon GetIcon(string filePath, bool bFolder)
        {
            return GetIcon(filePath, bFolder, false);
        }
        public static Icon GetFileIcon(string filePath)
        {
            return GetIcon(filePath, false);
        }
        public static Icon GetFolderIcon(string folderPath)
        {
            return GetIcon(folderPath, true);
        }
        public static Icon GetFileIcon(string filePath, bool bSmall)
        {
            return GetIcon(filePath, false, bSmall);
        }
        public static Icon GetFolderIcon(string folderPath, bool bSmall)
        {
            return GetIcon(folderPath, true, bSmall);
        }
        #endregion
    }
}

OwnerDisplayName: Vladimir


问:
jquery.validate.unobtrusive not working with dynamic injected elements
I am working with ASP.Net MVC3, the easier way to use the client validation would be enabling the jquery.validate.unobtrusive. Everything works fine, for stuff that's right from server.

But when I try to inject some new 'inputs' with javascript, and I knew that I need to call $.validator.unobtrusive.parse() to rebind the validations. But still, all those dynamic injected fields are not functioning.

Even worse, I try to manually bind using jquery.validate and it is not working either. Any thoughts?

答:
Firstly, I think the call should be to .validator, not validate then you need to pass in the id of the form </p>

```<code>$.validator.unobtrusive.parse("#id");
</code>```

Body:
Firstly, I think the call should be to .validator, not validate then you need to pass in the id of the form

$.validator.unobtrusive.parse("#id");


问:
Why does this function fail when I use this regular expression?
I have been practicing getting more comfortable with the use of regular expressions, but I am having a really hard time understanding why this function I wrote does not work. I wrote a simple function to count the number of duplicate letters in a word, which seems to work sometimes, but doesn't work all the time.

```<code>function duplicates(str){
    try{
        return str.match(/(.)\1+/ig).length;
    }catch(e){
        return 0;
    }
}
</code>```

According to what I have researched this statement should look through the string, find a letter (or multiple letters) that repeat more than once ignoring case, and return the length of the matched letters. If no matching letters occur it will return 0. It works correctly for some strings, but not all. Here's what I have been getting:

```<code>duplicates("abcdef") -> 0      #should return 0
duplicates("Aabccdef") -> 2    #should return 2
duplicates("Mississippi") -> 3 #should return 3
duplicates("Indivisible") -> 0 #should return 1
duplicates("abcabcabc") -> 0   #should return 3
</code>```

Upon further inspection, it would seem that when I ran "Mississippi", I got the expected number 3, however when I added .toString() in replacement of .length to see what the expression was counting I got:

```<code>ss,ss,pp
</code>```

There are no i's counted and there should be. It would also seem that the i's were not counted in "Indivisible" either and did not indicate any repeated letters in "abcabcabc". It seems that it can not count non-consecutive repeats, but I can't figure out why. I am sure it is my misunderstanding of how regular expressions work, since I am new to them, but if anyone would shed some light on why this is happening, that would be awesome!

Edit: Is there a way to do this with RegEx, or do I need to use a loop?

答:
In terms of the actual Regular expression that you've posted, there are a few problems with it. The reason that (.)\1+ doesn't work is that the 'first match' (\1) immediately follows the matching group with the .. This means in the case of 'Mississippi', since there are no consecutively matched letter 'i's, your pattern does not match them.

As an alternative solution to this problem, you might as well keep it simple. A more reasonable solution for your use case would be to simply loop through and count each letter.

function duplicates(str){
    try{
        let letters = str.toLowerCase().split('');
        let countedLetters = {}
        for(let i = 0; i < letters.length; i++) {
            countedLetters[letters[i]] = countedLetters[letters[i]] + 1 || 1;
        }
        return countedLetters;
    } catch(e) {
        return 0;
    }
}

console.log(duplicates('Mississippi'));```

Body:
I have been practicing getting more comfortable with the use of regular expressions, but I am having a really hard time understanding why this function I wrote does not work. I wrote a simple function to count the number of duplicate letters in a word, which seems to work sometimes, but doesn't work all the time.

function duplicates(str){
    try{
        return str.match(/(.)\1+/ig).length;
    }catch(e){
        return 0;
    }
}

According to what I have researched this statement should look through the string, find a letter (or multiple letters) that repeat more than once ignoring case, and return the length of the matched letters. If no matching letters occur it will return 0. It works correctly for some strings, but not all. Here's what I have been getting:

duplicates("abcdef") -> 0      #should return 0
duplicates("Aabccdef") -> 2    #should return 2
duplicates("Mississippi") -> 3 #should return 3
duplicates("Indivisible") -> 0 #should return 1
duplicates("abcabcabc") -> 0   #should return 3

Upon further inspection, it would seem that when I ran "Mississippi", I got the expected number 3, however when I added .toString() in replacement of .length to see what the expression was counting I got:

ss,ss,pp

There are no i's counted and there should be. It would also seem that the i's were not counted in "Indivisible" either and did not indicate any repeated letters in "abcabcabc". It seems that it can not count non-consecutive repeats, but I can't figure out why. I am sure it is my misunderstanding of how regular expressions work, since I am new to them, but if anyone would shed some light on why this is happening, that would be awesome!

Edit: Is there a way to do this with RegEx, or do I need to use a loop?


问:
CodeIgniter session behind proxy
What happens when you don't have a list of proxy IPs? When using site acceleration services like Akamai, Google, Edgecast or CloudFront; it would always be hard to get IPs for sessions from them.

When testing our codeigniter application on a CDN, we noticed that IPs were being passed as CDN IPs and not the client IPs in the session database.

How can you get around to this?

```<code>    /*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
</code>```

Thanks!

答:
If you want to handle IP in Codeigniter 3 but not in the web server, you can add CDN IP into this config:

```<code>$config['proxy_ips'] = ['10.0.1.2'];
</code>```

or giving a CDN network mask:

```<code>$config['proxy_ips'] = '10.0.1.0/24';
</code>```

If your server is always behind CDN:

```<code>$config['proxy_ips'] = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : '';
</code>```

Get IP method:

```<code>$this->input->ip_address(); //$this=>CI
</code>```

It will return forward IP if matched proxy IP, otherwise it will return $_SERVER["REMOTE_ADDR"], which could get the real client IP.

Referring to Codeigniter 3

Title: CodeIgniter session behind proxy

Body:
What happens when you don't have a list of proxy IPs? When using site acceleration services like Akamai, Google, Edgecast or CloudFront; it would always be hard to get IPs for sessions from them.

When testing our codeigniter application on a CDN, we noticed that IPs were being passed as CDN IPs and not the client IPs in the session database.

How can you get around to this?

    /*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';

Thanks!

Body:
If you want to handle IP in Codeigniter 3 but not in the web server, you can add CDN IP into this config:

$config['proxy_ips'] = ['10.0.1.2'];

or giving a CDN network mask:

$config['proxy_ips'] = '10.0.1.0/24';

If your server is always behind CDN:

$config['proxy_ips'] = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : '';

Get IP method:

$this->input->ip_address(); //$this=>CI

It will return forward IP if matched proxy IP, otherwise it will return $_SERVER["REMOTE_ADDR"], which could get the real client IP.

Referring to Codeigniter 3


问:
Rotate a string in C
I am trying to shift a string both left and right given the number of positions to shift the string by.

This is what I wrote so far but it does not work.

```<code>void Shift(char* string, shift)
{
    int length = strlen(string)-1;
    int i;
    char *buff;
    buff = malloc((sizeof(char) *shift) + 1);
    strncpy(buff, string, shift);
    buff[shift] = '/0';
    while (string[i + shift] != '/0')
        string[i++] = string[i + shift];
    strcat(string, buff);
}
</code>```

How can I fix this?
This should be the example:
shift = 1

HELLO ->
OHELL

答:
My solution is modulo based, use negative number to shift on the left and positive numbers to shift on the right.

```<code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

void shift(char* string, int shift)
{
    char *tmp = strdup(string);
    int len = strlen(string);
    if (shift < 0)
        shift = len + (shift % len);
    for (int i = 0; string[i] != 0; i++) {
        int new_idx = (i + shift) % len;
        tmp[new_idx] = string[i];
    }
    memcpy(string, tmp, len);
    free(tmp);
}

int main(void) {
    char test[] = "coucou";
    shift(test, -9);
    printf("%s\n", test);
    return 0;
}
</code>```

The trick is to compute where each charachter is going to end up in the destination string. By using modulo of the total size you make sure it stays in between bounds, thus adding the offset and then ensuring it stays in bounds gives the correct index.

For the left shift, i just transformed the left shift offset into a right shift offset and re-used the right shifting code.

Title: Rotate a string in C

Body:
I am trying to shift a string both left and right given the number of positions to shift the string by.

This is what I wrote so far but it does not work.

void Shift(char* string, shift)
{
    int length = strlen(string)-1;
    int i;
    char *buff;
    buff = malloc((sizeof(char) *shift) + 1);
    strncpy(buff, string, shift);
    buff[shift] = '/0';
    while (string[i + shift] != '/0')
        string[i++] = string[i + shift];
    strcat(string, buff);
}

How can I fix this?
This should be the example:
shift = 1

HELLO ->
OHELL

Body:
My solution is modulo based, use negative number to shift on the left and positive numbers to shift on the right.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

void shift(char* string, int shift)
{
    char *tmp = strdup(string);
    int len = strlen(string);
    if (shift < 0)
        shift = len + (shift % len);
    for (int i = 0; string[i] != 0; i++) {
        int new_idx = (i + shift) % len;
        tmp[new_idx] = string[i];
    }
    memcpy(string, tmp, len);
    free(tmp);
}

int main(void) {
    char test[] = "coucou";
    shift(test, -9);
    printf("%s\n", test);
    return 0;
}

The trick is to compute where each charachter is going to end up in the destination string. By using modulo of the total size you make sure it stays in between bounds, thus adding the offset and then ensuring it stays in bounds gives the correct index.

For the left shift, i just transformed the left shift offset into a right shift offset and re-used the right shifting code.


问:
How Do We Identify the Owner of a Window?
Suppose we have an Android device, and on that device are 1+ apps capable of creating their own floating windows (e.g., hold the SYSTEM_ALERT_WINDOW permission). Plus, of course, there can be other windows that are not necessarily independently floating (Spinner, Dialog, etc. all create their own windows via WindowManager, just for display over an existing activity).

Given that I know from developer tools a pixel coordinate inside a window, how can I determine the process or app that created the window containing that pixel? IOW, how can I find out who to blame for the existence of a given window?

I thought that perhaps adb shell dumpsys window would have that information, but if it does, I'm not seeing it.

Note that I am happy to settle for a solution involving development tools. I would hope that determining this information at runtime would be difficult or impossible without special privileges.

答:
From adb shell dumpsys window:

Window #3 Window{41b85d98 u10 com.example.app}:
    mDisplayId=0 mSession=Session{41bc2e38 10536:u10a10030} mClient=android.os.BinderProxy@41b064c0
    mOwnerUid=1010030 mShowToOwnerOnly=true package=com.example.app appop=SYSTEM_ALERT_WINDOW
    mAttrs=WM.LayoutParams{(0,0)(395x110) gr=#55 sim=#20 ty=2003 fl=#20008 fmt=-3}
    Requested w=395 h=110 mLayoutSeq=1200
    mHasSurface=true mShownFrame=[885.0,642.0][1280.0,752.0] isReadyForDisplay()=true
    WindowStateAnimator{41d4d2a8 }:
      Surface: shown=true layer=91000 alpha=1.0 rect=(885.0,642.0) 395.0 x 110.0

It looks to me that mShownFrame variable holds the data you need to determine if a pixel is contained by a window.


问:
Form not showing, Only the button shows Django
I am trying to show a newsletter form, and it is not shown in the page

This is my models.py

```<code>from django.db import models

# Create your models here.

class newsletter_user(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email
</code>```

This is my forms.py

```<code>from django import forms
from .models import newsletter_user

class newsletterForm(forms.ModelForm):

    class Meta:
        model = newsletter_user
        fields = ['email']

        def clean_email(self):
            email = self.cleaned_data.get('email')
            return email
</code>```

This is my admin.py

```<code>from django.contrib import admin

from .models import newsletter_user
# Register your models here.
class newsletterAdmin(admin.ModelAdmin):
    list_display = ('email','date_added',)

admin.site.register(newsletter_user,newsletterAdmin)
</code>```

This is the views.py

```<code>from django.shortcuts import render
from .models import newsletter_user
from .forms import newsletterForm

# Create your views here.
def newsletter_subscribe(request):
    form = newsletterForm(request.POST or none)

    if form.is_valid():
        instance = form.save(commit=false)
        if newsletter_user.objects.filter(email=instance.email).exists():
            print("already exists")
        else:
            instance.save()

    context = {'form':form,}
    template = "/blog/templates/footer.html"
    return render(request, template, context)
</code>```

This is the html

```<code><form method="post" action=''>
    <div class = "input-group">
        {{form}}  {% csrf_token %}
        <span class = "input-group-btn">
            <button class="btn btn-default" type="submit">Subscribe</button>

        </span>
    </div>
</form>
</code>```

This is my urls.py

```<code>urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^$', views.BlogIndex.as_view(), name='home'),
    url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^footer/$', subscribe_views.newsletter_subscribe, name='subscribe'),
]
</code>```

My Project directory

The button is shown
But the form is not shown..

This is my source in web browser RIGHT-CLICK->VIEW SOURCE

答:
The url router will send the request to the first matching view. That is the only one that is called, and that view has to provide the context data that the template consumes. (You can also write your own context processor to insert context that you need everywhere.)

Since another pattern also matches /footer/, your request is clearly handled by some other view.

```<code>url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
</code>```

If the other view doesn't provide form into the context, there's nothing for Django to render.

Your view function newsletter_detail() is not called from other views, so that context is not used. (Using the undefined none there would have caused a run time error, which shows that the code was never evaluated.)

Catch-all routes such as entry_detail should either be used as the last url route, or be made more specific. Something like r'^/blog/(?P<slug>[-\w]+)/$', for instance, which will not match /footer/.

For a simple "subscribe" form in the footer, I recommend writing it as just html, and set up a route /subscribe/ to handle POST requests. There's not anything to gain by using Django's form framework for such a simple case (Just one field).

The django docs has an example of how you can implement something like this.

You footer.html template fragment should not require any context that is not automatically inserted by a context processor. Django's CsrfViewMiddleware provides the {% csrf_token %}, so that's an example of something you can use in template fragments such as a footer.

If you need some complicated form in your footer, you can write custom middleware to insert a Django Form instance in every context, (but you should probably give it a less generic name than form).

Body:
I am trying to show a newsletter form, and it is not shown in the page

This is my models.py

from django.db import models

# Create your models here.

class newsletter_user(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

This is my forms.py

from django import forms
from .models import newsletter_user

class newsletterForm(forms.ModelForm):

    class Meta:
        model = newsletter_user
        fields = ['email']

        def clean_email(self):
            email = self.cleaned_data.get('email')
            return email

This is my admin.py

from django.contrib import admin

from .models import newsletter_user
# Register your models here.
class newsletterAdmin(admin.ModelAdmin):
    list_display = ('email','date_added',)

admin.site.register(newsletter_user,newsletterAdmin)

This is the views.py

from django.shortcuts import render
from .models import newsletter_user
from .forms import newsletterForm

# Create your views here.
def newsletter_subscribe(request):
    form = newsletterForm(request.POST or none)

    if form.is_valid():
        instance = form.save(commit=false)
        if newsletter_user.objects.filter(email=instance.email).exists():
            print("already exists")
        else:
            instance.save()

    context = {'form':form,}
    template = "/blog/templates/footer.html"
    return render(request, template, context)

This is the html

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

        {{form}}  {% csrf_token %}

            <button class="btn btn-default" type="submit">Subscribe</button>

</form>

This is my urls.py

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^$', views.BlogIndex.as_view(), name='home'),
    url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^footer/$', subscribe_views.newsletter_subscribe, name='subscribe'),
]

My Project directory

The button is shown
But the form is not shown..

This is my source in web browser RIGHT-CLICK->VIEW SOURCE

Body:
The url router will send the request to the first matching view. That is the only one that is called, and that view has to provide the context data that the template consumes. (You can also write your own context processor to insert context that you need everywhere.)

Since another pattern also matches /footer/, your request is clearly handled by some other view.

url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),

If the other view doesn't provide form into the context, there's nothing for Django to render.

Your view function newsletter_detail() is not called from other views, so that context is not used. (Using the undefined none there would have caused a run time error, which shows that the code was never evaluated.)

Catch-all routes such as entry_detail should either be used as the last url route, or be made more specific. Something like r'^/blog/(?P<slug>[-\w]+)/$', for instance, which will not match /footer/.

For a simple "subscribe" form in the footer, I recommend writing it as just html, and set up a route /subscribe/ to handle POST requests. There's not anything to gain by using Django's form framework for such a simple case (Just one field).

The django docs has an example of how you can implement something like this.

You footer.html template fragment should not require any context that is not automatically inserted by a context processor. Django's CsrfViewMiddleware provides the {% csrf_token %}, so that's an example of something you can use in template fragments such as a footer.

If you need some complicated form in your footer, you can write custom middleware to insert a Django Form instance in every context, (but you should probably give it a less generic name than form).


问:
Angular js inside of an ng-if
I know this is not how the code should be structured but I am limited.  I am trying to include a datatable inside angular ng-if section.  When I take off the ng-if statement the js runs fine.  I am looking for ways around this where it works.  I have tried to move the js outside of the ng-if, but then the datatable doesn't work.  Any hint in the right direction would be helpful.  Thanks.</p>

```<code><div ng-if="test">
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
    <!-- Results table -->
    <table id="example2" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Account</th>
                <th>Created On</th>
                <th>Table ID</th>
                <th>Edit</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2011-04-28 13:32:07</th>
                <th>Mortgage</th>
                <th>Edit</th>
            </tr>
            <tr ng-click="displayStatementToggle()">
                <th>123</th>
                <th>2016-04-18 14:36:07</th>
                <th>Monthly</th>
                <th>Edit</th>
            </tr>
        </tbody>
    </table>
    <script>
        $(document).ready(function() {
            $('#example2').DataTable();
        });
    </script>
</div>
</code>```

答:
ng-if has its own scope, so the functions you are calling are undefined inside of it.

ng-show is a possible solution, but has it's own caveats.

Plase, take a look at this answer, which explains the importance of using the dot in your directives. Even if you choose to use ng-show, I would recommend that you refactor your controller and view to avoid further complications down the road.

If you are new to angular, don't hesitate to read John Papa's styleguide, which covers that situation and many others.

Title: Angular js inside of an ng-if

Body:
I know this is not how the code should be structured but I am limited.  I am trying to include a datatable inside angular ng-if section.  When I take off the ng-if statement the js runs fine.  I am looking for ways around this where it works.  I have tried to move the js outside of the ng-if, but then the datatable doesn't work.  Any hint in the right direction would be helpful.  Thanks.

                Account
                Created On
                Table ID
                Edit

                123
                2011-04-28 13:32:07
                Mortgage
                Edit

                123
                2016-04-18 14:36:07
                Monthly
                Edit


问:
php class extend approch vs static approch,which one is better
Approch 1：

```<code>class Storage extends SaeStorage {
public function save($data,$name){
    if (! $this->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $this->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}
</code>```

}

approach 2：

```<code>class Storage  {
public static  function save($data,$name){
    $SaeStorage = new SaeStorage();
    if (! $SaeStorage->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $SaeStorage->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}
</code>```

}

答:
I propose to use dependency injection pattern.
Here is example </p>

Body:
Approch 1：

class Storage extends SaeStorage {
public function save($data,$name){
    if (! $this->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $this->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}

}

approach 2：

class Storage  {
public static  function save($data,$name){
    $SaeStorage = new SaeStorage();
    if (! $SaeStorage->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $SaeStorage->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}

}


问:
Passing class's method in requestAnimationFrame
When I call app.update() in console this works, but when I use requestAnimationFrame there is an error:

Uncaught TypeError: Cannot read property 'drops' of undefined at update (oee.html:40)

It works while using setInterval.

What am I missing?

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
      *{
        margin:0;
        padding:0;
      }
      #app{
        height:100vh;
        width:100vw;
        background-color: red;
        overflow: hidden;
      }
      .drop{
        position:absolute;
        background-color:#fff;
        top:10px;
        width: 5px;
      }
    </style>
  </head>
  <body>
    <div id="app">
    </div>
    <script type="text/javascript">
      class App{
        constructor(){
          this.el = document.getElementById("app");
          this.height=this.el.clientHeight;
          this.width=this.el.clientWidth;
          this.drops=[];
          for(var i=0;i<100;i++){
            this.drops.push(new Drop(this.height,this.width));
          }
        }
        update(){
          this.drops.forEach(function(drop){
            drop.update();
          });
        }
      }

      class Drop{
        constructor(appHeight,appWidth){
          this.speed=Math.random();
          this.el=document.createElement("div");
          this.el.setAttribute("class","drop");
          this.el.style.height=(Math.random()*10+5)+"px";
          this.el.style.left=(Math.random()*appWidth)+"px";
          this.appHeight=appHeight;
          document.getElementById("app").appendChild(this.el);
          this.el.style.top=0;
        }

        update(){
          this.top=this.el.style.top.replace("px","");
          this.el.style.top=(this.top>this.appHeight)?"0px":(parseFloat(this.top) + parseFloat(this.speed*300))+"px";
        }
      }
      var app=new App();
      requestAnimationFrame(app.update);
    </script>
  </body>
</html>
</code>```

答:
When you call app.update(), you are calling the update function as a method of the app object.

But the code shown in the question doesn't call your function as a method:

```<code>requestAnimationFrame(app.update);
</code>```

When you write app.update (without using parentheses), you are just getting a reference to the app.update function as a standalone function. It loses the connection to the app object. When requestAnimationFrame() later calls your update function, it just calls the function directly without any this object. So when update references this.drops it fails.

You didn't list your setInterval() version, but one thing we can be sure of is that it did not look like this:

```<code>setInterval( app.update, 10 );
</code>```

If that were the code you used, it would have the same problem you're having with requestAnimationFrame(). You may have written something like this:

```<code>setInterval( function() {
    app.update();
}, 10 );
</code>```

Now your setInterval() callback is the anonymous function, and that function calls app.update() as a method.

You can do the same thing with requestAnimationFrame(), except that you need to call requestAnimationFrame() each time you want to wait for another frame. In other words, it's more like setTimeout() rather than setInterval(). So it could look like this:

```<code>var updater = function() {
    app.update();
    requestAnimationFrame( updater );  // for subsequent frames
};

requestAnimationFrame( updater );  // for the first frame
</code>```

Now your code should work as expected.

Here's an updated version of yuriy636's CodePen test with animation working.

Body:
When I call app.update() in console this works, but when I use requestAnimationFrame there is an error:

Uncaught TypeError: Cannot read property 'drops' of undefined at update (oee.html:40)

It works while using setInterval.

What am I missing?

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

Body:
When you call app.update(), you are calling the update function as a method of the app object.

But the code shown in the question doesn't call your function as a method:

requestAnimationFrame(app.update);

When you write app.update (without using parentheses), you are just getting a reference to the app.update function as a standalone function. It loses the connection to the app object. When requestAnimationFrame() later calls your update function, it just calls the function directly without any this object. So when update references this.drops it fails.

You didn't list your setInterval() version, but one thing we can be sure of is that it did not look like this:

setInterval( app.update, 10 );

If that were the code you used, it would have the same problem you're having with requestAnimationFrame(). You may have written something like this:

setInterval( function() {
    app.update();
}, 10 );

Now your setInterval() callback is the anonymous function, and that function calls app.update() as a method.

You can do the same thing with requestAnimationFrame(), except that you need to call requestAnimationFrame() each time you want to wait for another frame. In other words, it's more like setTimeout() rather than setInterval(). So it could look like this:

var updater = function() {
    app.update();
    requestAnimationFrame( updater );  // for subsequent frames
};

requestAnimationFrame( updater );  // for the first frame

Now your code should work as expected.

Here's an updated version of yuriy636's CodePen test with animation working.


问:
C# sql query and datatable with no-date format to get difference
I take with SQL query 2 columns - 1st is only with numbers, 2nd is with date. But values from 1st column are date too, but without ":" and spaces (non-date format).

I need 3rd column in datatable which give me difference between 1st and 2nd time.

Can you give me advice how to proceed ? I tried manually add ":", I cannot change SQL database - only read and input into datatable.

SqlDataAdapter test = new SqlDataAdapter(query, con2);
test.Fill(dt);
dt.Columns.Add("Real", typeof(int));
dt.Columns["Real"].SetOrdinal(5);
DataTable distinctTable = dt.DefaultView.ToTable( /*distinct*/ true);
dataGridView1.DataSource = distinctTable;
distinctTable.Columns["Real"].SetOrdinal(5);
this.dataGridView1.Columns["Column1"].Visible = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

int a = 0;
foreach (DataRow d in distinctTable.Rows)
{
   try
   {
       DateTime da = DateTime.ParseExact(dataGridView1.Rows[a].Cells["Real"].Value.ToString(), "yyyy-dd-MM hh:mm", System.Globalization.CultureInfo.InvariantCulture);
       d["Real"] = da;
       ++a;
   }
   catch (Exception)
   {
       ++a;
       continue;
   }
}
```

<p>Example table:</p>

```   Column1           Column2
_______________|____________________
20170707060713 | 2017-07-07 06:13:43
20170707061326 | 2017-07-07 06:21:16
20170707062059 | 2017-07-07 06:28:54
20170707062837 | 2017-07-07 06:36:22
20170707063605 | 2017-07-07 06:43:50
20170707064333 | 2017-07-07 06:51:08
```

答:
Following SQL query converts numeric (bigint) column to SQL DateTime format, and calculate diff between two dates:

```<code>DECLARE @Test table(num bigint, dte datetime);
INSERT INTO @Test(num, dte) VALUES(20170707060713, '2017-07-05 18:36:58')

SELECT num,
       dte,
      DATEDIFF(hour, dte, convert(DATETIME, substring(CAST(num AS NVARCHAR), 0, 9)
                        +' '+substring(CAST(num AS NVARCHAR), 9, 2)
                        +':'+substring(CAST(num AS NVARCHAR), 11, 2)
                        +':'+substring(CAST(num AS NVARCHAR), 13, 2))) AS dteFromNum
    from @Test;
</code>```

SqlFiddle Demo

Body:
I take with SQL query 2 columns - 1st is only with numbers, 2nd is with date. But values from 1st column are date too, but without ":" and spaces (non-date format).

I need 3rd column in datatable which give me difference between 1st and 2nd time.

Can you give me advice how to proceed ? I tried manually add ":", I cannot change SQL database - only read and input into datatable.

SqlDataAdapter test = new SqlDataAdapter(query, con2);
test.Fill(dt);
dt.Columns.Add("Real", typeof(int));
dt.Columns["Real"].SetOrdinal(5);
DataTable distinctTable = dt.DefaultView.ToTable( /*distinct*/ true);
dataGridView1.DataSource = distinctTable;
distinctTable.Columns["Real"].SetOrdinal(5);
this.dataGridView1.Columns["Column1"].Visible = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

int a = 0;
foreach (DataRow d in distinctTable.Rows)
{
   try
   {
       DateTime da = DateTime.ParseExact(dataGridView1.Rows[a].Cells["Real"].Value.ToString(), "yyyy-dd-MM hh:mm", System.Globalization.CultureInfo.InvariantCulture);
       d["Real"] = da;
       ++a;
   }
   catch (Exception)
   {
       ++a;
       continue;
   }
}

Example table:

   Column1           Column2
_______________|____________________
20170707060713 | 2017-07-07 06:13:43
20170707061326 | 2017-07-07 06:21:16
20170707062059 | 2017-07-07 06:28:54
20170707062837 | 2017-07-07 06:36:22
20170707063605 | 2017-07-07 06:43:50
20170707064333 | 2017-07-07 06:51:08

Body:
Following SQL query converts numeric (bigint) column to SQL DateTime format, and calculate diff between two dates:

DECLARE @Test table(num bigint, dte datetime);
INSERT INTO @Test(num, dte) VALUES(20170707060713, '2017-07-05 18:36:58')

SELECT num,
       dte,
      DATEDIFF(hour, dte, convert(DATETIME, substring(CAST(num AS NVARCHAR), 0, 9)
                        +' '+substring(CAST(num AS NVARCHAR), 9, 2)
                        +':'+substring(CAST(num AS NVARCHAR), 11, 2)
                        +':'+substring(CAST(num AS NVARCHAR), 13, 2))) AS dteFromNum
    from @Test;

SqlFiddle Demo


问:
How to rank transactions in custom order in redshift?
I have some transactions in database. I need to rank the transaction in a custom order. The transactions are

Transactions needs to be given rank in descending order of csave column and transactions with same tx number will get the same rank. So i execute below query:

```<code>SELECT * , DENSE_RANK() over (ORDER BY csave desc, tx) AS rank
FROM noma_d.setu_test.report_result
</code>```

And the result:

In the above transactions, for same tx, the value of csave column is same. Let's consider below transactions where for tx =1, csave values are different.

Now if i execute the same above query, then the result i got:

Here, one transaction of tx = 1 has rank = 2 and another transaction of tx = 1 has rank = 5. But i want to give all the transactions of tx = 1 to rank = 2 as one transaction of the tx = 1 got rank 2 so the rest of the transactions with tx = 1 will also have to be given rank 2.

The expected output will be like below:

How will i achieve this by modifying my above query?

答:
As answered by JohnHC, need to group by the tx before ranking and also use rank() instead of row_number(). The final query is:

```<code>select t1.*, t2.rank
from noma_d.setu_test.report_result as t1
inner join
(
    select a2.*, rank() over (order by csave desc, tx) as rank
    from
    (
        select tx, max(csave) as csave
        from noma_d.setu_test.report_result
        group by tx
    ) a2
) t2
    on t1.tx = t2.tx
</code>```

Body:
I have some transactions in database. I need to rank the transaction in a custom order. The transactions are

Transactions needs to be given rank in descending order of csave column and transactions with same tx number will get the same rank. So i execute below query:

SELECT * , DENSE_RANK() over (ORDER BY csave desc, tx) AS rank
FROM noma_d.setu_test.report_result

And the result:

In the above transactions, for same tx, the value of csave column is same. Let's consider below transactions where for tx =1, csave values are different.

Now if i execute the same above query, then the result i got:

Here, one transaction of tx = 1 has rank = 2 and another transaction of tx = 1 has rank = 5. But i want to give all the transactions of tx = 1 to rank = 2 as one transaction of the tx = 1 got rank 2 so the rest of the transactions with tx = 1 will also have to be given rank 2.

The expected output will be like below:

How will i achieve this by modifying my above query?

Body:
As answered by JohnHC, need to group by the tx before ranking and also use rank() instead of row_number(). The final query is:

select t1.*, t2.rank
from noma_d.setu_test.report_result as t1
inner join
(
    select a2.*, rank() over (order by csave desc, tx) as rank
    from
    (
        select tx, max(csave) as csave
        from noma_d.setu_test.report_result
        group by tx
    ) a2
) t2
    on t1.tx = t2.tx


问:
Parse Server Cloud Code set notifications badge to specific number
I am using cloud code on parse server to send push notifications to specific users on the app. Currently the badge is set to increment for each notification the user receives, which isn't bad, however I find it unattractive to see high numbers in the badge icon. I was wondering if instead of incrementing with each notification I can just set the badge number to be 1 so even if the user has 5 new notifications it will always say 1 in the corner.

Here is what my current javascript cloud code looks like

  Parse.Cloud.define("mentions", function(request,response){

  var message = request.params.message;
  var pushQuery = new Parse.Query(Parse.Installation);
  pushQuery.equalTo("user",request.params.User);

  Parse.Push.send({
    where: pushQuery,
    data : {
      alert: message,
      badge: "increment",
    }
    }, {
    success: function(result) {
    console.log(JSON.stringify(result));
    response.success(result);
    },
    error: function(error) {
    console.error(JSON.stringify(error));
    response.error(error.message)
    },
  useMasterKey: true

  });

});```

答:
badge: 1, check the guide here:

http://docs.parseplatform.org/rest/guide/#sending-options

Looks like that option is iOS only, though, so you won't be able to do this for Android.

The value should be a number, unless you are specifying "Increment" to add one to the current badge number.


问:
How do I split an array into smaller arrays bsaed on a condition?
Ruby 2.4.  I have an array of strings

```<code>2.4.0 :007 > arr = ["a", "b", "g", "e", "f", "i"]
 => ["a", "b", "g", "e", "f", "h", "i"]
</code>```

How do I split my array into smaller arrays based on a condition?  I have a function -- "contains_vowel," which returns true if a string contains "a", "e", "i", "o", or "u".  How would I take an array of strings and split it into smaller arrays, using a divider function of "contains_vowel"?  That is, for the above, the resulting array of smaller arrays would be

```<code>[["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]
</code>```

If an element of the larger array satisfies the condition, it would become an array of one element.

答:
```<code>arr = ["a", "b", "g", "e", "f", "i"]

r = /[aeiou]/
arr.slice_when { |a,b| a.match?(r) ^ b.match?(r) }.to_a
   => [["a"], ["b", "g"], ["e"], ["f"], ["i"]]
</code>```

String#match? made its debut in Ruby v2.4. For earlier versions you could use (for example) !!(b =~ r), where !! converts a truthy/falsy value to true/false. That converstion is needed because the XOR operator ^ serves double-duty: it's a logical XOR when a and b in a^b are true, false or nil, and a bit-wise XOR when the operands are integers, such as 2^6 #=> 4 (2.to_s(2) #=> "10"; 6.to_s(2) #=> "110"; 4.to_s(2) #=> "100").

Body:
Ruby 2.4.  I have an array of strings

2.4.0 :007 > arr = ["a", "b", "g", "e", "f", "i"]
 => ["a", "b", "g", "e", "f", "h", "i"]

How do I split my array into smaller arrays based on a condition?  I have a function -- "contains_vowel," which returns true if a string contains "a", "e", "i", "o", or "u".  How would I take an array of strings and split it into smaller arrays, using a divider function of "contains_vowel"?  That is, for the above, the resulting array of smaller arrays would be

[["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]

If an element of the larger array satisfies the condition, it would become an array of one element.

Body:
arr = ["a", "b", "g", "e", "f", "i"]

r = /[aeiou]/
arr.slice_when { |a,b| a.match?(r) ^ b.match?(r) }.to_a
   => [["a"], ["b", "g"], ["e"], ["f"], ["i"]]

String#match? made its debut in Ruby v2.4. For earlier versions you could use (for example) !!(b =~ r), where !! converts a truthy/falsy value to true/false. That converstion is needed because the XOR operator ^ serves double-duty: it's a logical XOR when a and b in a^b are true, false or nil, and a bit-wise XOR when the operands are integers, such as 2^6 #=> 4 (2.to_s(2) #=> "10"; 6.to_s(2) #=> "110"; 4.to_s(2) #=> "100").


答: Just add multidex support in your project settings. That should solve your problem.</p>

Title: Analyze methods count of an android library

Body:
I recently in my project get 65536 error message about dex size and blahblah.

and now I'm trying to reduce my dex size but I don't know exactly wich of my  libraries is adding more size to dex file I just can see hole dex file size in apk analyzer is there a tool or way to analyze dex file and getting information about how many methods this library has and how much adding to my dex file?


问:
Yii2 when used transactions for multi step registration then on the step back how to retrive data
Current Implementation

Currently I am using multi step registration and i have total 3 steps for the same.

Last step is confirm all data entered and then submit.

Now I am using transaction on the very beginning of step 1 like :

```<code>$transaction = Yii::$app->db->beginTransaction();
</code>```

if execution fails at any point I am using

```<code>$transaction->rollBack();
</code>```

to rollback all the entries from database

Now if everything is executed well and in the last step user confirms entered data and submit i save all data in db like :

```<code>$transaction->commit();
</code>```

Issue

Now as I am using multi step registration if anytime user want to go back to previous step, then how to retrieve filled data ???

We can not retrieve data from table as still we haven't store anything into db until last commit statement.

Current Solution

One solution is that is to use session to store temporary data but I am looking for any other way

答:
If you are using a new action for each of the steps (and one table called 'registration' i.e.) then for each action you can pass registration id, and load fields depending on step number.
So, let's consider you have a registration form with name, surname, age, gender fields, and in Step-1 you fill name, surname, and in Step 2 fill age and gender.. Your model will look like follow:

```<code>class Registration extends \yii\db\ActiveRecord
{
    const SCENARIO_STEP1 = 'step1';
    const SCENARIO_STEP2 = 'step2';

    public function scenarios()
    {
        return [
            self::SCENARIO_STEP1 => ['name', 'surname'],
            self::SCENARIO_STEP2 => ['age', 'gender'],
        ];
    }

    public function rules()
    {
        ... your validation for fields...
</code>```

...

Note that Scenarios are important here to enable validation for some exact fields in exact step (More about scenarios you can read from official documentation)

And the action for your first step will look this way:

```<code>public function actionStep1()
{
    $model = new Registration();
    $model->setScenario(Registration::SCENARIO_STEP1);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['step-2', 'id' => $model->id]);
    } else {
        return $this->render('step-1', [
            'model' => $model,
        ]);
    }
}
</code>```

And in your step-1 view you have fields name and surname that you need to fill, and where validation will work for them only as listed in scenarios() method). Then in second step action the code will look like this:

```<code>public function actionStep2($id)
{
    $model = Order::findOne($id);
    $model->setScenario(Order::SCENARIO_STEP2);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['finish', 'id' => $model->id]);
    } else {
        return $this->render('step-2', [
            'model' => $model,
        ]);
    }
}
</code>```

.. As you can see, in second step we pass id of already existing Registration model, and continue filling its attributes. Depending on how much steps you have, you can redirect from second step to the third one, or show finish message and do some other logic that you need..

I think you have a little bit wrong idea about how transactions are used, because transaction is the way how rows in DB are saved (preventing these rows from being changed somewhere else, when the change itself is being proceeded..)

Another approach of making a multi step registration is to include all steps in single page, and show/hide needed fields depending on your stage (Using JQuery for example). I remember answering this kind of question already, but cannot find the link.. If I succeed, I'll definitely update my answer..

Hope my answer was helpful

Body:
Current Implementation

Currently I am using multi step registration and i have total 3 steps for the same.

Last step is confirm all data entered and then submit.

Now I am using transaction on the very beginning of step 1 like :

$transaction = Yii::$app->db->beginTransaction();

if execution fails at any point I am using

$transaction->rollBack();

to rollback all the entries from database

Now if everything is executed well and in the last step user confirms entered data and submit i save all data in db like :

$transaction->commit();

Issue

Now as I am using multi step registration if anytime user want to go back to previous step, then how to retrieve filled data ???

We can not retrieve data from table as still we haven't store anything into db until last commit statement.

Current Solution

One solution is that is to use session to store temporary data but I am looking for any other way

Body:
If you are using a new action for each of the steps (and one table called 'registration' i.e.) then for each action you can pass registration id, and load fields depending on step number.
So, let's consider you have a registration form with name, surname, age, gender fields, and in Step-1 you fill name, surname, and in Step 2 fill age and gender.. Your model will look like follow:

class Registration extends \yii\db\ActiveRecord
{
    const SCENARIO_STEP1 = 'step1';
    const SCENARIO_STEP2 = 'step2';

    public function scenarios()
    {
        return [
            self::SCENARIO_STEP1 => ['name', 'surname'],
            self::SCENARIO_STEP2 => ['age', 'gender'],
        ];
    }

    public function rules()
    {
        ... your validation for fields...

...

Note that Scenarios are important here to enable validation for some exact fields in exact step (More about scenarios you can read from official documentation)

And the action for your first step will look this way:

public function actionStep1()
{
    $model = new Registration();
    $model->setScenario(Registration::SCENARIO_STEP1);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['step-2', 'id' => $model->id]);
    } else {
        return $this->render('step-1', [
            'model' => $model,
        ]);
    }
}

And in your step-1 view you have fields name and surname that you need to fill, and where validation will work for them only as listed in scenarios() method). Then in second step action the code will look like this:

public function actionStep2($id)
{
    $model = Order::findOne($id);
    $model->setScenario(Order::SCENARIO_STEP2);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['finish', 'id' => $model->id]);
    } else {
        return $this->render('step-2', [
            'model' => $model,
        ]);
    }
}

.. As you can see, in second step we pass id of already existing Registration model, and continue filling its attributes. Depending on how much steps you have, you can redirect from second step to the third one, or show finish message and do some other logic that you need..

I think you have a little bit wrong idea about how transactions are used, because transaction is the way how rows in DB are saved (preventing these rows from being changed somewhere else, when the change itself is being proceeded..)

Another approach of making a multi step registration is to include all steps in single page, and show/hide needed fields depending on your stage (Using JQuery for example). I remember answering this kind of question already, but cannot find the link.. If I succeed, I'll definitely update my answer..

Hope my answer was helpful


问:
How to remove space between span elements using inline style only?
I would like to display a single word "WorldWide" in two colors(red and blue).

I've tried using span elements as below.

```<code><span style="color:red">World</span><span style="color:blue">Wide</span>
</code>```

but the issue is that the email clients format the html as below so the text ends-up displayed in two words (World Wide instead of WordWide) due the new lines added in the html.

```<code><span style="color:red">World
</span>
<span style="color:blue">Wide
</span>
</code>```

So my question is: How can I display a single word in two colors considering that the html clients format/add new lines to span elements? Please note that only inline styling is allowed in email clients so I can't use  tags.

答:
The float property specifies whether or not a box (an element) should float.
You may add the float in your span tag.
For your code you just need, float:left with the first span tag.

So it will be

World
Wide```

Body:
I would like to display a single word "WorldWide" in two colors(red and blue).

I've tried using span elements as below.

WorldWide

but the issue is that the email clients format the html as below so the text ends-up displayed in two words (World Wide instead of WordWide) due the new lines added in the html.

World

Wide

So my question is: How can I display a single word in two colors considering that the html clients format/add new lines to span elements? Please note that only inline styling is allowed in email clients so I can't use  tags.

Body:
The float property specifies whether or not a box (an element) should float.
You may add the float in your span tag.
For your code you just need, float:left with the first span tag.

So it will be

<span style="color:#FF0000; float: left">World</span>
<span style="color:#0D0DFF;">Wide</span>


问:
Is there a way to put columns of a table in divs using DataTable?
So what I'm trying to do is make it so that the user can choose which columns of a table to display after it has already been generated. I already have functionality that does this, after the user changes their options it destroys the current table and then reinitializes it with different visibility settings for certain columns. While this works, it's sorta slow and doesn't look as pretty as say, the columns just disappearing. I think if I put the columns in uniquely id'd divs and then edited their css to say display: none; using jquery when the user deselects them it would work quicker and more attractively, but I haven't been able to find a way to put the columns in divs.

答:
May be a better solution but you could use the CSS nth-child (https://www.w3schools.com/cssref/sel_nth-child.asp) property and jQuery's .index()to identify the column you wish to remove and remove the column from each table row.

Something like this might work (assuming you have a header row containing  elements):

```<code>$('table th').on("click", function() {
    var index = $(this).index() + 1;
    $.each('table tr', function() {
        $(this).find('td:nth-child(' + index + ')').hide();
    });
});
</code>```

Body:
May be a better solution but you could use the CSS nth-child (https://www.w3schools.com/cssref/sel_nth-child.asp) property and jQuery's .index()to identify the column you wish to remove and remove the column from each table row.

Something like this might work (assuming you have a header row containing <th> elements):

$('table th').on("click", function() {
    var index = $(this).index() + 1;
    $.each('table tr', function() {
        $(this).find('td:nth-child(' + index + ')').hide();
    });
});


问:
Not show Correct Scores java
in my code , i have 2 array name and score and length of both is 2

```<code>import java.util.Scanner;

public class Test {

    private static Scanner key = new Scanner (System.in);

    public static void main (String [] args){

        String [] name = new String [2];
        int [] score = new int [2];

        readInfo(name, score);
        showInfo(name, score);

    }

    public static void readInfo (String [] name, int [] score){

        for (int i = 0; i < name.length; i++){

            System.out.print("Name no."+(i + 1)+": ");
            name [i] = key.next();

            for (int j = 0; j < score.length; j++){

                System.out.print("Score no."+(j + 1)+": ");
                score [j] = key.nextInt();

            }

            System.out.println("");

        }

    }

    public static void showInfo (String [] name, int [] score){

        System.out.println("Name\tScores\n");

        for (int i = 0; i < name.length; i++){

            System.out.print(name [i]);

            for (int j = 0; j < score.length; j++ )
                System.out.println("\t"+score [j]+"\t");

            System.out.println("");
        }

    }

}
</code>```

when i input names and scores, in output only show second scores for both names.

```<code>Name no.1: john
Score no.1: 17
Score no.2: 19

Name no.2: jack
Score no.1: 12
Score no.2: 18

Name    Scores

john    12
        18

jack    12
        18
</code>```

this is my problem how can i fix it?

答: You have four total scores, and an array that only holds two. When you run readInfo, the second name's scores overwrite the data in the scores array that were stored there from the first name. You would need to have enough spaces in the array for all the scores, or choose a different way to store this data.</p>

Title: Not show Correct Scores java

Body:
in my code , i have 2 array name and score and length of both is 2

import java.util.Scanner;

public class Test {

    private static Scanner key = new Scanner (System.in);

    public static void main (String [] args){

        String [] name = new String [2];
        int [] score = new int [2];

        readInfo(name, score);
        showInfo(name, score);

    }

    public static void readInfo (String [] name, int [] score){

        for (int i = 0; i < name.length; i++){

            System.out.print("Name no."+(i + 1)+": ");
            name [i] = key.next();

            for (int j = 0; j < score.length; j++){

                System.out.print("Score no."+(j + 1)+": ");
                score [j] = key.nextInt();

            }

            System.out.println("");

        }

    }

    public static void showInfo (String [] name, int [] score){

        System.out.println("Name\tScores\n");

        for (int i = 0; i < name.length; i++){

            System.out.print(name [i]);

            for (int j = 0; j < score.length; j++ )
                System.out.println("\t"+score [j]+"\t");

            System.out.println("");
        }

    }

}

when i input names and scores, in output only show second scores for both names.

Name no.1: john
Score no.1: 17
Score no.2: 19

Name no.2: jack
Score no.1: 12
Score no.2: 18

Name    Scores

john    12
        18

jack    12
        18

this is my problem how can i fix it?


问:
Why do I get an exception when I reference DataGridView CurrentRow?
I'm trying to get a "changed currentcell" event in DataGridView, but every time I try to load the form (which is a child of another form), I get an exception in the datagridview_currentcell event:

SystemNullReferenceException: object not set to an instance of an object.

I guess it's because I haven't selected any row. Of course I can use catch and try to bypass, but I want a more elegant way and to know what am I doing wrong.

Here's my code:

Form2.CS:

```<code>namespace AsefotSystem
{
    public partial class ownerReport : Form
    {
        public ownerReport()
        {
            InitializeComponent();
            loadDB();
            setGrid();
        }

        private void loadDB()
        {
            string connetionString = null;
            OleDbConnection connection;
            OleDbDataAdapter oledbAdapter;

            DataSet ds = new DataSet();
            string sql2 = null;
            connetionString = ConfigurationManager.ConnectionStrings["RiskDB"].ConnectionString;
            sql2 = "select * From tbl2_asefot";
            connection = new OleDbConnection(connetionString);

            try
            {
                connection.Open();

                oledbAdapter = new OleDbDataAdapter(sql2, connection);
                oledbAdapter.Fill(ds, "Asefot");
                oledbAdapter.Dispose();

                connection.Close();
                dsAsefotGrid = ds;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void setGrid()
        {
            Controls.Add(dataGridView1);
            dataGridView1.DataSource = dsAsefotGrid.Tables[0];
        }

        private void dataGridView1_CurrentCell(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
                textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        DataSet dsAsefotGrid;
    }
}
</code>```

Form2.Designer.CS:

```<code>this.dataGridView1.CurrentCellChanged += new System.EventHandler(this.dataGridView1_CurrentCell);
</code>```

答:
Your dataGridView Cell has no value and you are trying to save a string of null.

Try catching the exception and inform the user that he has to write something in the cell

```<code>try
{
    textBox1.Text = dataGridView1.Rows[dataGridView1.
    CurrentRow.Index].Cells[2].Value.ToString();
}
catch(NullReferenceException)
{
    MessageBox.Show("You cannot process an empty cell");
}
</code>```

Please find more information under the following link:

Body:
I'm trying to get a "changed currentcell" event in DataGridView, but every time I try to load the form (which is a child of another form), I get an exception in the datagridview_currentcell event:

SystemNullReferenceException: object not set to an instance of an object.

I guess it's because I haven't selected any row. Of course I can use catch and try to bypass, but I want a more elegant way and to know what am I doing wrong.

Here's my code:

Form2.CS:

namespace AsefotSystem
{
    public partial class ownerReport : Form
    {
        public ownerReport()
        {
            InitializeComponent();
            loadDB();
            setGrid();
        }

        private void loadDB()
        {
            string connetionString = null;
            OleDbConnection connection;
            OleDbDataAdapter oledbAdapter;

            DataSet ds = new DataSet();
            string sql2 = null;
            connetionString = ConfigurationManager.ConnectionStrings["RiskDB"].ConnectionString;
            sql2 = "select * From tbl2_asefot";
            connection = new OleDbConnection(connetionString);

            try
            {
                connection.Open();

                oledbAdapter = new OleDbDataAdapter(sql2, connection);
                oledbAdapter.Fill(ds, "Asefot");
                oledbAdapter.Dispose();

                connection.Close();
                dsAsefotGrid = ds;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void setGrid()
        {
            Controls.Add(dataGridView1);
            dataGridView1.DataSource = dsAsefotGrid.Tables[0];
        }

        private void dataGridView1_CurrentCell(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
                textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        DataSet dsAsefotGrid;
    }
}

Form2.Designer.CS:

this.dataGridView1.CurrentCellChanged += new System.EventHandler(this.dataGridView1_CurrentCell);

Body:
Your dataGridView Cell has no value and you are trying to save a string of null.

Try catching the exception and inform the user that he has to write something in the cell

try
{
    textBox1.Text = dataGridView1.Rows[dataGridView1.
    CurrentRow.Index].Cells[2].Value.ToString();
}
catch(NullReferenceException)
{
    MessageBox.Show("You cannot process an empty cell");
}

Please find more information under the following link:


问:
Xamarin binding Reference is it needed for every element?
I have this code in my application:

```<code><StackLayout x:Name="pfs" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

   <StackLayout Grid.Row="0" Grid.Column="1" Padding="0,0,20,0" Orientation="Horizontal"
      HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand">
      <Label x:Name="scoreCountLabel"
        TextColor="{Binding BindingContext.TickMarkColor, Source={Reference pfs}}"/>
   </StackLayout>
</code>```

I am trying to understand how the TextColor is set. Can someone explain to me why the developer has set the Source={Reference pfs}

Why is this needed as it's already inside a StackLayout with the name of pfs?

答:
It's completely unnecessary from what I can tell. BindingContext is inherited by all subviews, so referencing the parent view's BindingContext is redundant.

```<code>TextColor="{Binding TickMarkColor}"/>
</code>```

Done.

Body:
I have this code in my application:

<StackLayout x:Name="pfs" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

   <StackLayout Grid.Row="0" Grid.Column="1" Padding="0,0,20,0" Orientation="Horizontal"
      HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand">

   </StackLayout>

I am trying to understand how the TextColor is set. Can someone explain to me why the developer has set the Source={Reference pfs}

Why is this needed as it's already inside a StackLayout with the name of pfs?

Body:
It's completely unnecessary from what I can tell. BindingContext is inherited by all subviews, so referencing the parent view's BindingContext is redundant.

TextColor="{Binding TickMarkColor}"/>

Done.


问:
Could not load file or assembly System.Net.Http version 4.1.1.0
I'm porting a Net Framework 4 dll to Net Core.
When porting my unit tests project I get an exception running some specific tests (not all).

System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This is the project.json for my dll

```<code> {
  "version": "1.0.0-*",

  "dependencies": {
    "log4net": "2.0.7",
    "NETStandard.Library": "1.6.1",
    "Newtonsoft.Json": "9.0.1",
    "StackExchange.Redis": "1.2.1"
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": "dnxcore50"
    }
  }
}
</code>```

And this is Packages.config for the unit tests project

```<code><packages>
  <package id="Castle.Core" version="4.0.0" targetFramework="net462" />
  <package id="log4net" version="2.0.7" targetFramework="net462" />
  <package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="Moq" version="4.7.1" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net462" />
  <package id="StackExchange.Redis" version="1.2.1" targetFramework="net462" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.0.0" targetFramework="net462" />
  <package id="System.IO" version="4.1.0" targetFramework="net462" />
  <package id="System.IO.FileSystem" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Watcher" version="4.0.0" targetFramework="net462" />
  <package id="System.Linq" version="4.1.0" targetFramework="net462" />
  <package id="System.Net.Http" version="4.1.1" targetFramework="net462" />
  <package id="System.Net.NameResolution" version="4.0.0" targetFramework="net462" />
  <package id="System.Runtime" version="4.1.0" targetFramework="net462" />
  <package id="System.Runtime.Extensions" version="4.1.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Algorithms" version="4.2.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Encoding" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Primitives" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.1.0" targetFramework="net462" />
  <package id="System.Text.RegularExpressions" version="4.1.0" targetFramework="net462" />
  <package id="System.Threading.Thread" version="4.0.0" targetFramework="net462" />
</packages>
</code>```

答:
My problem was that my service had a referenced assembly that had a reference to a newer version of System.Net.Http.
I've resolved the issue by updating System.Net.Http in the service.</p>

Body:
I'm porting a Net Framework 4 dll to Net Core.
When porting my unit tests project I get an exception running some specific tests (not all).

System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This is the project.json for my dll

 {
  "version": "1.0.0-*",

  "dependencies": {
    "log4net": "2.0.7",
    "NETStandard.Library": "1.6.1",
    "Newtonsoft.Json": "9.0.1",
    "StackExchange.Redis": "1.2.1"
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": "dnxcore50"
    }
  }
}

And this is Packages.config for the unit tests project

<packages>
  <package id="Castle.Core" version="4.0.0" targetFramework="net462" />
  <package id="log4net" version="2.0.7" targetFramework="net462" />
  <package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="Moq" version="4.7.1" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net462" />
  <package id="StackExchange.Redis" version="1.2.1" targetFramework="net462" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.0.0" targetFramework="net462" />
  <package id="System.IO" version="4.1.0" targetFramework="net462" />
  <package id="System.IO.FileSystem" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Watcher" version="4.0.0" targetFramework="net462" />
  <package id="System.Linq" version="4.1.0" targetFramework="net462" />
  <package id="System.Net.Http" version="4.1.1" targetFramework="net462" />
  <package id="System.Net.NameResolution" version="4.0.0" targetFramework="net462" />
  <package id="System.Runtime" version="4.1.0" targetFramework="net462" />
  <package id="System.Runtime.Extensions" version="4.1.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Algorithms" version="4.2.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Encoding" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Primitives" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.1.0" targetFramework="net462" />
  <package id="System.Text.RegularExpressions" version="4.1.0" targetFramework="net462" />
  <package id="System.Threading.Thread" version="4.0.0" targetFramework="net462" />
</packages>


问:
Shortest path that goes through different points
Let's say I have few points : -5,-4,-3,-2,-1,0,1,2,3,4,5

I'm at point 0, I need to create a line that goes all through the points of 1,2,3,4,5,-1,-2... etc.

The line would start at 0 and end at whatever point that ends as the shortest.

The answer for this example would be that it'd go like this 0->1->2->3->4->5->-1->-2->-3->-4->-5 or that it'd go first to -1 and go all through the minus to the plus, same result (5*4=20 length).

If for example we'd go 0->1->-1->2->-2... it'd end as the longest line that goes straight from point to point (1+2+3+4+5+6+7+8+9+10=10*11/2=55 length)

The question is how to write this in code?

The points might also consist of 2 or 3 dimensional points, where the start would be (0,0,0,0) or whatever, eventually the line can go through all of these points, but which way will achieve the shortest line?

How to make it as a code, as we see it in the eye?

答:
I think this is basically the Travelling Salesman problem.  You've got N destinations, and each pair of destinations has a concrete length between them, and you're trying to find out the shortest travel time to visit all destinations.

You've got two different directions to pursue this, that I can see.  First, is to read up on the Travelling Salesman problem and the various algorithms that have been proposed for it (it's a very famous algorithm problem) and then try to implement one in C# - though just to warn you, you should be very proficient in math, because it's not an easy problem.  Or, alternatively, you can look for someone else's existing implementation for it and just use it without understanding the theoretical underpinnings.


问:
Why do we need connection pool in node.js when node is single threaded?
Node.js is single threaded. The Javascript V8 engine and some of the internal libraries are multi threaded. For I/O, node delegates I/O to OS which may be multi-threaded.

If my node.js application is connecting to redis or ,sql/mariadb server, I assume I should not need a connection pool for redis or mysql.

As a developer, I create 1 redis or mysql connection and reuse it to send/get data. When data arrives, node will invoke the callback to process the data.

I understand connection pooling with Java/.NET but they are multi-threaded and so connection pooling in Java/.NET has clear benefit.

My question is: Why do we need connection pool in node.js when node is single threaded? Is there any benefit of it? Will node not leverage the multi-threading features of underlying OS and javascript engine without the developer having to do it?

Thanks

答:
You need connection pools because even a single thread can hold multiple "blocking" DB connections (assuming RDBMS here). Without a connection pool, your app will create each connection from scratch for every additional DB request, even in a async / non-blocking system like Node.

Example:

```<code>request 1 - insert user  -- wait for response (assume it's 5 secs)
request 2 - insert invoice - wait for response (assume it's 3 secs)
request 3 - insert another invoice
</code>```

Notice that request 3 is processed right away, without waiting for request 1 and 2 to complete. Right here in this single thread, we've already used three resources to connect to the DB. Imagine having to create each one every time you need a DB operation. It's much faster to just grab one from a connection pool!

Body:
You need connection pools because even a single thread can hold multiple "blocking" DB connections (assuming RDBMS here). Without a connection pool, your app will create each connection from scratch for every additional DB request, even in a async / non-blocking system like Node.

Example:

request 1 - insert user  -- wait for response (assume it's 5 secs)
request 2 - insert invoice - wait for response (assume it's 3 secs)
request 3 - insert another invoice

Notice that request 3 is processed right away, without waiting for request 1 and 2 to complete. Right here in this single thread, we've already used three resources to connect to the DB. Imagine having to create each one every time you need a DB operation. It's much faster to just grab one from a connection pool!


问:
Visual Studio, ASP.Net (.Net Framework) and including NuGet installed packages in a project
I have an ASP.Net (.Net Framework) MVC web application in Visual Studio 2017 that is comprised mainly of JavaScript. I have used NuGet to install a package (specifically the marker-animate-unobtrusive package.) The documentation goes on to say that i should include the JavaScript in my HTML pages but upon examining exactly what NuGet did I'm not sure how to proceed.

I have checked my packages.config file and have found a reference to the package, which I have also been able to find in the packages folder in the root of the solution. But these references indicate a TypeScript file - should I just be including that in my HTML?

And how would I do that, if that were the case? Should I route back to the packages folder? That seems like a bad idea, since that's not even included in my project. How can I dynamically link to what I've installed?

I am just getting to grips with Visual Studio and don't understand what it's doing some of the time, so any pointers would be helpful. In a broader sense, the two questions I'm mainly asking are:

What is NuGet doing exactly when you install a package?

How can these packages be accessed in the context of my web pages and JavaScript?

答:
What does NuGet do when you install a package? In this specific case it is extracting the js files to your Scripts folder and if any css is needed then it exacts the CSS files or in some cases folders to your Content folder of your solution.

If you want the js to be included on just certain pages and not all then at the bottom of the target pages (Views > Controller > Whatever.cshtml) you put the following lines:

```<code>    @section css {
        <link href="~/Content/Your installedCSS.css" rel="stylesheet" class="skins" type="text/css">
    }

    @section scripts{
        <script src="~/Scripts/YourInstalledScript.js"></script>
    }
</code>```

What this is telling it to do is to find where you have the section "scripts" and "css" defined in your site layout page (Views > Shared > _Layout) and place the included files there.

Look for lines:

```<code>@RenderSection("css", required: false)

@RenderSection("scripts", required: false)
</code>```

Body:
What does NuGet do when you install a package? In this specific case it is extracting the js files to your Scripts folder and if any css is needed then it exacts the CSS files or in some cases folders to your Content folder of your solution.

If you want the js to be included on just certain pages and not all then at the bottom of the target pages (Views > Controller > Whatever.cshtml) you put the following lines:

    @section css {
        <link href="~/Content/Your installedCSS.css" rel="stylesheet" class="skins" type="text/css">
    }

    @section scripts{
        <script src="~/Scripts/YourInstalledScript.js"></script>
    }

What this is telling it to do is to find where you have the section "scripts" and "css" defined in your site layout page (Views > Shared > _Layout) and place the included files there.

Look for lines:

@RenderSection("css", required: false)

@RenderSection("scripts", required: false)


问:
Why can't Beam AvroIO use runtime parameters and how to use AvroIO in Dataflow templates?
I tried to use runtime parameters in Dataflow in combination with AvroIO only to run into serialization issues (java.io.NotSerializableException: org.apache.avro.Schema$RecordSchema). Then I discovered AvroIO is missing from the table on the bottom of this page: https://cloud.google.com/dataflow/docs/templates/creating-templates

I guess it's due to unserializability of some Avro classes, is that true? Are there plans to work around this?

If not, how should I do it if I need to use runtime parameters in templates that write to Avro files? Do I have to give up templates and somehow make my service run and deploy the job the stadard way every time it needs to? That means a lot of additional network traffic and/or infrastructural code on my side. I kinda refuse to believe I'm the first one who needs to run templated jobs and use Avro at the same time. How do people solve this?

答:
Using templates with a specific IO requires that the IO must accept ValueProvider versions of any parameters that will be filled in by templates. AvroIO has not been modified to accept ValueProvider arguments, so it does not yet support runtime parameters.

I am not sure where you are getting the serializable exception or how you are passing a RuntimeValueProvider to AvroIO given the above. To make this work, AvroIO would need to change to support appropriate parameterization -- likely taking a schema string -- at which point you should be able to pass it a RuntimeValueProvider of the Schema.