问:
MAMP: How to upgrade PEAR
When trying to upgrade MAMP pear the following error is raised:

```<code>Notice: unserialize(): Error at offset 276 of 1133 bytes in Config.php on line 1050
ERROR: The default config file is not a valid config file or is corrupted.
</code>```

Some suggestions how to fix this?

Steps to reproduce:

Installed MAMP (version 2.0.5)

cd /Applications/MAMP/bin/php/php5.3.6/bin

sudo ./pear upgrade pear

above mentioned error is thrown

Update (1):

Based on answer 8375349/420953 I tried 2 possibilities to fix this

A: delete pear.conf

rm /Applications/MAMP/bin/php/php5.3.6/conf/pear.conf

B: edit pear.conf

change "php_dir";s:44 to "php_dir";s:43

both resulted in error:

```<code>Could not get contents of package "/Applications/MAMP/bin/php/php5.3.6/bin/pear". Invalid tgz file.
upgrade failed
</code>```

Update (2):

running

which pear

results in output

/usr/local/bin/pear

With this, I noticed that I was using the "local" version of PEAR.

I removed it with

sudo pear uninstall pear

and then tried to upgrade the MAMP version of PEAR with

/Applications/MAMP/bin/php/php5.3.6/bin/pear upgrade pear

this results in error

```<code>Cannot install, php_dir for channel "pear.php.net" is not writeable by the current user
</code>```

upgrading with

sudo /Applications/MAMP/bin/php/php5.3.6/bin/pear upgrade pear

installs it locally (again).

running

which pear

outputs

/usr/local/bin/pear

this brings me back to the starting point of Update (2). Seems that I am not able to upgrade PEAR under a MAMP directory.

Update (3):

I posted question

MAMP PEAR configuration is pointing to local directories

because my assumption is that the root of this issue is related to MAMP PEAR config.

Update (4):

I did not install a local PEAR version and this was causing quite some issues. After also installing a local version (and not only the MAMP) version, upgarding the MAMP version worked perfectly.

答:
Just chipping in with a late response for others finding this answer. My PEAR config had several issues and not just the php_dir config setting.

I had to go over all of my settings to verify that the count was correct. When all errors where fixed my PEAR was working fine again.

Seeing this message in the terminal:

```<code>Notice: unserialize(): Error at offset 276 of 1133 bytes in Config.php on line 1050
ERROR: The default config file is not a valid config file or is corrupted.
</code>```

Go to your PEAR Config file (probably located here /MAMP/bin/php/php7.0.10/conf/pear.conf)

Go to the 276th character in that file and verify that the string length matches the s43 that's defined before the string.

Run a PEAR command again (e.g. pear version)

If you have more errors located at e.g. 317th character you count that string and write the length in the s:XX before the string.

Just for clarifying for others finding this issue. The PEAR Config file is a serialized object that is unserialized when running commands.

A serialized object looks like s:5:"value" with the s:5 defining the length the string.

Title: MAMP: How to upgrade PEAR

Body:
When trying to upgrade MAMP pear the following error is raised:

Notice: unserialize(): Error at offset 276 of 1133 bytes in Config.php on line 1050
ERROR: The default config file is not a valid config file or is corrupted.

Some suggestions how to fix this?

Steps to reproduce:

Installed MAMP (version 2.0.5)

cd /Applications/MAMP/bin/php/php5.3.6/bin

sudo ./pear upgrade pear

above mentioned error is thrown

Update (1):

Based on answer 8375349/420953 I tried 2 possibilities to fix this

A: delete pear.conf

rm /Applications/MAMP/bin/php/php5.3.6/conf/pear.conf

B: edit pear.conf

change "php_dir";s:44 to "php_dir";s:43

both resulted in error:

Could not get contents of package "/Applications/MAMP/bin/php/php5.3.6/bin/pear". Invalid tgz file.
upgrade failed

Update (2):

running

which pear

results in output

/usr/local/bin/pear

With this, I noticed that I was using the "local" version of PEAR.

I removed it with

sudo pear uninstall pear

and then tried to upgrade the MAMP version of PEAR with

/Applications/MAMP/bin/php/php5.3.6/bin/pear upgrade pear

this results in error

Cannot install, php_dir for channel "pear.php.net" is not writeable by the current user

upgrading with

sudo /Applications/MAMP/bin/php/php5.3.6/bin/pear upgrade pear

installs it locally (again).

running

which pear

outputs

/usr/local/bin/pear

this brings me back to the starting point of Update (2). Seems that I am not able to upgrade PEAR under a MAMP directory.

Update (3):

I posted question

MAMP PEAR configuration is pointing to local directories

because my assumption is that the root of this issue is related to MAMP PEAR config.

Update (4):

I did not install a local PEAR version and this was causing quite some issues. After also installing a local version (and not only the MAMP) version, upgarding the MAMP version worked perfectly.

Body:
Just chipping in with a late response for others finding this answer. My PEAR config had several issues and not just the php_dir config setting.

I had to go over all of my settings to verify that the count was correct. When all errors where fixed my PEAR was working fine again.

Seeing this message in the terminal:

Notice: unserialize(): Error at offset 276 of 1133 bytes in Config.php on line 1050
ERROR: The default config file is not a valid config file or is corrupted.

Go to your PEAR Config file (probably located here /MAMP/bin/php/php7.0.10/conf/pear.conf)

Go to the 276th character in that file and verify that the string length matches the s43 that's defined before the string.

Run a PEAR command again (e.g. pear version)

If you have more errors located at e.g. 317th character you count that string and write the length in the s:XX before the string.

Just for clarifying for others finding this issue. The PEAR Config file is a serialized object that is unserialized when running commands.

A serialized object looks like s:5:"value" with the s:5 defining the length the string.


来源: stackexchange

问:
Touch Gesture for the entire screen
I am new to writing programs for windows. Apologies, if my question is a very easy or basic one.

I am trying to write a code which uses the touch gesture api's provided by Microsoft for windows 10 using C++. I am using a touch screen monitor too.

I was able to create a window and a handle to that to use the touch gesture as mentioned in the code below:

```<code>LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

LRESULT CALLBACK DecodeGesture(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    // Register the window class.

    const wchar_t CLASS_NAME[] = L"Sample Window Class";

    WNDCLASS wc = {};

    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    // Create the window.

    HWND hwnd = CreateWindowEx(
        0,                              // Optional window styles.
        CLASS_NAME,                     // Window class
        L"Learn to Program Windows",    // Window text
        WS_OVERLAPPEDWINDOW,            // Window style

                                        // Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL,       // Parent window
        NULL,       // Menu
        hInstance,  // Instance handle
        NULL        // Additional application data
    );

    if (hwnd == NULL)
    {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    // Run the message loop.

    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{

    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);

        FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));

        EndPaint(hwnd, &ps);
    }
    return 0;

    case WM_GESTURE:
        // Insert handler code here to interpret the gesture.
        return DecodeGesture(hwnd, uMsg, wParam, lParam);

    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

LRESULT DecodeGesture(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    // Create a structure to populate and retrieve the extra message info.

    GESTUREINFO gi;

    ZeroMemory(&gi, sizeof(GESTUREINFO));

    gi.cbSize = sizeof(GESTUREINFO);

    BOOL bResult = GetGestureInfo((HGESTUREINFO)lParam, &gi);
    BOOL bHandled = FALSE;

    if (bResult) {
        // now interpret the gesture
        switch (gi.dwID) {
        case GID_ZOOM:
            // Code for zooming goes here
            bHandled = TRUE;
            break;
        case GID_PAN:
            // Code for panning goes here
            bHandled = TRUE;
            break;
        case GID_ROTATE:
            // Code for rotation goes here
            bHandled = TRUE;
            break;
        case GID_TWOFINGERTAP:
        {
            // Code for two-finger tap goes here
            // Get all instances of the onscreen keyboard running on the local computer.
            // This will return an empty array if onscreen keyboard isn't running.
            array<Process^>^localByName = Process::GetProcessesByName("osk");
            if (localByName->Length < 1)
            {
                system("start powershell.exe Set-ExecutionPolicy RemoteSigned \n");
                system("start powershell.exe osk");
                //system("pause");
            }
            bHandled = TRUE;
            break;
        }
        case GID_PRESSANDTAP:
            // Code for roll over goes here
            bHandled = TRUE;
            break;
        default:
            // A gesture was not recognized
            break;
        }
    }
    else {
        DWORD dwErr = GetLastError();
        if (dwErr > 0) {
            //MessageBoxW(hWnd, L"Error!", L"Could not retrieve a GESTUREINFO structure.", MB_OK);
        }
    }
    if (bHandled) {
        return 0;
    }
    else {
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

//----------------------------------------------------------------------//
</code>```

Clearly, the above mentioned code points to a handle, that is a window and not the entire screen.

How can I modify this code to create a handle that will point to the entire screen and not just the area inside that window?

答:
The above approach is incorrect and the same could be achieved using the concept of global hooks.

You can hook onto a certain kind of touch gesture and populate the onscreen keyboard accordingly

ContentLicense: CC BY-SA 3.0

Title: Touch Gesture for the entire screen

Body:
I am new to writing programs for windows. Apologies, if my question is a very easy or basic one.

I am trying to write a code which uses the touch gesture api's provided by Microsoft for windows 10 using C++. I am using a touch screen monitor too.

I was able to create a window and a handle to that to use the touch gesture as mentioned in the code below:

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

LRESULT CALLBACK DecodeGesture(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    // Register the window class.

    const wchar_t CLASS_NAME[] = L"Sample Window Class";

    WNDCLASS wc = {};

    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    // Create the window.

    HWND hwnd = CreateWindowEx(
        0,                              // Optional window styles.
        CLASS_NAME,                     // Window class
        L"Learn to Program Windows",    // Window text
        WS_OVERLAPPEDWINDOW,            // Window style

                                        // Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL,       // Parent window
        NULL,       // Menu
        hInstance,  // Instance handle
        NULL        // Additional application data
    );

    if (hwnd == NULL)
    {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    // Run the message loop.

    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{

    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);

        FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));

        EndPaint(hwnd, &ps);
    }
    return 0;

    case WM_GESTURE:
        // Insert handler code here to interpret the gesture.
        return DecodeGesture(hwnd, uMsg, wParam, lParam);

    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

LRESULT DecodeGesture(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    // Create a structure to populate and retrieve the extra message info.

    GESTUREINFO gi;

    ZeroMemory(&gi, sizeof(GESTUREINFO));

    gi.cbSize = sizeof(GESTUREINFO);

    BOOL bResult = GetGestureInfo((HGESTUREINFO)lParam, &gi);
    BOOL bHandled = FALSE;

    if (bResult) {
        // now interpret the gesture
        switch (gi.dwID) {
        case GID_ZOOM:
            // Code for zooming goes here
            bHandled = TRUE;
            break;
        case GID_PAN:
            // Code for panning goes here
            bHandled = TRUE;
            break;
        case GID_ROTATE:
            // Code for rotation goes here
            bHandled = TRUE;
            break;
        case GID_TWOFINGERTAP:
        {
            // Code for two-finger tap goes here
            // Get all instances of the onscreen keyboard running on the local computer.
            // This will return an empty array if onscreen keyboard isn't running.
            array<Process^>^localByName = Process::GetProcessesByName("osk");
            if (localByName->Length < 1)
            {
                system("start powershell.exe Set-ExecutionPolicy RemoteSigned \n");
                system("start powershell.exe osk");
                //system("pause");
            }
            bHandled = TRUE;
            break;
        }
        case GID_PRESSANDTAP:
            // Code for roll over goes here
            bHandled = TRUE;
            break;
        default:
            // A gesture was not recognized
            break;
        }
    }
    else {
        DWORD dwErr = GetLastError();
        if (dwErr > 0) {
            //MessageBoxW(hWnd, L"Error!", L"Could not retrieve a GESTUREINFO structure.", MB_OK);
        }
    }
    if (bHandled) {
        return 0;
    }
    else {
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

//----------------------------------------------------------------------//

Clearly, the above mentioned code points to a handle, that is a window and not the entire screen.

How can I modify this code to create a handle that will point to the entire screen and not just the area inside that window?


问:
Plotly notebook mode with google colaboratory
I am am trying out colaboratory with plotly notebook mode - I open a new notebook, copy and paste the following simple example from plotly's documentation, but don't see an output. There is a large blank in the output space where the plot whould normally be.

This works fine in my local notebook (which is a newer version of plotly, but per their docs offline mode should work with the google colab version)
Any ideas?

```<code>import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.init_notebook_mode(connected=True)

plotly.offline.iplot({
    "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": Layout(title="hello world")
})
</code>```

答:
configure_plotly_browser_state() can be executed before running every cell by using IPython's pre_run_cell hook:

```<code>import IPython

IPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)
</code>```

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

Body:
I am am trying out colaboratory with plotly notebook mode - I open a new notebook, copy and paste the following simple example from plotly's documentation, but don't see an output. There is a large blank in the output space where the plot whould normally be.

This works fine in my local notebook (which is a newer version of plotly, but per their docs offline mode should work with the google colab version)
Any ideas?

import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.init_notebook_mode(connected=True)

plotly.offline.iplot({
    "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": Layout(title="hello world")
})

Body:
configure_plotly_browser_state() can be executed before running every cell by using IPython's pre_run_cell hook:

import IPython

IPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)

ContentLicense: CC BY-SA 4.0


问:
Syntax error on token "Invalid Character", delete this token
I am not sure why is it giving this error. Braces seem to be right. Another thing is that the same program works in Windows-eclipse but not in eclipse for Mac. What could be the reason?</p>

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

public class Debug
{
    private int something = 0;
    private Vector list = new Vector();

    public void firstMethod()
    {
        thirdMethod(something);
        something = something + 1;
    }
    public void secondMethod()
    {
        thirdMethod(something);
        something = something + 2;
    }
    public void thirdMethod(int value)
    {
        something = something + value;
    }

    public static void main(String[] args)
    {
        Debug debug = new Debug();
        debug.firstMethod();
        debug.secondMethod();
    }
}
</code>```

答: There are probably hidden characters in the line. If you move your cursor through the characters and your cursor doesn't move in one character, that means there is an invalid character in the line. Delete those and it should work. Also try copying and pasting the line to an hex editor and you will see the invalid characters in it.</p>

Body:
I am not sure why is it giving this error. Braces seem to be right. Another thing is that the same program works in Windows-eclipse but not in eclipse for Mac. What could be the reason?

import java.util.Vector;

public class Debug
{
    private int something = 0;
    private Vector list = new Vector();

    public void firstMethod()
    {
        thirdMethod(something);
        something = something + 1;
    }
    public void secondMethod()
    {
        thirdMethod(something);
        something = something + 2;
    }
    public void thirdMethod(int value)
    {
        something = something + value;
    }

    public static void main(String[] args)
    {
        Debug debug = new Debug();
        debug.firstMethod();
        debug.secondMethod();
    }
}


问:
Django doesn't load second page
I have just started Django, and I'm facing some difficulty.
When the first time I'm loading "localhost:8000/first_app" it is successfully loading index(), but on clicking on "About" link, url is changing to "localhost:8000/first_app/about/", but it is still loading "index()" and not "about()". Don't know what I'm missing.

Here's my project's URL:

```<code>from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^first_app/', include('first_app.urls')),
)
</code>```

App's URL:

```<code>from django.conf.urls import patterns, url
from first_app import views

urlpatterns = patterns('',
        url(r'^$', views.index, name='index'),
        url(r'^about/', views.index, name='about'),
)
</code>```

And views.py:

```<code>from django.http import HttpResponse

def index(request):
    return HttpResponse("Rango says: Hello world! <br/> <a href='/first_app/about'>About</a>")

def about(request):
    return HttpResponse("This is the ABOUT page! <br /> <a href='/first_app/'>Index</a>")
</code>```

I'm using Django 1.7 and python 2.7.
Thanks.

答:
You need to define your URLs like this;

```<code>urlpatterns = patterns('',
    url(r'^about/$', views.about, name='about'),
    url(r'^/$', views.index, name='index'),
)
</code>```

Basically '^$' is the beginning & end of the match. The ^ is the start of the pattern & the $ is the end of the pattern so keep that in mind when defining your URLs. It's good practice to use $ to end your urls to avoid views being rendered regardless of what you add to the URL after what you match in your pattern.

Title: Django doesn't load second page

Body:
I have just started Django, and I'm facing some difficulty.
When the first time I'm loading "localhost:8000/first_app" it is successfully loading index(), but on clicking on "About" link, url is changing to "localhost:8000/first_app/about/", but it is still loading "index()" and not "about()". Don't know what I'm missing.

Here's my project's URL:

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^first_app/', include('first_app.urls')),
)

App's URL:

from django.conf.urls import patterns, url
from first_app import views

urlpatterns = patterns('',
        url(r'^$', views.index, name='index'),
        url(r'^about/', views.index, name='about'),
)

And views.py:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Rango says: Hello world!
 About")

def about(request):
    return HttpResponse("This is the ABOUT page!
 Index")

I'm using Django 1.7 and python 2.7.
Thanks.

Body:
You need to define your URLs like this;

urlpatterns = patterns('',
    url(r'^about/$', views.about, name='about'),
    url(r'^/$', views.index, name='index'),
)

Basically '^$' is the beginning & end of the match. The ^ is the start of the pattern & the $ is the end of the pattern so keep that in mind when defining your URLs. It's good practice to use $ to end your urls to avoid views being rendered regardless of what you add to the URL after what you match in your pattern.


问:
XSLT escaping >
i have a problem like a lot of people with escaping the > sign.
the data xml file looks like

```<code><XML>
<check><![CDATA[value > 60]]></check>
</Xml>
</code>```

with xslt i would like to create a c# function. the checks are items that gone be used in a if statement.

```<code>public void product(int value)
{
if( <xsl:value-of disable-output-escaping="yes" select="actie" />)

this should be: if( value > 60 ) but returns if( value > 60 )

}
</code>```

<xsl:value-of cdata-section-elements="check"/> can't be used becouse i can't use this data in a template.

disable-output-escaping just returns >

hope one of u have a working solution.

thanking you in
advance

答:
Thanks vor the help but it wasn't the solution, had some help from a friend who told me i was doing it wrong on calling the xslt file
What i dit was:

```<code>XPathDocument myXPathDoc = new XPathDocument("../../file.xml");
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load("../../file.xslt");
XmlTextWriter myWriter = new XmlTextWriter("../../file.txt", null);
myXslTrans.Transform(myXPathDoc, null, myWriter);
</code>```

i changed it to:

```<code>XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load("../../file.xslt");
myXslTrans.Transform("../../file.xml", "../../file.cs");
</code>```

now it worked

ContentLicense: CC BY-SA 2.5

Title: XSLT escaping >

Body:
i have a problem like a lot of people with escaping the > sign.
the data xml file looks like

<XML>
<check><![CDATA[value > 60]]></check>
</Xml>

with xslt i would like to create a c# function. the checks are items that gone be used in a if statement.

public void product(int value)
{
if( <xsl:value-of disable-output-escaping="yes" select="actie" />)

this should be: if( value > 60 ) but returns if( value > 60 )

}

<xsl:value-of cdata-section-elements="check"/> can't be used becouse i can't use this data in a template.

disable-output-escaping just returns >

hope one of u have a working solution.

thanking you in
advance

Body:
Thanks vor the help but it wasn't the solution, had some help from a friend who told me i was doing it wrong on calling the xslt file
What i dit was:

XPathDocument myXPathDoc = new XPathDocument("../../file.xml");
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load("../../file.xslt");
XmlTextWriter myWriter = new XmlTextWriter("../../file.txt", null);
myXslTrans.Transform(myXPathDoc, null, myWriter);

i changed it to:

XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load("../../file.xslt");
myXslTrans.Transform("../../file.xml", "../../file.cs");

now it worked


问:
How to import a Specific Contact's phone number?
I'm trying to Read Phone number of a Contact Selected using Contact Picker.
The Display Name works fine, But Phone number doesn't.
Code:

```<code>//calling Contact Picker
public void CPick(View v){
        Intent intent=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);
    }
    @Override
//Contact Picker here:
    protected void onActivityResult(int reqCode, int resultCode, Intent data){
        super.onActivityResult(reqCode,resultCode, data);

        if (reqCode==PICK_CONTACT){
            if(resultCode==AppCompatActivity.RESULT_OK){
                Uri contatctData=data.getData();
                Cursor c=getContentResolver().query(contatctData,null,null,null,null);
                if (c.moveToFirst()){
                    //String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Above line works Fine

                    String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Above line gives error on runtime "invalid column"
                    Toast.makeText(this,"U have picked:"+name,Toast.LENGTH_SHORT).show();

                }
            }

        }
    }
</code>```

Anyhelp will be very Appreciated because I couldn't find relevant answer anywhere.

答:
If you want to allow the user to pick a phone-number, the best option is to use a PHONE-PICKER not a CONTACT-PICKER:

```<code>Intent intent = new Intent(Intent.ACTION_PICK, CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_PHONE);

...

protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    if (requestCode == PICK_PHONE && resultCode == RESULT_OK){
        Uri phoneUri = intent.getData();
        Cursor cur = getContentResolver().query(phoneUri, new String[] { Phone.DISPLAY_NAME, Phone.NUMBER }, null, null, null);
        if (cur != null && cur.moveToFirst()){
            String name = cur.getString(0);
            String number = cur.getString(1);
            Log.d("PHONE-PICKER", "User picker: " + name + " - " + number);
            cur.close();
        }
    }
}
</code>```

Body:
I'm trying to Read Phone number of a Contact Selected using Contact Picker.
The Display Name works fine, But Phone number doesn't.
Code:

//calling Contact Picker
public void CPick(View v){
        Intent intent=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);
    }
    @Override
//Contact Picker here:
    protected void onActivityResult(int reqCode, int resultCode, Intent data){
        super.onActivityResult(reqCode,resultCode, data);

        if (reqCode==PICK_CONTACT){
            if(resultCode==AppCompatActivity.RESULT_OK){
                Uri contatctData=data.getData();
                Cursor c=getContentResolver().query(contatctData,null,null,null,null);
                if (c.moveToFirst()){
                    //String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Above line works Fine

                    String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Above line gives error on runtime "invalid column"
                    Toast.makeText(this,"U have picked:"+name,Toast.LENGTH_SHORT).show();

                }
            }

        }
    }

Anyhelp will be very Appreciated because I couldn't find relevant answer anywhere.

Body:
If you want to allow the user to pick a phone-number, the best option is to use a PHONE-PICKER not a CONTACT-PICKER:

Intent intent = new Intent(Intent.ACTION_PICK, CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_PHONE);

...

protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    if (requestCode == PICK_PHONE && resultCode == RESULT_OK){
        Uri phoneUri = intent.getData();
        Cursor cur = getContentResolver().query(phoneUri, new String[] { Phone.DISPLAY_NAME, Phone.NUMBER }, null, null, null);
        if (cur != null && cur.moveToFirst()){
            String name = cur.getString(0);
            String number = cur.getString(1);
            Log.d("PHONE-PICKER", "User picker: " + name + " - " + number);
            cur.close();
        }
    }
}


问:
Generating Images from maps
How do you capture an image of a user generated map, like one created using Leaflet.js?

Here is my example:

I have a website that generates a map.

I want to save an image of that map

e.g. when the user shares their profile, the preview image is of their map.

I know facebook, Strava, and most other services show images of a user map in their news feeds instead of showing interactive maps.

The problem

The map is generated client side, so grabbing an image of the map serverside isn't possible

Possible Solution

Once a map is generated, use PhantomJS to capture a screenshot of the map, and crop out the rest of the website.

Question

Since this is such a common thing to do, is anyone aware of a better or more standard way of grabbing these screenshots? I've seen things like the mapbox static API, but that doesn't capture the custom pins and line features on my maps.

I'm using rails for the back end.

答:
You can make your map to be able to read the url params and set its state from it. When the user changes something on the map, the map's state is saved as url parameters and then send it/store it on the server for PhantomJS to generate it.
E.g. </p>

```<code>&coords=123.123,10.123,54.54,45.11&zoom_level=5&....
</code>```

Title: Generating Images from maps

Body:
You can make your map to be able to read the url params and set its state from it. When the user changes something on the map, the map's state is saved as url parameters and then send it/store it on the server for PhantomJS to generate it.
E.g.

&coords=123.123,10.123,54.54,45.11&zoom_level=5&....


问:
Cannot read struct from binary file
I am trying to read the contents of a binary file into a struct, but each time I print out the contents of my struct, I get a pretty strange output. Below is the struct I am trying to set:

```<code>struct student {
    char name[32];
    unsigned int age;
    SEX sex;
    float gpa;
    struct course *courses;
    struct student *next;
}
</code>```

With the course struct defined as:

```<code>struct course {
    char grade;
    unsigned int number;
    struct course *next;
}
</code>```

And SEX defined as:

```<code>typedef enum _SEX {MALE = 'M', FEMALE = 'F', OTHER = 'O'} SEX;
</code>```

Right now, my function is as follows:

```<code>void read_bin(char *filename){
    FILE *file;
    struct student myStudent;
    file = fopen(filename, "rb");
    if(file == NULL){
        printf("Unable to open file!");
        return;
    }
    fread(&myStudent, sizeof(struct student), 1, file);
    printf("\nName: %s, Age: %d", myStudent.name, myStudent.age);
    fclose(file);
}
</code>```

But I keep on getting this strange output:

Age: 0

With name not even showing up and age set to an incorrect number. I thought this might be due to padding, so I tried using

```<code>fread(&myStudent.name, sizeof myStudent.name, 1, file);
fread(&myStudent.age, sizeof myStudent.age, 1, file);
</code>```

So that it reads each individual element and pads as needed. However, I get the same output. When I ran hexdump to see what exactly I was dealing with, this is what came out:

```<code>f0 0d 03 00 00 00 46 72  65 64 00 00 00 00 00 00  |......Fred......|
00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00 00 00 00 00 00 1d 00  00 00 4d 00 00 00 cd cc  |..........M.....|
4c 40 01 00 00 00 44 02  00 00 41 4a 6f 65 00 00  |L@....D...AJoe..|
00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00 00 00 00 00 00 00 00  00 00 00 16 00 00 00 4d  |...............M|
00 00 00 33 33 73 40 03  00 00 00 6e 00 00 00 42  |...33s@....n...B|
dc 00 00 00 41 54 01 00  00 41 53 61 72 61 68 00  |....AT...ASarah.|
00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00 00 00 00 00 00 00 00  00 00 16 00 00 00 46 00  |..............F.|
00 00 00 00 40 40 03 00  00 00 78 00 00 00 42 dc  |....@@....x...B.|
00 00 00 41 4a 01 00 00  43                       |...AJ...C|
</code>```

Any help would be greatly appreciated -- I've been stuck on this function for awhile.

答:
Depending on the filetype the first few bytes can be a fileheader, here information can be stored like version numbers, length of the data etc.

As for the pointers, that won't work like others pointed out since pointers are adresses, not actual relevant data.

You want to fseek to sizeof(fileheader), before you start reading the file.

Also be wary that structs are padded in C and that the order in which you declared the elements in the struct might not be the order the compiler decided for it.

Title: Cannot read struct from binary file

Body:
I am trying to read the contents of a binary file into a struct, but each time I print out the contents of my struct, I get a pretty strange output. Below is the struct I am trying to set:

struct student {
    char name[32];
    unsigned int age;
    SEX sex;
    float gpa;
    struct course *courses;
    struct student *next;
}

With the course struct defined as:

struct course {
    char grade;
    unsigned int number;
    struct course *next;
}

And SEX defined as:

typedef enum _SEX {MALE = 'M', FEMALE = 'F', OTHER = 'O'} SEX;

Right now, my function is as follows:

void read_bin(char *filename){
    FILE *file;
    struct student myStudent;
    file = fopen(filename, "rb");
    if(file == NULL){
        printf("Unable to open file!");
        return;
    }
    fread(&myStudent, sizeof(struct student), 1, file);
    printf("\nName: %s, Age: %d", myStudent.name, myStudent.age);
    fclose(file);
}

But I keep on getting this strange output:

Age: 0

With name not even showing up and age set to an incorrect number. I thought this might be due to padding, so I tried using

fread(&myStudent.name, sizeof myStudent.name, 1, file);
fread(&myStudent.age, sizeof myStudent.age, 1, file);

So that it reads each individual element and pads as needed. However, I get the same output. When I ran hexdump to see what exactly I was dealing with, this is what came out:

f0 0d 03 00 00 00 46 72  65 64 00 00 00 00 00 00  |......Fred......|
00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00 00 00 00 00 00 1d 00  00 00 4d 00 00 00 cd cc  |..........M.....|
4c 40 01 00 00 00 44 02  00 00 41 4a 6f 65 00 00  |L@....D...AJoe..|
00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00 00 00 00 00 00 00 00  00 00 00 16 00 00 00 4d  |...............M|
00 00 00 33 33 73 40 03  00 00 00 6e 00 00 00 42  |...33s@....n...B|
dc 00 00 00 41 54 01 00  00 41 53 61 72 61 68 00  |....AT...ASarah.|
00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00 00 00 00 00 00 00 00  00 00 16 00 00 00 46 00  |..............F.|
00 00 00 00 40 40 03 00  00 00 78 00 00 00 42 dc  |....@@....x...B.|
00 00 00 41 4a 01 00 00  43                       |...AJ...C|

Any help would be greatly appreciated -- I've been stuck on this function for awhile.


问:
Using an opaque pointer to a non struct type
In my C programming, I use opaque-pointers to struct as a way to enforce abstraction and encapsulation of my code, in that manner :

interface_header.h:

```<code> typedef struct s_mytype t_mytype;
</code>```

defs_header.h:

```<code>struct s_mytype
{
/* Actual definition of the struct */
};
</code>```

My problem I want to use a simple type as t_mytype (char for example), but not inform the interface about that. I can't just use typedef char t_mytype, since that would expose the the internals of the type.
I could just use void pointers, but at the cost of type-checking, and I'd rather avoid that.

Doing two typedef wont work either, since that throw an typedef redefinition with different types from the compiler.

I am also considering doing a struct with only one member, which will be my simple type, but would that be an overkill ?

Thanks for your answers.

答:
You have to make a decision. With code like this:

```<code>typedef char myHandle;

frobnicate(myHandle *obj);
</code>```

you already document the intent that client code should only use pointers to myHandle and never assume anything about the underlying type, so you should be able to change the typedef later -- unless there's "sloppy" client code making assumptions it shouldn't.

If you want to completely hide what's behind myHandle, a struct is your only option in C:

```<code>typedef struct myHandle myHandle;

frobnicate(myHandle *obj);
</code>```

and only in a private header or implementation file, you will put

```<code>struct myHandle
{
    char val;
};
</code>```

The first option is simpler because inside the implementation of frobnicate(), you can access your value simply using *obj while the second option requires to write obj->val. What you gain with the second version is that you force client code to be written correctly.

In terms of the resulting executable, both versions are equivalent.

Body:
In my C programming, I use opaque-pointers to struct as a way to enforce abstraction and encapsulation of my code, in that manner :

interface_header.h:

 typedef struct s_mytype t_mytype;

defs_header.h:

struct s_mytype
{
/* Actual definition of the struct */
};

My problem I want to use a simple type as t_mytype (char for example), but not inform the interface about that. I can't just use typedef char t_mytype, since that would expose the the internals of the type.
I could just use void pointers, but at the cost of type-checking, and I'd rather avoid that.

Doing two typedef wont work either, since that throw an typedef redefinition with different types from the compiler.

I am also considering doing a struct with only one member, which will be my simple type, but would that be an overkill ?

Thanks for your answers.

Body:
You have to make a decision. With code like this:

typedef char myHandle;

frobnicate(myHandle *obj);

you already document the intent that client code should only use pointers to myHandle and never assume anything about the underlying type, so you should be able to change the typedef later -- unless there's "sloppy" client code making assumptions it shouldn't.

If you want to completely hide what's behind myHandle, a struct is your only option in C:

typedef struct myHandle myHandle;

frobnicate(myHandle *obj);

and only in a private header or implementation file, you will put

struct myHandle
{
    char val;
};

The first option is simpler because inside the implementation of frobnicate(), you can access your value simply using *obj while the second option requires to write obj->val. What you gain with the second version is that you force client code to be written correctly.

In terms of the resulting executable, both versions are equivalent.


问:
How can I have the same javascript variable on the same page?
Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.

The problem right now is that I can't include the same variables names on the page.

For instance:

```<code><script type="text/javascript">
  var ttp_number = "1Z8E26R80281495993"; // Tracking number

  var ttp_key="123456";
  (function(){
    document.write('<div id="ttp"></div>');
    s=document.createElement('script');
    s.type="text/javascript";
    s.src="http://c.trackthepack.com/j/e?" + Math.random();
    setTimeout("document.getElementById('ttp').appendChild(s);",1);
  })()
</script>
</code>```

Then if they wanted to be able to embed that again, I'd have to change all variable names:

```<code><script type="text/javascript">
  var ttp_number_001 = "446888240962"; // Tracking number

  var ttp_key_001="123456";
  (function(){
    document.write('<div id="ttp_001"></div>');
    s_001=document.createElement('script');
    s_001.type="text/javascript";
    s_001.src="http://c.trackthepack.com/j/e?" + Math.random();
    setTimeout("document.getElementById('ttp_001').appendChild(s_001);",1);
  })()
</script>
</code>```

I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.

Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.

So, the ultimate question here...how do I fix that?

答: Maybe store the ttp_key and ttp_number's in arrays instead?</p>

Body:
Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.

The problem right now is that I can't include the same variables names on the page.

For instance:

Then if they wanted to be able to embed that again, I'd have to change all variable names:

I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.

Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.

So, the ultimate question here...how do I fix that?


问:
Importing Excel to internal table with same layout
I know of function module ALSM_EXCEL_TO_INTERNAL_TABLE. This FM creates an internal table with three columns (row, column, value). But I want to create an internal table which has the same layout as my Excel sheet. How can I achieve this? </p>

答:
You can use class cl_mass_spreadsheet_service if you are uploading the excel in foreground. See my example code below:</p>

```<code>DATA:
    lv_file      TYPE if_mass_spreadsheet_types=>file_name,
    lt_result    TYPE STANDARD TABLE OF zsd_salesorder_create. "your result table

lv_file = 'C:\some_file.xlsx'.

cl_mass_spreadsheet_service=>fill_table(
    EXPORTING
        iv_file                     = lv_file   "full path+name of file. See method navigate_to_file below
        iv_from_file                = abap_true "use to upload from excel/CSV
        iv_from_clipboard           = abap_false "use to copy directly from clipbiard
        iv_tabname                  = 'Order_Create' "can be whatever
    CHANGING
        ct_table                    = lt_result "if ct_table have the same column names as the excel file, the order of the columns does not matter
).
</code>```

Body:
You can use class cl_mass_spreadsheet_service if you are uploading the excel in foreground. See my example code below:

DATA:
    lv_file      TYPE if_mass_spreadsheet_types=>file_name,
    lt_result    TYPE STANDARD TABLE OF zsd_salesorder_create. "your result table

lv_file = 'C:\some_file.xlsx'.

cl_mass_spreadsheet_service=>fill_table(
    EXPORTING
        iv_file                     = lv_file   "full path+name of file. See method navigate_to_file below
        iv_from_file                = abap_true "use to upload from excel/CSV
        iv_from_clipboard           = abap_false "use to copy directly from clipbiard
        iv_tabname                  = 'Order_Create' "can be whatever
    CHANGING
        ct_table                    = lt_result "if ct_table have the same column names as the excel file, the order of the columns does not matter
).


问:
Can I download crash reports from Crashlytics without uploading .dSYM?
It was said in docs, that

All .app dSYMs are marked as required. When Crashlytics fails to receive one of
  these dSYMs we are unable to properly symbolicate crashes. Once a
  required dSYM is uploaded, Crashlytics will reprocess all impacted
  crashes for the last 7 days and you will see new issues appears in the
  crash dashboard.

So Fabric has reports even without dSYM. My question is: Can I download reports and symbolicate them manually?

答: Mike from Fabric here. We store the crashes for 7 days, but don't have a mechanism to deliver them in an unprocessed format. </p>


问:
C# Decoding long Base64 Strings
I am using Unity Free + NodeJS to code a small project with my mates.

NodeJs for the Server, and Unity for the Clients.

If you entered valid login data, the Server will return a jwt using njwt, which can be decoded using various online tools, and with c#.

But, this Line: byte[] _dec = Convert.FromBase64String(part); returns no error, but also prevents execution of more code. And I don't know why.

Here are more samples to understand what's going on.

LoginMenu.cs

```<code>ws.OnMessage += (sender, e) => {
    JObject res = JObject.Parse(e.Data);

    switch ((string)res["type"])
    {
        // If we get a token from the server
        // login was successful
        case "jwt":
            Debug.Log("Res was JWT");
            UserAccountManager.instance.LogIn((string)res["jwt"]);
            Debug.LogWarning("FINISHED");
            break;
        // Only 1 case for now
    }
};
</code>```

UserAccountManager.cs

```<code>public static UserAccountManager instance;
void Awake() {
    if (instance != null)
    {
        Destroy(gameObject);
        return;
    }

    instance = this;
    DontDestroyOnLoad(this);
}

void Set_Jwt(string _jwt)
{
    Jwt = _jwt;
    Jwt_data = decode_jwt(_jwt);

    playerUsername = (string)Jwt_data["username"];
    Debug.Log("Jwt set");
    Debug.LogWarning(playerUsername);
}

private JObject decode_jwt(string _jwt)
{
    string[] splitted = _jwt.Split('.');
    var part = splitted[1];
    // Code only runs until here
    byte[] _dec = Convert.FromBase64String(part);
    string decodedjwt = Encoding.UTF8.GetString(_dec);

    return JObject.Parse(decodedjwt);
}

public void LogIn(string _jwt) {
    Debug.LogWarning("LogIn called");
    Set_Jwt(_jwt);

    isLoggedIn = true;
    Debug.Log("Trying to load " + loggedInSceneName);
    SceneManager.LoadScene(loggedInSceneName);
}
</code>```

EDIT:

I have written almost the same code in a new C# ConsoleApplication, and it throws a System.FormatException: "Invalid Length for base64 Char array"

```<code>static void Main(string[] args)
    {
        string jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJncy5hd2Vzb21lc3R1ZmYuYXQiLCJpYXQiOjE1MTA1OTkyNzQsImV4cCI6MTUxMDYwMjg3MywidWlkIjoiMTY1ZWMxZjAtYzhhNC0xMWU3LTk2ZWQtYzNjNGQ4NTRmM2I4IiwiYXV0aCI6dHJ1ZSwidXNlcm5hbWUiOiJnYWJlbml6aGVyZSIsImlwIjoiMTk0LjIwOC4xMzguMTI4IiwianRpIjoiNjg4NWM0N2YtMjk3NS00N2MyLTgzYTktN2RmMjhmODE3NDljIn0.tRhx3mUbGBxoGFFr0t6dnPMrdlUT4UKJKLBY_9IiJdBePWp1S10Z91875z6OFK92ymACRR_wO3_1_h6fKXAPTQ";
        string[] splitted = jwt.Split('.');
        var part = splitted[1];

        byte[] arr = Convert.FromBase64String(part);
        string res = Encoding.UTF8.GetString(arr);
        Console.WriteLine(res);

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

What should I do now?

答: I finally fixed it. It was a very tiny mistake. The whole token was correct b64, but when I split out the middle part it was dividable by 4. I added a = and then it decoded fine.

Title: C# Decoding long Base64 Strings

Body:
I am using Unity Free + NodeJS to code a small project with my mates.

NodeJs for the Server, and Unity for the Clients.

If you entered valid login data, the Server will return a jwt using njwt, which can be decoded using various online tools, and with c#.

But, this Line: byte[] _dec = Convert.FromBase64String(part); returns no error, but also prevents execution of more code. And I don't know why.

Here are more samples to understand what's going on.

LoginMenu.cs

ws.OnMessage += (sender, e) => {
    JObject res = JObject.Parse(e.Data);

    switch ((string)res["type"])
    {
        // If we get a token from the server
        // login was successful
        case "jwt":
            Debug.Log("Res was JWT");
            UserAccountManager.instance.LogIn((string)res["jwt"]);
            Debug.LogWarning("FINISHED");
            break;
        // Only 1 case for now
    }
};

UserAccountManager.cs

public static UserAccountManager instance;
void Awake() {
    if (instance != null)
    {
        Destroy(gameObject);
        return;
    }

    instance = this;
    DontDestroyOnLoad(this);
}

void Set_Jwt(string _jwt)
{
    Jwt = _jwt;
    Jwt_data = decode_jwt(_jwt);

    playerUsername = (string)Jwt_data["username"];
    Debug.Log("Jwt set");
    Debug.LogWarning(playerUsername);
}

private JObject decode_jwt(string _jwt)
{
    string[] splitted = _jwt.Split('.');
    var part = splitted[1];
    // Code only runs until here
    byte[] _dec = Convert.FromBase64String(part);
    string decodedjwt = Encoding.UTF8.GetString(_dec);

    return JObject.Parse(decodedjwt);
}

public void LogIn(string _jwt) {
    Debug.LogWarning("LogIn called");
    Set_Jwt(_jwt);

    isLoggedIn = true;
    Debug.Log("Trying to load " + loggedInSceneName);
    SceneManager.LoadScene(loggedInSceneName);
}

EDIT:

I have written almost the same code in a new C# ConsoleApplication, and it throws a System.FormatException: "Invalid Length for base64 Char array"

static void Main(string[] args)
    {
        string jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJncy5hd2Vzb21lc3R1ZmYuYXQiLCJpYXQiOjE1MTA1OTkyNzQsImV4cCI6MTUxMDYwMjg3MywidWlkIjoiMTY1ZWMxZjAtYzhhNC0xMWU3LTk2ZWQtYzNjNGQ4NTRmM2I4IiwiYXV0aCI6dHJ1ZSwidXNlcm5hbWUiOiJnYWJlbml6aGVyZSIsImlwIjoiMTk0LjIwOC4xMzguMTI4IiwianRpIjoiNjg4NWM0N2YtMjk3NS00N2MyLTgzYTktN2RmMjhmODE3NDljIn0.tRhx3mUbGBxoGFFr0t6dnPMrdlUT4UKJKLBY_9IiJdBePWp1S10Z91875z6OFK92ymACRR_wO3_1_h6fKXAPTQ";
        string[] splitted = jwt.Split('.');
        var part = splitted[1];

        byte[] arr = Convert.FromBase64String(part);
        string res = Encoding.UTF8.GetString(arr);
        Console.WriteLine(res);

        Console.Read();
    }

What should I do now?


问:
Sort Entry Set of String, Integer by more than one field
Have a Map<String, Integer> and trying to sort on value and length of String. I am trying to compare two different things in the statement so don't know if I need two different statements.  This is being used to compare digit root so the String length and then the digit root is the value and the value.

For example:

```<code>("103",4); (1+0+3 == 4)
("4",4); (4 ==4)
("11101",4); (1+1+1+0+1 == 4)
("5",5); (5 == 5 )
("1003",4); (1+0+0+3 == 4)
</code>```

But ("103",4) > ("4",4) because the length of "103" > "4", and ("11101",4) > ("103",4);, length "11101" > "103"

```<code>Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int length = o1.getKey().length().compareTo(o2.getKey().length());
if(length != 0) {
 return length;
}
return (o1.getValue()).compareTo(o2.getValue());
}
});
</code>```

Edit Answered to the above Question(Also, response given)

```<code> Map<String,Integer> unsortMap = new.
                        TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4); Map<String,

 Integer> result =unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)) )
   .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap
     (Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 System.println(result);
</code>```

答:
You haven't said why it doesn't work. What happens when you try?

In Java, a Map is not meant to be sorted, it is meant for fast access.
However, implementations like TreeMap maintain a deterministic ordering, and can be sorted. Your code suggests you are trying to sort the Map's EntrySet. A Java Set also has no order, and cannot be sorted.

I suggest you either utilise a NavigableMap like a TreeMap, or work with a List rather than a Set. A Java List has an order, and can be sorted using Collections.sort(...).

There are a number of reasons why your existing code may not be working. For one thing, you are attempting to call compareToon an int (at o1.getKey().length().compareTo(...)). This is not possible. You could instead use:

```<code>Ints.compare(o1.getKey().length(), o2.getKey().length());
</code>```

Body:
Have a Map<String, Integer> and trying to sort on value and length of String. I am trying to compare two different things in the statement so don't know if I need two different statements.  This is being used to compare digit root so the String length and then the digit root is the value and the value.

For example:

("103",4); (1+0+3 == 4)
("4",4); (4 ==4)
("11101",4); (1+1+1+0+1 == 4)
("5",5); (5 == 5 )
("1003",4); (1+0+0+3 == 4)

But ("103",4) > ("4",4) because the length of "103" > "4", and ("11101",4) > ("103",4);, length "11101" > "103"

Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int length = o1.getKey().length().compareTo(o2.getKey().length());
if(length != 0) {
 return length;
}
return (o1.getValue()).compareTo(o2.getValue());
}
});

Edit Answered to the above Question(Also, response given)

 Map<String,Integer> unsortMap = new.
                        TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4); Map<String,

 Integer> result =unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)) )
   .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap
     (Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 System.println(result);

Body:
You haven't said why it doesn't work. What happens when you try?

In Java, a Map is not meant to be sorted, it is meant for fast access.
However, implementations like TreeMap maintain a deterministic ordering, and can be sorted. Your code suggests you are trying to sort the Map's EntrySet. A Java Set also has no order, and cannot be sorted.

I suggest you either utilise a NavigableMap like a TreeMap, or work with a List rather than a Set. A Java List has an order, and can be sorted using Collections.sort(...).

There are a number of reasons why your existing code may not be working. For one thing, you are attempting to call compareToon an int (at o1.getKey().length().compareTo(...)). This is not possible. You could instead use:

Ints.compare(o1.getKey().length(), o2.getKey().length());


问:
C++ Is there something like RVO for passing temporary objects to functions?
With RVO it is possible to create an object from a returned object without move or copy. Is it possible to do something similar when passing an object to a function?

```<code>class SomeClass {
    int a;

public:
    SomeClass(int _a)                   {a = _a;        std::cout << "created\n";}
    SomeClass(const SomeClass& source)  {a = source.a;  std::cout << "copied\n";}
    SomeClass(SomeClass&& source)       {a = source.a;  std::cout << "moved\n";}
};

void create(SomeClass&& source) {
    SomeClass some_object( std::move( source));
    //p_some_object = new SomeClass( std::move( source));
    //new( p_some_object) SomeClass( std::move( source));
}

// ...

create(SomeClass(15));
</code>```

In this example the result is "created, moved". (GCC 5.4 / C++11 / -O3) It is the same with new or placement-new. There is no branch or anything so why can't it be created without move?

答:
There is no guarantee that the compiler must inline and analyze enough to recognize that the temporary object referred to by source is unnecessary. Beyond that, even RVO is intended for value semantics; when && references come into play, it's not guaranteed.

As it happens, GCC would handle your case just fine if you followed the general rule for C++ function parameters: "If you need to copy the argument anyway, accept the argument by value."

Accepting by value means that, in cases like this where the argument is constructed as part of the call, no copy or move is needed (it can, and on GCC, is, "RVO"-ed).

```<code>class SomeClass {
    int a;

public:
    SomeClass(int _a)                   {a = _a;        std::cout << "created\n";}
    SomeClass(const SomeClass& source)  {a = source.a;  std::cout << "copied\n";}
    SomeClass(SomeClass&& source)       {a = source.a;  std::cout << "moved\n";}
};

void create(SomeClass some_object) {

}

int main() {
    create(SomeClass(15));
}
</code>```

which if you try it, shows only the created message.

If the goal is for create to construct the object for you, then use a templated function with argument forwarding so you construct it within create, e.g.

```<code>template<typename T, class... Args>
T create(Args&&... args) {
    T some_object(std::forward<Args>(args)...);

    return some_object;
}

int main() {
    auto foo = create<SomeClass>(15);
}
</code>```

which solves the problem by passing the constructor arguments as forwarding references, and constructing the object itself inside create, avoiding any additional construction, as seen here.

Body:
With RVO it is possible to create an object from a returned object without move or copy. Is it possible to do something similar when passing an object to a function?

class SomeClass {
    int a;

public:
    SomeClass(int _a)                   {a = _a;        std::cout << "created\n";}
    SomeClass(const SomeClass& source)  {a = source.a;  std::cout << "copied\n";}
    SomeClass(SomeClass&& source)       {a = source.a;  std::cout << "moved\n";}
};

void create(SomeClass&& source) {
    SomeClass some_object( std::move( source));
    //p_some_object = new SomeClass( std::move( source));
    //new( p_some_object) SomeClass( std::move( source));
}

// ...

create(SomeClass(15));

In this example the result is "created, moved". (GCC 5.4 / C++11 / -O3) It is the same with new or placement-new. There is no branch or anything so why can't it be created without move?

Body:
There is no guarantee that the compiler must inline and analyze enough to recognize that the temporary object referred to by source is unnecessary. Beyond that, even RVO is intended for value semantics; when && references come into play, it's not guaranteed.

As it happens, GCC would handle your case just fine if you followed the general rule for C++ function parameters: "If you need to copy the argument anyway, accept the argument by value."

Accepting by value means that, in cases like this where the argument is constructed as part of the call, no copy or move is needed (it can, and on GCC, is, "RVO"-ed).

class SomeClass {
    int a;

public:
    SomeClass(int _a)                   {a = _a;        std::cout << "created\n";}
    SomeClass(const SomeClass& source)  {a = source.a;  std::cout << "copied\n";}
    SomeClass(SomeClass&& source)       {a = source.a;  std::cout << "moved\n";}
};

void create(SomeClass some_object) {

}

int main() {
    create(SomeClass(15));
}

which if you try it, shows only the created message.

If the goal is for create to construct the object for you, then use a templated function with argument forwarding so you construct it within create, e.g.

template<typename T, class... Args>
T create(Args&&... args) {
    T some_object(std::forward<Args>(args)...);

    return some_object;
}

int main() {
    auto foo = create<SomeClass>(15);
}

which solves the problem by passing the constructor arguments as forwarding references, and constructing the object itself inside create, avoiding any additional construction, as seen here.


问:
How do you reset state when keys are not known? (i.e. dynamic forms)
I'm using es6 syntax setState({[name]: value}) to track dynamically added inputs in form and everything is working fine. I'm wondering about clearing state after form submit. I'll submit my solution but I'd be interested in hearing opinions on a better way of clearing the state, or maybe managing dynamic state shape in general.

According to @DavidL.Walsh (see link below) adding fields to state that were not defined in initial state is wrong. But what about dynamic forms in which you don't know the number of inputs or their names.
https://stackoverflow.com/a/34845925/4634544

答:
Generally when you define a state in a React Component you would define all of the keys and their initial value on mount / construct. you can encapsulate this data to a constant that you use to reset

Using a login form as an example

```<code>const LOGIN_INITIAL_STATE = { username: '', password: '', rememberEmail: false }

// in the class
this.state = {...LOGIN_INITIAL_STATE}

// to reset
this.setState({...LOGIN_INITIAL_STATE})
</code>```

If you dont know the fields for the form, I would not render the form until you get those fields. Pass them as an initial state property.. in the constructor you can then define the state with the initial state property. That way you define the state on construct instead of adding fields in after defining state (which David Walsh recommends because its a bad practice)

Dynamic form example

```<code>someRequestToGetFormFields().then(fields => dispatch({type: FIELDS_ADDED, fields})
// in a reducer you store these fields and update the state of the reducer.

// in a class that renders the form
{ this.props.formFields
  ? <SomeDynamicForm initialState={this.props.formFields} />
  : null
}

// your form class
class SomeDynamicForm extends Component {
    constructor(props) {
        this.state = {...props.initialState}
    }
    resetState = () => {
        this.setState({...this.props.initialState})
    }
    ...
}
</code>```

Now this is a quick and not exhaustive solution.. You should be able to figure out the rest from here though.

Body:
Generally when you define a state in a React Component you would define all of the keys and their initial value on mount / construct. you can encapsulate this data to a constant that you use to reset

Using a login form as an example

const LOGIN_INITIAL_STATE = { username: '', password: '', rememberEmail: false }

// in the class
this.state = {...LOGIN_INITIAL_STATE}

// to reset
this.setState({...LOGIN_INITIAL_STATE})

If you dont know the fields for the form, I would not render the form until you get those fields. Pass them as an initial state property.. in the constructor you can then define the state with the initial state property. That way you define the state on construct instead of adding fields in after defining state (which David Walsh recommends because its a bad practice)

Dynamic form example

someRequestToGetFormFields().then(fields => dispatch({type: FIELDS_ADDED, fields})
// in a reducer you store these fields and update the state of the reducer.

// in a class that renders the form
{ this.props.formFields
  ? <SomeDynamicForm initialState={this.props.formFields} />
  : null
}

// your form class
class SomeDynamicForm extends Component {
    constructor(props) {
        this.state = {...props.initialState}
    }
    resetState = () => {
        this.setState({...this.props.initialState})
    }
    ...
}

Now this is a quick and not exhaustive solution.. You should be able to figure out the rest from here though.


问:
Headless browser and locust.io
Is it possible to integrate a headless browser with locust? I need my load tests to process client side script that triggers additional requests on each page load.</p>

答: You could use something like browserless to take care of the hosting of Chrome (https://browserless.io). Depending on how you brutal your load tests are there’s varying degrees of concurrency. Full disclaimer: I’m the maker of the browserless service</p>

Title: Headless browser and locust.io


问:
iPhone/Obj C: Why does convert float to int: (int) float * 100 does not work?
In my code, I am using float to do currency calculation but the rounding has yielded undesired results so I am trying to convert it all to int. With as little change to the infrastructure as possible, in my init functions, I did this:

```<code>-(id)initWithPrice:(float)p;
{
[self setPrice:(int)(p*100)];
}
</code>```

I multiply by 100 b/c in the main section, the values are given as .xx to 2 decimals. I abnormally I notice is that for float 1.18, the int rounds it to 117. Does anyone know it does that? The float leaves it as 1.18. I expect it to be 118 for the int equiv in cents.

Thanks.

答:
Floating point is always a little imprecise.   With IEEE floating point encoding, powers of two can be represented exactly (like 4,2,1,0.5,0.25,0.125,0.0625,...) , but numbers like 0.1 are always an approximation (just try representing it as a sum of powers of 2).

Your (int) cast will truncate whatever comes in, so if p*100 is resolving to 117.9999995 due to this imprecision , that will become 1.17 instead of 1.18.

Better solution is to use something like roundf on p*100.    Even better would be if you can go upstream and fully convert to fixed-point math using integers in the entire program.

Body:
In my code, I am using float to do currency calculation but the rounding has yielded undesired results so I am trying to convert it all to int. With as little change to the infrastructure as possible, in my init functions, I did this:

-(id)initWithPrice:(float)p;
{
[self setPrice:(int)(p*100)];
}

I multiply by 100 b/c in the main section, the values are given as .xx to 2 decimals. I abnormally I notice is that for float 1.18, the int rounds it to 117. Does anyone know it does that? The float leaves it as 1.18. I expect it to be 118 for the int equiv in cents.

Thanks.