问:
Build a net core project on TFS 2017
I have a solution with 30 odd projects in it that I am trying to build with the TFS2017 build process. Currently I am hitting some speed bumps.

The projects were created in the RTM version of VS2017 and are building with msbuild on the dev machine completely fine. I have also transferred the project between machines only running dotnet restore to get all the dependencies working.

The only change to the projects that is not 'stock' is that I am targeting both NET46 and NETCORE using the <TargetFrameworks /> parameter in the csproj.

Below are the steps I have taken to set up TFS in order to build the projects. Steps 4, 5 and 6 are attempts at getting it working to no avail.

The error that I am constantly provided with is that TFS can't find the dotnet executable, as you will be able to see in the log outputs at the bottom.

Install TFS 2017 - this was an upgrade from 2015

Install VS 2017 on the build server making sure that all frameworks and compilers were installed.

Launch VS as the build server account, and create and build a new net core project as suggested here (https://stackoverflow.com/a/38173701/2302383)

Set up the build described here (https://www.visualstudio.com/en-us/docs/build/apps/aspnet/ci/build-aspnet-core).

Clone an existing build that works on 4.5.2 and add the dotnet restore command.

Use the Net Core preview build template to create a build.

Debug log of step 4 & 5 (uses cmd task with dotnet restore)

```<code>2017-07-05T15:11:46.5154865Z ##[warning]File name doesn't indicate a full path to a executable file.
2017-07-05T15:11:46.5174870Z Executing the following command-line. (workingFolder = E:\VsoAgents\agent1\_work\31\s)
2017-07-05T15:11:46.5204867Z dotnet restore
2017-07-05T15:11:46.5214870Z Error message highlight pattern:
2017-07-05T15:11:46.5214870Z Warning message highlight pattern:
2017-07-05T15:11:46.5224872Z C:\Windows\system32\cmd.exe /c "dotnet restore"
2017-07-05T15:11:46.5624906Z 'dotnet' is not recognized as an internal or external command,
2017-07-05T15:11:46.5634910Z operable program or batch file.
</code>```

Debug log of step 6 (sensitive info has been replaced by [[REDACTED]])

```<code>2017-07-05T15:15:37.1734770Z Set workingFolder to default: E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1
2017-07-05T15:15:37.7375119Z ##[debug]agent.workFolder=E:\VsoAgents\agent1\_work
2017-07-05T15:15:37.7385124Z ##[debug]loading inputs and endpoints
2017-07-05T15:15:37.7415122Z ##[debug]loading ENDPOINT_AUTH_$/
2017-07-05T15:15:37.7455138Z ##[debug]loading ENDPOINT_AUTH_PARAMETER_$/_ACCESSTOKEN
2017-07-05T15:15:37.7465136Z ##[debug]loading ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN
2017-07-05T15:15:37.7475134Z ##[debug]loading ENDPOINT_AUTH_SCHEME_$/
2017-07-05T15:15:37.7485123Z ##[debug]loading ENDPOINT_AUTH_SCHEME_SYSTEMVSSCONNECTION
2017-07-05T15:15:37.7495157Z ##[debug]loading ENDPOINT_AUTH_SYSTEMVSSCONNECTION
2017-07-05T15:15:37.7505131Z ##[debug]loading INPUT_COMMAND
2017-07-05T15:15:37.7515125Z ##[debug]loading INPUT_PROJECTS
2017-07-05T15:15:37.7525123Z ##[debug]loading INPUT_PUBLISHWEBPROJECTS
2017-07-05T15:15:37.7535143Z ##[debug]loading INPUT_ZIPAFTERPUBLISH
2017-07-05T15:15:37.7545134Z ##[debug]loaded 10
2017-07-05T15:15:38.1705390Z ##[debug]command=restore
2017-07-05T15:15:38.1715403Z ##[debug]projects=**/project.json
2017-07-05T15:15:38.1725392Z ##[debug]arguments=null
2017-07-05T15:15:38.1735387Z ##[debug]publishWebProjects=true
2017-07-05T15:15:38.1745389Z ##[debug]zipAfterPublish=true
2017-07-05T15:15:38.1755406Z ##[debug]check path : E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1\task.json
2017-07-05T15:15:38.1765390Z ##[debug]set resource file to: E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1\task.json
2017-07-05T15:15:38.1775415Z ##[debug]system.culture=en-US
2017-07-05T15:15:38.1825417Z ##[debug]Absolute path for pathSegments: C:\Program Files\Python 3.5\Scripts\/dotnet = C:\Program Files\Python 3.5\Scripts\dotnet
2017-07-05T15:15:38.1835414Z ##[debug]Absolute path for pathSegments: C:\Program Files\Python 3.5\/dotnet = C:\Program Files\Python 3.5\dotnet
2017-07-05T15:15:38.1845418Z ##[debug]Absolute path for pathSegments: C:\Windows\system32/dotnet = C:\Windows\system32\dotnet
2017-07-05T15:15:38.1855401Z ##[debug]Absolute path for pathSegments: C:\Windows/dotnet = C:\Windows\dotnet
2017-07-05T15:15:38.1855401Z ##[debug]Absolute path for pathSegments: C:\Windows\System32\Wbem/dotnet = C:\Windows\System32\Wbem\dotnet
2017-07-05T15:15:38.1865430Z ##[debug]Absolute path for pathSegments: C:\Windows\System32\WindowsPowerShell\v1.0\/dotnet = C:\Windows\System32\WindowsPowerShell\v1.0\dotnet
2017-07-05T15:15:38.1875421Z ##[debug]Absolute path for pathSegments: %USERPROFILE%\.dnx\bin/dotnet = E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1\%USERPROFILE%\.dnx\bin\dotnet
2017-07-05T15:15:38.1885418Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft DNX\Dnvm\/dotnet = C:\Program Files\Microsoft DNX\Dnvm\dotnet
2017-07-05T15:15:38.1895423Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft SQL Server\120\Tools\Binn\/dotnet = C:\Program Files\Microsoft SQL Server\120\Tools\Binn\dotnet
2017-07-05T15:15:38.1905429Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft Office Servers\15.0\Bin\/dotnet = C:\Program Files\Microsoft Office Servers\15.0\Bin\dotnet
2017-07-05T15:15:38.1915417Z ##[debug]Absolute path for pathSegments: C:\Program Files\Babel/dotnet = C:\Program Files\Babel\dotnet
2017-07-05T15:15:38.1925419Z ##[debug]Absolute path for pathSegments: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\/dotnet = C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\dotnet
2017-07-05T15:15:38.1935419Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft SQL Server\110\Tools\Binn\/dotnet = C:\Program Files\Microsoft SQL Server\110\Tools\Binn\dotnet
2017-07-05T15:15:38.1945409Z ##[debug]Absolute path for pathSegments: C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\/dotnet = C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\dotnet
2017-07-05T15:15:38.1955423Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft\Web Platform Installer\/dotnet = C:\Program Files\Microsoft\Web Platform Installer\dotnet
2017-07-05T15:15:38.1955423Z ##[debug]Absolute path for pathSegments: C:\Program Files (x86)\NuGet/dotnet = C:\Program Files (x86)\NuGet\dotnet
2017-07-05T15:15:38.1965419Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft SQL Server\130\Tools\Binn\/dotnet = C:\Program Files\Microsoft SQL Server\130\Tools\Binn\dotnet
2017-07-05T15:15:38.1975423Z ##[debug]Absolute path for pathSegments: C:\Users\[[REDACTED]]\.dnx\bin/dotnet = C:\Users\[[REDACTED]]\.dnx\bin\dotnet
2017-07-05T15:15:38.1985426Z ##[debug]check path : null
2017-07-05T15:15:38.2065429Z ##[debug]task result: Failed
2017-07-05T15:15:38.2245432Z ##[error]Error: Failed which: Not found dotnet: null
</code>```

答: The agent scan's the PATH and other environment-related configuration on startup so you'll need to restart the agent service for environment-related changes to take effect. The more complete approach is to just reboot the machine which will allow all system-wide changes made by installing/updating components to take effect.

Title: Build a net core project on TFS 2017

Body:
I have a solution with 30 odd projects in it that I am trying to build with the TFS2017 build process. Currently I am hitting some speed bumps.

The projects were created in the RTM version of VS2017 and are building with msbuild on the dev machine completely fine. I have also transferred the project between machines only running dotnet restore to get all the dependencies working.

The only change to the projects that is not 'stock' is that I am targeting both NET46 and NETCORE using the <TargetFrameworks /> parameter in the csproj.

Below are the steps I have taken to set up TFS in order to build the projects. Steps 4, 5 and 6 are attempts at getting it working to no avail.

The error that I am constantly provided with is that TFS can't find the dotnet executable, as you will be able to see in the log outputs at the bottom.

Install TFS 2017 - this was an upgrade from 2015

Install VS 2017 on the build server making sure that all frameworks and compilers were installed.

Launch VS as the build server account, and create and build a new net core project as suggested here (https://stackoverflow.com/a/38173701/2302383)

Set up the build described here (https://www.visualstudio.com/en-us/docs/build/apps/aspnet/ci/build-aspnet-core).

Clone an existing build that works on 4.5.2 and add the dotnet restore command.

Use the Net Core preview build template to create a build.

Debug log of step 4 & 5 (uses cmd task with dotnet restore)

2017-07-05T15:11:46.5154865Z ##[warning]File name doesn't indicate a full path to a executable file.
2017-07-05T15:11:46.5174870Z Executing the following command-line. (workingFolder = E:\VsoAgents\agent1\_work\31\s)
2017-07-05T15:11:46.5204867Z dotnet restore
2017-07-05T15:11:46.5214870Z Error message highlight pattern:
2017-07-05T15:11:46.5214870Z Warning message highlight pattern:
2017-07-05T15:11:46.5224872Z C:\Windows\system32\cmd.exe /c "dotnet restore"
2017-07-05T15:11:46.5624906Z 'dotnet' is not recognized as an internal or external command,
2017-07-05T15:11:46.5634910Z operable program or batch file.

Debug log of step 6 (sensitive info has been replaced by [[REDACTED]])

2017-07-05T15:15:37.1734770Z Set workingFolder to default: E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1
2017-07-05T15:15:37.7375119Z ##[debug]agent.workFolder=E:\VsoAgents\agent1\_work
2017-07-05T15:15:37.7385124Z ##[debug]loading inputs and endpoints
2017-07-05T15:15:37.7415122Z ##[debug]loading ENDPOINT_AUTH_$/
2017-07-05T15:15:37.7455138Z ##[debug]loading ENDPOINT_AUTH_PARAMETER_$/_ACCESSTOKEN
2017-07-05T15:15:37.7465136Z ##[debug]loading ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN
2017-07-05T15:15:37.7475134Z ##[debug]loading ENDPOINT_AUTH_SCHEME_$/
2017-07-05T15:15:37.7485123Z ##[debug]loading ENDPOINT_AUTH_SCHEME_SYSTEMVSSCONNECTION
2017-07-05T15:15:37.7495157Z ##[debug]loading ENDPOINT_AUTH_SYSTEMVSSCONNECTION
2017-07-05T15:15:37.7505131Z ##[debug]loading INPUT_COMMAND
2017-07-05T15:15:37.7515125Z ##[debug]loading INPUT_PROJECTS
2017-07-05T15:15:37.7525123Z ##[debug]loading INPUT_PUBLISHWEBPROJECTS
2017-07-05T15:15:37.7535143Z ##[debug]loading INPUT_ZIPAFTERPUBLISH
2017-07-05T15:15:37.7545134Z ##[debug]loaded 10
2017-07-05T15:15:38.1705390Z ##[debug]command=restore
2017-07-05T15:15:38.1715403Z ##[debug]projects=**/project.json
2017-07-05T15:15:38.1725392Z ##[debug]arguments=null
2017-07-05T15:15:38.1735387Z ##[debug]publishWebProjects=true
2017-07-05T15:15:38.1745389Z ##[debug]zipAfterPublish=true
2017-07-05T15:15:38.1755406Z ##[debug]check path : E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1\task.json
2017-07-05T15:15:38.1765390Z ##[debug]set resource file to: E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1\task.json
2017-07-05T15:15:38.1775415Z ##[debug]system.culture=en-US
2017-07-05T15:15:38.1825417Z ##[debug]Absolute path for pathSegments: C:\Program Files\Python 3.5\Scripts\/dotnet = C:\Program Files\Python 3.5\Scripts\dotnet
2017-07-05T15:15:38.1835414Z ##[debug]Absolute path for pathSegments: C:\Program Files\Python 3.5\/dotnet = C:\Program Files\Python 3.5\dotnet
2017-07-05T15:15:38.1845418Z ##[debug]Absolute path for pathSegments: C:\Windows\system32/dotnet = C:\Windows\system32\dotnet
2017-07-05T15:15:38.1855401Z ##[debug]Absolute path for pathSegments: C:\Windows/dotnet = C:\Windows\dotnet
2017-07-05T15:15:38.1855401Z ##[debug]Absolute path for pathSegments: C:\Windows\System32\Wbem/dotnet = C:\Windows\System32\Wbem\dotnet
2017-07-05T15:15:38.1865430Z ##[debug]Absolute path for pathSegments: C:\Windows\System32\WindowsPowerShell\v1.0\/dotnet = C:\Windows\System32\WindowsPowerShell\v1.0\dotnet
2017-07-05T15:15:38.1875421Z ##[debug]Absolute path for pathSegments: %USERPROFILE%\.dnx\bin/dotnet = E:\VsoAgents\agent1\tasks\DotNetCoreCLI\0.3.1\%USERPROFILE%\.dnx\bin\dotnet
2017-07-05T15:15:38.1885418Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft DNX\Dnvm\/dotnet = C:\Program Files\Microsoft DNX\Dnvm\dotnet
2017-07-05T15:15:38.1895423Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft SQL Server\120\Tools\Binn\/dotnet = C:\Program Files\Microsoft SQL Server\120\Tools\Binn\dotnet
2017-07-05T15:15:38.1905429Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft Office Servers\15.0\Bin\/dotnet = C:\Program Files\Microsoft Office Servers\15.0\Bin\dotnet
2017-07-05T15:15:38.1915417Z ##[debug]Absolute path for pathSegments: C:\Program Files\Babel/dotnet = C:\Program Files\Babel\dotnet
2017-07-05T15:15:38.1925419Z ##[debug]Absolute path for pathSegments: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\/dotnet = C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\dotnet
2017-07-05T15:15:38.1935419Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft SQL Server\110\Tools\Binn\/dotnet = C:\Program Files\Microsoft SQL Server\110\Tools\Binn\dotnet
2017-07-05T15:15:38.1945409Z ##[debug]Absolute path for pathSegments: C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\/dotnet = C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\dotnet
2017-07-05T15:15:38.1955423Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft\Web Platform Installer\/dotnet = C:\Program Files\Microsoft\Web Platform Installer\dotnet
2017-07-05T15:15:38.1955423Z ##[debug]Absolute path for pathSegments: C:\Program Files (x86)\NuGet/dotnet = C:\Program Files (x86)\NuGet\dotnet
2017-07-05T15:15:38.1965419Z ##[debug]Absolute path for pathSegments: C:\Program Files\Microsoft SQL Server\130\Tools\Binn\/dotnet = C:\Program Files\Microsoft SQL Server\130\Tools\Binn\dotnet
2017-07-05T15:15:38.1975423Z ##[debug]Absolute path for pathSegments: C:\Users\[[REDACTED]]\.dnx\bin/dotnet = C:\Users\[[REDACTED]]\.dnx\bin\dotnet
2017-07-05T15:15:38.1985426Z ##[debug]check path : null
2017-07-05T15:15:38.2065429Z ##[debug]task result: Failed
2017-07-05T15:15:38.2245432Z ##[error]Error: Failed which: Not found dotnet: null


来源: stackexchange

问:
android toast a Chinese message to user
Basically I need to toast a message written in Chinese to user.
However I don't know how to achieve such thing.
Any solution that can help me?</p>

答:
I found my own answer. It's so simple I didn't think of that in the first place. And it always works.
Under res/values/string.xml of Android project, I edit:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="sample">中国的网页</string>
</resources>
</code>```

And the I retrieve the string name "sample" out of project's resource using:

```<code>this.getString(R.string.sample);
</code>```

ContentLicense: CC BY-SA 2.5

Title: android toast a Chinese message to user

Body:
I found my own answer. It's so simple I didn't think of that in the first place. And it always works.
Under res/values/string.xml of Android project, I edit:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="sample">中国的网页</string>
</resources>

And the I retrieve the string name "sample" out of project's resource using:

this.getString(R.string.sample);


问:
Why can't I reuse "unapply" without repeating the method signature
The following Scala code compiles fine:

```<code>val f = (input: String) => Some("result")
object Extract {
   def unapply(input: String): Option[String] = f(input)
}
val Extract(result) = "a string"
</code>```

But if I replace the extractor by:

```<code>object Extract {
   def unapply = f
}
</code>```

Then compilation fails with:

```<code>error: an unapply result must have a member `def isEmpty: Boolean
val Extract(result) = "a string"
    ^
</code>```

Why? Where does def isEmpty: Boolean come from?

答:
In Scala 2.10 (and before) unapply had to always return an Option or a Boolean. Since 2.11, it can return any type, so far as it has def isEmpty: Boolean and def get: <some type> methods (like Option does). See https://hseeberger.wordpress.com/2013/10/04/name-based-extractors-in-scala-2-11/ for an explanation why it's useful.
But your unapply returns a String => Some[String], which doesn't have either, and that's what the error says.

ContentLicense: CC BY-SA 3.0

Body:
The following Scala code compiles fine:

val f = (input: String) => Some("result")
object Extract {
   def unapply(input: String): Option[String] = f(input)
}
val Extract(result) = "a string"

But if I replace the extractor by:

object Extract {
   def unapply = f
}

Then compilation fails with:

error: an unapply result must have a member `def isEmpty: Boolean
val Extract(result) = "a string"
    ^

Why? Where does def isEmpty: Boolean come from?

ContentLicense: CC BY-SA 4.0


问:
Setting viewport width is ignored on cordova 7
A couple of years ago I developed a cordova/phonegap application. I needed to fix screen width to 1200 (some devices had a width of 962px) so I added a meta tag to set viewport content width like

```<code><meta name="viewport" content="width=1200, user-scalable-no">
</code>```

Recently I've had to add some new features and upgraded to latest cordova/phonegap versions (7.0.1/6.5.0) and it seems the viewport meta tag is ignored. Running old version I can see in the chrome devtools that html width is 1200px but with the newer version html width remains to 960px

Any idea about how to fix this issue?

答:
I finally could solve this issue by editing the MainActivity.java file in android platform folder.
This file declares a class that inherits from CordovaActivity and overrides the onCreate method. It seem that now is required to set a couple of settings in order the webview makes use of the "viewport" meta.

My onCreate method in MainActivity.java now looks like:

```<code>@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // enable Cordova apps to be started in the background
    Bundle extras = getIntent().getExtras();
    if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
        moveTaskToBack(true);
    }

    // Set by <content src="index.html" /> in config.xml

    if(appView == null)
              init();

    WebView webView = (WebView)appView.getView();
    WebSettings settings = webView.getSettings();
    settings.setLoadWithOverviewMode(true);
   settings.setUseWideViewPort(true);

   loadUrl(launchUrl);
}
</code>```

The key is to call set "LoadWithOverviewMode" and "UseWideViewPort" to true.

Now app is working as expected

Body:
A couple of years ago I developed a cordova/phonegap application. I needed to fix screen width to 1200 (some devices had a width of 962px) so I added a meta tag to set viewport content width like

<meta name="viewport" content="width=1200, user-scalable-no">

Recently I've had to add some new features and upgraded to latest cordova/phonegap versions (7.0.1/6.5.0) and it seems the viewport meta tag is ignored. Running old version I can see in the chrome devtools that html width is 1200px but with the newer version html width remains to 960px

Any idea about how to fix this issue?

Body:
I finally could solve this issue by editing the MainActivity.java file in android platform folder.
This file declares a class that inherits from CordovaActivity and overrides the onCreate method. It seem that now is required to set a couple of settings in order the webview makes use of the "viewport" meta.

My onCreate method in MainActivity.java now looks like:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // enable Cordova apps to be started in the background
    Bundle extras = getIntent().getExtras();
    if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
        moveTaskToBack(true);
    }

    // Set by <content src="index.html" /> in config.xml

    if(appView == null)
              init();

    WebView webView = (WebView)appView.getView();
    WebSettings settings = webView.getSettings();
    settings.setLoadWithOverviewMode(true);
   settings.setUseWideViewPort(true);

   loadUrl(launchUrl);
}

The key is to call set "LoadWithOverviewMode" and "UseWideViewPort" to true.

Now app is working as expected


问:
Remove automatic naming of variables in visualizations in Power BI
I have two columns with dates and daily currency observations. In a chart, the default title looks like this:

If you change the valuetype to Average like this:

Then the title changes as well:

Is there any way to override this functionality?
There is a suggestion on community.powerbi.com to add another measure with the desired name, but that is not a very feasible solution when you have a lot of variables.

Thank you for any suggestions!

Edit in response to a comment below where @user5226582 correctly points out that the title can be easily edited. Here's another example with two variables and labels in addition to a title:

The title, as you pointed out, can easily be changed here:

So that we end up with this:

However, the problem  with the automatic addition of Average of... still persist in the legend:

And as far as i can tell you don't have the same felxibility with the legend as you do with the title:

答:
With the July release of Power BI Desktop, you can now rename fields in visuals. The field will be renamed anywhere it is used in a chart.

Power BI Blog


问:
retrofit 2 onResponse getting called for no internet
retrofit 2 onResponse() getting called even if there is no internet connection.

build.gradle:

```<code>  compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
</code>```

Code:

```<code>Call<ArrayList<Repository>> call = mViewsApiEnd.getRepository("rajuse");

                call.enqueue(new Callback<ArrayList<Repository>>() {
                    @Override
                    public void onResponse(@NonNull Call<ArrayList<Repository>> call, @NonNull Response<ArrayList<Repository>> response) {
                        if (response.code()==200) {
                            }
                    }

                    @Override
                    public void onFailure(Call<ArrayList<Repository>> call, Throwable t) {
                        tv_response.setText("Retrofit onFailure got called :(");
                    }
</code>```

Steps to recreate:

1.make api call when internet is present

2. turn off internet

3. make api call.

onResponse() got called

Update:
I found out that this is kind of umimplemented fubtionality in retrofit. Please refer my workaround and issue:

https://github.com/square/retrofit/issues/2390

Other libraries like volley doesn't call success callback. Instead give ioexception in error callback.

答:
Yes failure or success it should get a response

so handle it like this

```<code>    compile 'com.google.api-client:google-api-client-android:1.20.0' exclude module: 'httpclient'
    compile 'com.google.http-client:google-http-client-gson:1.20.0' exclude module: 'httpclient'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'

 Call<UserMaster> call = Retro.getRetroWS().UserLogin(userMaster, otp);
        try {
            Response<UserMaster> response = call.execute();
            if (response.isSuccessful()) {
                return response.body();
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
</code>```

Body:
retrofit 2 onResponse() getting called even if there is no internet connection.

build.gradle:

  compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'

Code:

Call<ArrayList<Repository>> call = mViewsApiEnd.getRepository("rajuse");

                call.enqueue(new Callback<ArrayList<Repository>>() {
                    @Override
                    public void onResponse(@NonNull Call<ArrayList<Repository>> call, @NonNull Response<ArrayList<Repository>> response) {
                        if (response.code()==200) {
                            }
                    }

                    @Override
                    public void onFailure(Call<ArrayList<Repository>> call, Throwable t) {
                        tv_response.setText("Retrofit onFailure got called :(");
                    }

Steps to recreate:

1.make api call when internet is present

2. turn off internet

3. make api call.

onResponse() got called

Update:
I found out that this is kind of umimplemented fubtionality in retrofit. Please refer my workaround and issue:

https://github.com/square/retrofit/issues/2390

Other libraries like volley doesn't call success callback. Instead give ioexception in error callback.

Body:
Yes failure or success it should get a response

so handle it like this

    compile 'com.google.api-client:google-api-client-android:1.20.0' exclude module: 'httpclient'
    compile 'com.google.http-client:google-http-client-gson:1.20.0' exclude module: 'httpclient'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'

 Call<UserMaster> call = Retro.getRetroWS().UserLogin(userMaster, otp);
        try {
            Response<UserMaster> response = call.execute();
            if (response.isSuccessful()) {
                return response.body();
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


问:
Addition of UI elements in a cardboard application
I want to make a 360 panorama viewer in Android studio.

The idea is to make it exactly like the existing googles street view application.

I want to know how to add a/some UI element inside the VR view so that if a user looks at it, the 360 picture would change to some other picture.

I know it is a long way to go but for now, if somebody could help me or direct me towards achieving it, it will really help.

Thanks in Advance.

答: A good place to start is a demo app by Google called TreasureHunt (this is part of GoogleVR). Download the sample code compile and run you'll get a sense of what you need to do. TreasureHunt is also found on Google Play.</p>


问:
can not resolve symbol 'from' Error in Android Studio
can not resolve symbol 'from' in

```<code>LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
</code>```

this is my complete class:

```<code>package ir.sangram.sangram.chat;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import ir.sangram.sangram.R;

/**
 * Created by HOW on 07/04/2017.
 */
class ChatListViewHolder extends RecyclerView.ViewHolder{
    public CircleImageView profile_picture;
    public TextView user_name, last_chat, unread_messages;
    public ChatListViewHolder(View itemView) {
        super(itemView);
        profile_picture = (CircleImageView) itemView.findViewById(R.id.profile_picture);
        user_name = (TextView) itemView.findViewById(R.id.user_name);
        last_chat = (TextView) itemView.findViewById(R.id.last_chat);
        unread_messages = (TextView) itemView.findViewById(R.id.unread_messages);
    }
}
public class ChatListAdapter extends RecyclerView.Adapter<ChatListViewHolder>{
    private List<ChatListData> chat_list = new ArrayList<ChatListData>();

    public ChatListAdapter(List<ChatListData> chat_list) {
        this.chat_list = chat_list;
    }

    @Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
        //LayoutInflater inflater;// = new LayoutInflater.from(parent.getContext());
        //inflater = ( LayoutInflater )parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);//!!!!!!!!!!
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ChatListViewHolder holder, int position) {
        holder.profile_picture.setImageResource(chat_list.get(position).getProfile_picture_id());
        holder.user_name.setText(chat_list.get(position).getUser_name());
        holder.unread_messages.setText(chat_list.get(position).getUnread_messages());
        holder.last_chat.setText(chat_list.get(position).getLast_chat());
    }

    @Override
    public int getItemCount() {
        return chat_list.size();
    }
}
</code>```

What can i do?
please help me
thnx

答:
LayoutInflater.from() is an static method and to access static method you don't need to create an instance using new keyword.

Use:

```<code>LayoutInflater inflater = LayoutInflater.from(parent.getContext());
</code>```

Instead of:

```<code>LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
</code>```

Body:
can not resolve symbol 'from' in

LayoutInflater inflater = new LayoutInflater.from(parent.getContext());

this is my complete class:

package ir.sangram.sangram.chat;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import ir.sangram.sangram.R;

/**
 * Created by HOW on 07/04/2017.
 */
class ChatListViewHolder extends RecyclerView.ViewHolder{
    public CircleImageView profile_picture;
    public TextView user_name, last_chat, unread_messages;
    public ChatListViewHolder(View itemView) {
        super(itemView);
        profile_picture = (CircleImageView) itemView.findViewById(R.id.profile_picture);
        user_name = (TextView) itemView.findViewById(R.id.user_name);
        last_chat = (TextView) itemView.findViewById(R.id.last_chat);
        unread_messages = (TextView) itemView.findViewById(R.id.unread_messages);
    }
}
public class ChatListAdapter extends RecyclerView.Adapter<ChatListViewHolder>{
    private List<ChatListData> chat_list = new ArrayList<ChatListData>();

    public ChatListAdapter(List<ChatListData> chat_list) {
        this.chat_list = chat_list;
    }

    @Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
        //LayoutInflater inflater;// = new LayoutInflater.from(parent.getContext());
        //inflater = ( LayoutInflater )parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);//!!!!!!!!!!
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ChatListViewHolder holder, int position) {
        holder.profile_picture.setImageResource(chat_list.get(position).getProfile_picture_id());
        holder.user_name.setText(chat_list.get(position).getUser_name());
        holder.unread_messages.setText(chat_list.get(position).getUnread_messages());
        holder.last_chat.setText(chat_list.get(position).getLast_chat());
    }

    @Override
    public int getItemCount() {
        return chat_list.size();
    }
}

What can i do?
please help me
thnx

Body:
LayoutInflater.from() is an static method and to access static method you don't need to create an instance using new keyword.

Use:

LayoutInflater inflater = LayoutInflater.from(parent.getContext());

Instead of:

LayoutInflater inflater = new LayoutInflater.from(parent.getContext());


问:
Match substring in string divided by a dot
I have following strings:

```<code>'sample1.sample2'
'sample1.sample2.samaple3'
</code>```

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

```<code>$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);
</code>```

works fine only for first case.

答:
You can trim single quotes and then a simple explode on dot:

```<code>php> $str = "'sample1.sample2.samaple3'";

php> print_r(explode('.', trim($str, "'")));
Array
(
    [0] => sample1
    [1] => sample2
    [2] => samaple3
)

php> $str = "'sample1.sample2'";

php> print_r(explode('.', trim($str, "'")));
Array
(
    [0] => sample1
    [1] => sample2
)
</code>```

Body:
I have following strings:

'sample1.sample2'
'sample1.sample2.samaple3'

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);

works fine only for first case.

Body:
You can trim single quotes and then a simple explode on dot:

php> $str = "'sample1.sample2.samaple3'";

php> print_r(explode('.', trim($str, "'")));
Array
(
    [0] => sample1
    [1] => sample2
    [2] => samaple3
)

php> $str = "'sample1.sample2'";

php> print_r(explode('.', trim($str, "'")));
Array
(
    [0] => sample1
    [1] => sample2
)


问:
jQuery window resize on tabs
I've got a masonry image grid within 2 tabs (so 1 masonry grid within each tab content area). The common issue i'm having is switching between tabs is messing up the grid because of a window resize issue.

You can see working example here: http://www.gomy5.co.uk/our-work-copy/

I'm currently trying .resize on tab click, but it's not working correctly.

```<code>$(".tab-link").click(function(){
    $('#tab-1').resize();
    $('#tab-2').resize();
});
</code>```

Any ideas why it's not re-sizing the tabbed content area correctly?

Thanks

答:
I couldn't find a working jQuery solution. So i've found a css based one. Instead of using

```<code>display:none
</code>```

and the dimensions not being set on hidden elements. I changed and used

```<code>visibility:hidden;
visibility: visible;
</code>```

This seems to have solved the problem.

Title: jQuery window resize on tabs

Body:
I've got a masonry image grid within 2 tabs (so 1 masonry grid within each tab content area). The common issue i'm having is switching between tabs is messing up the grid because of a window resize issue.

You can see working example here: http://www.gomy5.co.uk/our-work-copy/

I'm currently trying .resize on tab click, but it's not working correctly.

$(".tab-link").click(function(){
    $('#tab-1').resize();
    $('#tab-2').resize();
});

Any ideas why it's not re-sizing the tabbed content area correctly?

Thanks

Body:
I couldn't find a working jQuery solution. So i've found a css based one. Instead of using

display:none

and the dimensions not being set on hidden elements. I changed and used

visibility:hidden;
visibility: visible;

This seems to have solved the problem.


问:
Run the application in iPad 10.5 inch Simulator?
I have downloaded Xcode 8.3.3 and I am able to view iPad pro 10.5 inch in Interface builder. But I would like to test it in iPad pro 10.5 inch simulator. Is there anyway to download that simulator on Xcode.

I have looked at below thread but it does not answer my question.

How to add support for 10.5 inch iPad Pro

答:
You don't have to download a different simulator for different device sizes, only for different iOS versions. Look for "iPad Pro (10.5-inch)" in the Xcode "Devices" window (press Shift+Cmd+2 to show it). If it's not there, try using the "+" button to add it.

Also make sure your target is correctly set up. Click on your project in the file navigator and select the target you're building in the main pane, then:

look in the deployment info for your target (in your target's "General" tab) and make sure "Devices" are set to "Universal" or "iPad",

make sure the Base SDK, in your target's  "Build Settings" tab, is set to "Latest iOS", as the simulator may not show if the target is not being built for the minimum iOS version it supports.


问:
How to use explode function for finding the result like this? and please explain the meaning of each $delimiter used inside the explode function
My input is $text = '( ( LED AND DIODE ) OR ( "LEE power" and system ) ) '

I am applying explode function on this input

```<code>function multiexplode ($delimiters,$string)
{
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}
$exploded = multiexplode(array(' ',":" ), $text);
for($i=0;$i<(count($exploded));$i++)
    echo "<br> $exploded[$i]";
</code>```

My output is coming like this

```<code>0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - "LEE
9 - power"
10 - and
11 - system
12 - )
13 - )
</code>```

But I want to output like the following

```<code>0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - LEE power
9 - and
10 - system
11 - )
12 - )
</code>```

I want to store all words inside " " in one element of array.

答:
here </p>

```<code><?php
    $text = str_replace('LEE power','LEE-power',"( ( LED AND DIODE ) OR ( 'LEE power' and system ) ) ");
    $newArray = explode(' ',$text);
    foreach($newArray as $row) $data[] = str_replace('-',' ',$row);
    echo "```";print_r($data);die;
?>
</code>```

Body:
My input is $text = '( ( LED AND DIODE ) OR ( "LEE power" and system ) ) '

I am applying explode function on this input

function multiexplode ($delimiters,$string)
{
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}
$exploded = multiexplode(array(' ',":" ), $text);
for($i=0;$i<(count($exploded));$i++)
    echo "
 $exploded[$i]";

My output is coming like this

0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - "LEE
9 - power"
10 - and
11 - system
12 - )
13 - )

But I want to output like the following

0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - LEE power
9 - and
10 - system
11 - )
12 - )

I want to store all words inside " " in one element of array.

Body:
here

<?php
    $text = str_replace('LEE power','LEE-power',"( ( LED AND DIODE ) OR ( 'LEE power' and system ) ) ");
    $newArray = explode(' ',$text);
    foreach($newArray as $row) $data[] = str_replace('-',' ',$row);
    echo "<pre>";print_r($data);die;
?>


问:
Android instance app feature module fails to find a layout resource in the same module
I have the following project structure which I want to convert to a instant apps. The installed project works fine, but when I want to runt the instant app version, the base feature module loads perfectly, but when it comes to the feature module, then it fails to find the resources from its module. When I move the resources from feature module to base module, then it recognizes them with the full package name of the base feature module.

The project structure is the following:
 - app module
 - instant app module

 - base feature module  - com.app.base.feature
 - feature module       - com.app.feature.

in feature module when the resource is located in feature module itself the resources are not found, but they are found when I move the resource into the base feature module and reference them as following com.app.base.feature.R.layout.sample_layout.

EDIT: No known package when getting value for resource number 0x80060009.

Any kind of help would be appreciated :)

答:
When you modularise your app, the base feature module cannot access any classes or resources present in the feature module. However the vice versa is possible.

It might so happen that when you create the fragment, the R class might be pointing to the base module. Try specifying the full path to the feature module R class while accessing the layout and check if it solves your issue. Just go through all your R class references and specify full paths to base and feature R classes wherever necessary.


问:
Combining two queries and using HAVING
My solution about this problem is by using 2 queries, but I am wondering if I can do it in one query only.

I have tables like these:

saved_docs

```<code>   id   |   user_id   |   doc_id   |   date
-----------------------------------------------
   1    |   2         |   1        |   date
   2    |   3         |   2        |   date
   3    |   2         |   3        |   date
</code>```

docs_list

```<code>   id   |   url   |   title   |   date
-----------------------------------------
   1    |   url   |   title   |   date
   2    |   url   |   title   |   date
   3    |   url   |   title   |   date
</code>```

What I want is first to get the doc_id on where the user_id is equal to user's id. Then, get the docs on where the id in the docs_list is equal to doc_id/s I get in saved_docs and order by the saved_docs' date.

This can be done on 2 queries, but if there is a possibility that I can do it in one only then I will go for it.

Here is my current mysql query:

```<code>SELECT docs_list.url, docs_list.title

FROM docs_list

INNER JOIN saved_docs

ON saved_posts.user_id = {$user_id}

ORDER BY saved_docs.date DESC
</code>```

Note: I read about HAVING, problem is I do not know how to apply it to this query.

Current problem:

It is giving me all the docs in which is obvious because it does not give the right doc_id/s (automated). What do I need to do to make this the way I wanted to?

[SOLVED]

Note: Both etsa's and adam's answer solved my problem.

答:
You can try this:</p>

```<code>SELECT docs_list.url, docs_list.title
FROM docs_list
INNER JOIN saved_docs ON docs_list.id = saved_docs.doc_id
 WHERE saved_posts.user_id = {$user_id}
ORDER BY saved_docs.date DESC
</code>```

Title: Combining two queries and using HAVING

Body:
My solution about this problem is by using 2 queries, but I am wondering if I can do it in one query only.

I have tables like these:

saved_docs

   id   |   user_id   |   doc_id   |   date
-----------------------------------------------
   1    |   2         |   1        |   date
   2    |   3         |   2        |   date
   3    |   2         |   3        |   date

docs_list

   id   |   url   |   title   |   date
-----------------------------------------
   1    |   url   |   title   |   date
   2    |   url   |   title   |   date
   3    |   url   |   title   |   date

What I want is first to get the doc_id on where the user_id is equal to user's id. Then, get the docs on where the id in the docs_list is equal to doc_id/s I get in saved_docs and order by the saved_docs' date.

This can be done on 2 queries, but if there is a possibility that I can do it in one only then I will go for it.

Here is my current mysql query:

SELECT docs_list.url, docs_list.title

FROM docs_list

INNER JOIN saved_docs

ON saved_posts.user_id = {$user_id}

ORDER BY saved_docs.date DESC

Note: I read about HAVING, problem is I do not know how to apply it to this query.

Current problem:

It is giving me all the docs in which is obvious because it does not give the right doc_id/s (automated). What do I need to do to make this the way I wanted to?

[SOLVED]

Note: Both etsa's and adam's answer solved my problem.

Body:
You can try this:

SELECT docs_list.url, docs_list.title
FROM docs_list
INNER JOIN saved_docs ON docs_list.id = saved_docs.doc_id
 WHERE saved_posts.user_id = {$user_id}
ORDER BY saved_docs.date DESC


问:
Python sort and sorted -- How are lists of lists sorted precisely?
What is the precise rule used in Python in order to sort lists where
the elements are lists? Can this be expressed as a 'key' or 'cmp'
function? The problems comes from the fact that there are two things
to consider: length and values at their position.

```<code>sorted([
   [ 0, 1, 2, 3 ],  # 1st line: longer list
   [ 0, 1 ],        # 2nd line: shorter list
   [ 0, 2 ]         # 3rd line: suspected last
])
</code>```

Is it safe to assume that the second line will sort before the first?
Is it safe to assume that the third line will sort always last?

Note, this is not about stability! The specific case above behaves
that way as described. But, can the rules there be considered to
be general? What are the precise rules which python applies here?

Relying on the following definition Lexicographical Order (Thanks to Ashniwi):

To compare sequences of different lengths, the shorter sequence is
  usually padded at the end with enough "blanks" (a special symbol that
  is treated as smaller than every element of A). This way of comparing
  sequences of different lengths is always used in dictionaries.
  However, in combinatorics, another convention is frequently used,
  whereby a shorter sequence is always smaller than a longer sequence.
  This variant of the lexicographical order is sometimes called shortlex
  order.

Is Python using 'shortlex order'. Where is proof for that assumption,
beyond practical examples?

答:
Quoting from docs:

In particular, tuples and lists are compared lexicographically by
  comparing corresponding elements. This means that to compare equal,
  every element must compare equal and the two sequences must be of the
  same type and have the same length.

Lexicographical comparison between built-in collections works as follows:

For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).

Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

The basic comparison done for lists can be expressed using this function:

```<code>def cmp(list_1, list_2):
    length_1 = len(list_1)
    length_2 = len(list_2)
    min_length = min(length_1, length_2)

    # Compare individual items till there's a different item found
    for i in xrange(min_length):
        if list_1[i] > list_2[i]:
            return 1
        elif list_1[i] < list_2[i]:
            return -1

    # All items were same so far, let's compare sizes.
    if length_1 > length_2:
        return 1
    elif length_1 < length_2:
        return -1
    elif length_1 == length_2:
        return 0
</code>```

Demo:

```<code>>>> lst = [[ 0, 1, 2, 3 ], [ 0, 1 ], [ 0, 2 ]]
>>> print sorted(lst) == sorted(lst, cmp=cmp)
True
</code>```

Related CPython code for reference:

```<code>/* Search for the first index where items are different */
for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
    int k = PyObject_RichCompareBool(vl->ob_item[i],
                                     wl->ob_item[i], Py_EQ);
    if (k < 0)
        return NULL;
    if (!k)
        break;
}

if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
    /* No more items to compare -- compare sizes */
    Py_ssize_t vs = Py_SIZE(vl);
    Py_ssize_t ws = Py_SIZE(wl);
    int cmp;
    PyObject *res;
    switch (op) {
    case Py_LT: cmp = vs <  ws; break;
    case Py_LE: cmp = vs <= ws; break;
    case Py_EQ: cmp = vs == ws; break;
    case Py_NE: cmp = vs != ws; break;
    case Py_GT: cmp = vs >  ws; break;
    case Py_GE: cmp = vs >= ws; break;
    default: return NULL; /* cannot happen */
    }
    if (cmp)
        res = Py_True;
    else
        res = Py_False;
    Py_INCREF(res);
    return res;
}
</code>```

Body:
What is the precise rule used in Python in order to sort lists where
the elements are lists? Can this be expressed as a 'key' or 'cmp'
function? The problems comes from the fact that there are two things
to consider: length and values at their position.

sorted([
   [ 0, 1, 2, 3 ],  # 1st line: longer list
   [ 0, 1 ],        # 2nd line: shorter list
   [ 0, 2 ]         # 3rd line: suspected last
])

Is it safe to assume that the second line will sort before the first?
Is it safe to assume that the third line will sort always last?

Note, this is not about stability! The specific case above behaves
that way as described. But, can the rules there be considered to
be general? What are the precise rules which python applies here?

Relying on the following definition Lexicographical Order (Thanks to Ashniwi):

To compare sequences of different lengths, the shorter sequence is
  usually padded at the end with enough "blanks" (a special symbol that
  is treated as smaller than every element of A). This way of comparing
  sequences of different lengths is always used in dictionaries.
  However, in combinatorics, another convention is frequently used,
  whereby a shorter sequence is always smaller than a longer sequence.
  This variant of the lexicographical order is sometimes called shortlex
  order.

Is Python using 'shortlex order'. Where is proof for that assumption,
beyond practical examples?

Body:
Quoting from docs:

In particular, tuples and lists are compared lexicographically by
  comparing corresponding elements. This means that to compare equal,
  every element must compare equal and the two sequences must be of the
  same type and have the same length.

Lexicographical comparison between built-in collections works as follows:

For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).

Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

The basic comparison done for lists can be expressed using this function:

def cmp(list_1, list_2):
    length_1 = len(list_1)
    length_2 = len(list_2)
    min_length = min(length_1, length_2)

    # Compare individual items till there's a different item found
    for i in xrange(min_length):
        if list_1[i] > list_2[i]:
            return 1
        elif list_1[i] < list_2[i]:
            return -1

    # All items were same so far, let's compare sizes.
    if length_1 > length_2:
        return 1
    elif length_1 < length_2:
        return -1
    elif length_1 == length_2:
        return 0

Demo:

>>> lst = [[ 0, 1, 2, 3 ], [ 0, 1 ], [ 0, 2 ]]
>>> print sorted(lst) == sorted(lst, cmp=cmp)
True

Related CPython code for reference:

/* Search for the first index where items are different */
for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
    int k = PyObject_RichCompareBool(vl->ob_item[i],
                                     wl->ob_item[i], Py_EQ);
    if (k < 0)
        return NULL;
    if (!k)
        break;
}

if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
    /* No more items to compare -- compare sizes */
    Py_ssize_t vs = Py_SIZE(vl);
    Py_ssize_t ws = Py_SIZE(wl);
    int cmp;
    PyObject *res;
    switch (op) {
    case Py_LT: cmp = vs <  ws; break;
    case Py_LE: cmp = vs <= ws; break;
    case Py_EQ: cmp = vs == ws; break;
    case Py_NE: cmp = vs != ws; break;
    case Py_GT: cmp = vs >  ws; break;
    case Py_GE: cmp = vs >= ws; break;
    default: return NULL; /* cannot happen */
    }
    if (cmp)
        res = Py_True;
    else
        res = Py_False;
    Py_INCREF(res);
    return res;
}


问:
not able to create controller by referencing to javascript file having module declared in it
I created angular module in a javascript file app.js as below:

var app = angular.module('myApp', []);

Further i went to the controller folder of my project and added a javascript file for Controllers.
Next i referenced the already created app.js file(which is havning module creation) in the first step and then i tried to create controller using it as in below lines:

```<code>/// <reference path="app.js" />
app.controller('myctrl', function ($scope) {
$scope.tesdtata = 'test';
})
</code>```

Now when i am binding the scope variable to UI and running the solution, i am getting exceptions as:  'app' not defined

Finally i am not able to vied the value of 'testdata' in browser.

Moreover when i type the line: app.controller(..)  the intellisence shows me some diffenet overload variables i.e. app.controller(recepiename,factoryfunction)   which is not correct.

Everything works fine if i create module individualy for every controller file and then using that create controller in same file. And problem occurs when i try to reference the single app.js file (having module creation it) and try to create controllers.

答:
Check if your UI(HTML file) looks something like this. That'll do.</p>

```<code><!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.min.js"></script>
    <script src="app.js"></script>
    <script src="control.js"></script>
</head>
<body ng-controller="myCtrl">
        {{testdata}}

</body>
</html>
</code>```

Body:
I created angular module in a javascript file app.js as below:

var app = angular.module('myApp', []);

Further i went to the controller folder of my project and added a javascript file for Controllers.
Next i referenced the already created app.js file(which is havning module creation) in the first step and then i tried to create controller using it as in below lines:

/// <reference path="app.js" />
app.controller('myctrl', function ($scope) {
$scope.tesdtata = 'test';
})

Now when i am binding the scope variable to UI and running the solution, i am getting exceptions as:  'app' not defined

Finally i am not able to vied the value of 'testdata' in browser.

Moreover when i type the line: app.controller(..)  the intellisence shows me some diffenet overload variables i.e. app.controller(recepiename,factoryfunction)   which is not correct.

Everything works fine if i create module individualy for every controller file and then using that create controller in same file. And problem occurs when i try to reference the single app.js file (having module creation it) and try to create controllers.

Body:
Check if your UI(HTML file) looks something like this. That'll do.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/angular.min.js"></script>
    <script src="app.js"></script>
    <script src="control.js"></script>
</head>
<body ng-controller="myCtrl">
        {{testdata}}

</body>
</html>


问:
Cannot determine current directory
I am trying to run a .jar file that was created successfully in Netbeans and I am receiving the following error:

Error occurred during initialization of VM java.lang.Error:
  Properties init: Could not determine current working directory. at
  java.lang.System.initProperties(Native Method) at
  java.lang.System.initializeSystemClass(System.java:1070)

The command that I type to run the .jar is

```<code>java -jar "/path to the dist forlder/EOPPrototype.jar"
</code>```

My classpath is as follows:

```<code>CLASSPATH=/opt/netbeans-7.1.2/ide/modules/ext/mysql-connector-java-5.1.13-     bin.jar:/h/USERS/local/pagola/NetBeansProjects/mylib/dist/mylib.jar:/h/USERS/local/pagola/NetBeansProjects/EOPPrototype/build/classes:.
</code>```

What am i missing?

答: I was having this error in my mac, when I start tomcat from my eclipse. After setting JAVA_HOME and restarting the eclipse, the error is fixed.</p>

Title: Cannot determine current directory

Body:
I am trying to run a .jar file that was created successfully in Netbeans and I am receiving the following error:

Error occurred during initialization of VM java.lang.Error:
  Properties init: Could not determine current working directory. at
  java.lang.System.initProperties(Native Method) at
  java.lang.System.initializeSystemClass(System.java:1070)

The command that I type to run the .jar is

java -jar "/path to the dist forlder/EOPPrototype.jar"

My classpath is as follows:

CLASSPATH=/opt/netbeans-7.1.2/ide/modules/ext/mysql-connector-java-5.1.13-     bin.jar:/h/USERS/local/pagola/NetBeansProjects/mylib/dist/mylib.jar:/h/USERS/local/pagola/NetBeansProjects/EOPPrototype/build/classes:.

What am i missing?


问:
How can I set password in aws EC2 instead of ppk file?
I have created a account in aws ec2 and logged in through converted ppk file with putty. Now I would like to login via password.

Here how can I set password?

Can any one provide step by step process.

Thanks in advance.

Please help!!

答:
Enable Password authentication in SSH by editing /etc/ssh/sshd_config.
--> change PasswordAuthentication no to PasswordAuthentication yes

Restart SSH Service
--> service sshd restart

Set a Strong password and open up a new terminal and access the instance with username and password.
--> passwd username


问:
Don't include dependencies from packages.config file when creating NuGet package
I am using Nuget to create packages. I would like to create a package which does not contain any dependencies (in the .nuspec) file to any other NuGet packages. My project does have NuGet package dependencies defined in its packages.config file.

First I create the .nuspec file...

```<code>C:\code\MySolution>.nuget\nuget.exe spec MyProject\MyProject.csproj
</code>```

I edit the generated .nuspec file to be minimal, with no dependencies.

```<code><?xml version="1.0"?>
<package >
  <metadata>
    <id>MyProject</id>
    <version>1.2.3</version>
    <title>MyProject</title>
    <authors>Example</authors>
    <owners>Example</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Example</description>
    <copyright>Copyright 2013 Example</copyright>
    <tags>example</tags>
    <dependencies />
  </metadata>
</package>
</code>```

Then I build the solution and create a NuGet package...

```<code>C:\code\MySolution>.nuget\nuget.exe pack MyProject\MyProject.csproj -Verbosity detailed
</code>```

Here is the output of that command...

```<code>Attempting to build package from 'MyProject.csproj'.
Packing files from 'C:\code\MySolution\MyProject\bin\Debug'.
Using 'MyProject.nuspec' for metadata.
Found packages.config. Using packages listed as dependencies

Id: MyProject
Version: 1.2.3
Authors: Example
Description: Example
Tags: example
Dependencies: Google.ProtocolBuffers (= 2.4.1.473)

Added file 'lib\net40\MyProject.dll'.

Successfully created package 'C:\code\MySolution\MyProject.1.2.3.nupkg'.
</code>```

The .nupkg package that is created has a .nuspec file contained within it but it includes a dependencies section which I did not have in the original .nuspec file...

```<code><dependencies>
  <dependency id="Google.ProtocolBuffers" version="2.4.1.473" />
</dependencies>
</code>```

I believe this is happening because of this... (from the output above)

```<code>Found packages.config. Using packages listed as dependencies
</code>```

How can I make NuGet not automatically resolve dependencies and insert them into the .nuspec file which is generated from the pack command?

I am using NuGet 2.2 currently. Also, I don't think that this behaviour happened in older version of NuGet; is this a new "feature"? I couldn't find any documentation describing this "feature" or when it was implemented.

答:
If you are using the PackageReference element instead of package.config file, here is the solution:

```<code><PackageReference Include="Nerdbank.GitVersioning" Version="1.5.28-rc" PrivateAssets="All" />
</code>```

or

```<code><PackageReference Include="Nerdbank.GitVersioning" Version="1.5.28-rc">
   <PrivateAssets>all</PrivateAssets>
</PackageReference>
</code>```

Related GitHub discussion

Body:
I am using Nuget to create packages. I would like to create a package which does not contain any dependencies (in the .nuspec) file to any other NuGet packages. My project does have NuGet package dependencies defined in its packages.config file.

First I create the .nuspec file...

C:\code\MySolution>.nuget\nuget.exe spec MyProject\MyProject.csproj

I edit the generated .nuspec file to be minimal, with no dependencies.

<?xml version="1.0"?>
<package >
  <metadata>
    <id>MyProject</id>
    <version>1.2.3</version>
    <title>MyProject</title>
    <authors>Example</authors>
    <owners>Example</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Example</description>
    <copyright>Copyright 2013 Example</copyright>
    <tags>example</tags>
    <dependencies />
  </metadata>
</package>

Then I build the solution and create a NuGet package...

C:\code\MySolution>.nuget\nuget.exe pack MyProject\MyProject.csproj -Verbosity detailed

Here is the output of that command...

Attempting to build package from 'MyProject.csproj'.
Packing files from 'C:\code\MySolution\MyProject\bin\Debug'.
Using 'MyProject.nuspec' for metadata.
Found packages.config. Using packages listed as dependencies

Id: MyProject
Version: 1.2.3
Authors: Example
Description: Example
Tags: example
Dependencies: Google.ProtocolBuffers (= 2.4.1.473)

Added file 'lib\net40\MyProject.dll'.

Successfully created package 'C:\code\MySolution\MyProject.1.2.3.nupkg'.

The .nupkg package that is created has a .nuspec file contained within it but it includes a dependencies section which I did not have in the original .nuspec file...

<dependencies>
  <dependency id="Google.ProtocolBuffers" version="2.4.1.473" />
</dependencies>

I believe this is happening because of this... (from the output above)

Found packages.config. Using packages listed as dependencies

How can I make NuGet not automatically resolve dependencies and insert them into the .nuspec file which is generated from the pack command?

I am using NuGet 2.2 currently. Also, I don't think that this behaviour happened in older version of NuGet; is this a new "feature"? I couldn't find any documentation describing this "feature" or when it was implemented.

Body:
If you are using the PackageReference element instead of package.config file, here is the solution:

<PackageReference Include="Nerdbank.GitVersioning" Version="1.5.28-rc" PrivateAssets="All" />

or

<PackageReference Include="Nerdbank.GitVersioning" Version="1.5.28-rc">
   <PrivateAssets>all</PrivateAssets>
</PackageReference>

Related GitHub discussion


问:
ComponentNotFound exception Castle.Windsor
I am trying to get started with Castle.Windsor and following a comment I made on the samples currently available for newbies (http://stw.castleproject.org/Windsor.Silvertlight_Sample_App_Customer_contact_manager.ashx?Discuss=1), I thought I'd take the bull by the horns and update the example provided here http://dotnetslackers.com/articles/designpatterns/InversionOfControlAndDependencyInjectionWithCastleWindsorContainerPart1.aspx.

This is a simple and fairly straightforward console application making use of Castle Windsor, albeit an outdated version. My Main method in Program.cs is as follows:

```<code>public static void Main()
    {
        IWindsorContainer container = new WindsorContainer();

        container.Install(FromAssembly.This());
        var retriever = container.Resolve<IHtmlTitleRetriever>();

        Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));

        Console.Read();

        container.Dispose();
    }
</code>```

and the Service and Components, which are all in the same file i.e. Program.cs are thus:

```<code>public interface IHtmlTitleRetriever
{
    string GetTitle(Uri file);

}

public interface IFileDownloader
{
    string Download(Uri file);
}

public interface ITitleScraper
{
    string Scrape(string fileContents);
}

public class HtmlTitleRetriever: IHtmlTitleRetriever
{
    private readonly IFileDownloader _downloader;
    private readonly ITitleScraper _scraper;

    public HtmlTitleRetriever(IFileDownloader dowloader, ITitleScraper scraper)
    {
        _downloader = dowloader;
        _scraper = scraper;
    }

    public string GetTitle(Uri file)
    {
        string fileContents = _downloader.Download(file);
        return _scraper.Scrape(fileContents);
    }
}

public class HttpFileDownloader : IFileDownloader
{
    public string Download(Uri file)
    {
        return new WebClient().DownloadString(file);
    }
}

public class StringParsingTitleScraper : ITitleScraper
{
    public string Scrape(string fileContents)
    {
        string title = string.Empty;
        int openingTagIndex = fileContents.IndexOf("<title>");
        int closingTagIndex = fileContents.IndexOf("</title>");

        if(openingTagIndex != -1 && closingTagIndex != -1)
            title = fileContents.Substring(openingTagIndex, closingTagIndex - openingTagIndex).Substring(7);

        return title;
    }
}
</code>```

It is pretty much a straight copy of what Simone Busoli has from his example. The code compiles fine but I get the following error when I run the application:

No component for supporting the service WindsorSample.IHtmlTitleRetriever was found

I understand what that means but I don't know what I'm doing wrong that the components are not getting loaded into the container. I'm using Castle.Windsor 2.5.2 and .NET 4.0.

Looking forward to the answers,

David

答:
First of all - awesome you're updating the sample. As you mentioned, an even smaller sample, without Silverlight overhead will certainly be useful.

As for your question - the exception means that the service you requested, IHtmlTitleRetriever is not supported by any component you registered, in other words - you didn't seem to have registered IHtmlTitleRetriever in the container at all. How does your installer look like? To check if components get registered properly you can put a breakpoint in the line after you call Install and see what components were registered, and if that's what you were expecting. It's quite useful for quickly diagnosing issues like the one you're having. (see the documentation here).

If you're still not sure what the reason is, make sure your installer classes are all public, and post their code here so that we can try to figure out what's the reason.

Body:
I am trying to get started with Castle.Windsor and following a comment I made on the samples currently available for newbies (http://stw.castleproject.org/Windsor.Silvertlight_Sample_App_Customer_contact_manager.ashx?Discuss=1), I thought I'd take the bull by the horns and update the example provided here http://dotnetslackers.com/articles/designpatterns/InversionOfControlAndDependencyInjectionWithCastleWindsorContainerPart1.aspx.

This is a simple and fairly straightforward console application making use of Castle Windsor, albeit an outdated version. My Main method in Program.cs is as follows:

public static void Main()
    {
        IWindsorContainer container = new WindsorContainer();

        container.Install(FromAssembly.This());
        var retriever = container.Resolve<IHtmlTitleRetriever>();

        Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));

        Console.Read();

        container.Dispose();
    }

and the Service and Components, which are all in the same file i.e. Program.cs are thus:

public interface IHtmlTitleRetriever
{
    string GetTitle(Uri file);

}

public interface IFileDownloader
{
    string Download(Uri file);
}

public interface ITitleScraper
{
    string Scrape(string fileContents);
}

public class HtmlTitleRetriever: IHtmlTitleRetriever
{
    private readonly IFileDownloader _downloader;
    private readonly ITitleScraper _scraper;

    public HtmlTitleRetriever(IFileDownloader dowloader, ITitleScraper scraper)
    {
        _downloader = dowloader;
        _scraper = scraper;
    }

    public string GetTitle(Uri file)
    {
        string fileContents = _downloader.Download(file);
        return _scraper.Scrape(fileContents);
    }
}

public class HttpFileDownloader : IFileDownloader
{
    public string Download(Uri file)
    {
        return new WebClient().DownloadString(file);
    }
}

public class StringParsingTitleScraper : ITitleScraper
{
    public string Scrape(string fileContents)
    {
        string title = string.Empty;
        int openingTagIndex = fileContents.IndexOf("<title>");
        int closingTagIndex = fileContents.IndexOf("</title>");

        if(openingTagIndex != -1 && closingTagIndex != -1)
            title = fileContents.Substring(openingTagIndex, closingTagIndex - openingTagIndex).Substring(7);

        return title;
    }
}

It is pretty much a straight copy of what Simone Busoli has from his example. The code compiles fine but I get the following error when I run the application:

No component for supporting the service WindsorSample.IHtmlTitleRetriever was found

I understand what that means but I don't know what I'm doing wrong that the components are not getting loaded into the container. I'm using Castle.Windsor 2.5.2 and .NET 4.0.

Looking forward to the answers,

David


问:
How can I increase the maximum call stack size in Node.js
This is different to other questions regarding an error message in Node that reads RangeError: Maximum call stack size exceeded in that I know exactly why I'm getting this error message. It's happening because I'm recursing, recursing quite a lot in fact.

Thanks.

答:
In node version 5 and 6, I have verified that the option to set maximum stack size is "--stack_size" (with an underscore):

```<code>$  node --v8-options
[...]
--stack_size (default size of stack region v8 is allowed to use (in kBytes))
      type: int  default: 984
</code>```

To increase the maximum stack size, just issue something like:

```<code>$ node --stack_size=1200
</code>```

As noted by others, be aware that increasing this value may lead to a segmentation fault. The maximum safe value for me with version 6 is 1361, but seems higher with version 5.

Looking at the bigger picture, increasing stack size may not solve all your issues. When writing recursive functions in node, your best strategy is to write them in a tail-recursive manner, since version 6 supports proper tail calls. This will eliminate stack size overflows.

Update: the comment about tail calls doesn't apply to Node.js anymore. They've removed tail-call optimization from the engine in version 8. See this answer for some more info.

Body:
In node version 5 and 6, I have verified that the option to set maximum stack size is "--stack_size" (with an underscore):

$  node --v8-options
[...]
--stack_size (default size of stack region v8 is allowed to use (in kBytes))
      type: int  default: 984

To increase the maximum stack size, just issue something like:

$ node --stack_size=1200

As noted by others, be aware that increasing this value may lead to a segmentation fault. The maximum safe value for me with version 6 is 1361, but seems higher with version 5.

Looking at the bigger picture, increasing stack size may not solve all your issues. When writing recursive functions in node, your best strategy is to write them in a tail-recursive manner, since version 6 supports proper tail calls. This will eliminate stack size overflows.

Update: the comment about tail calls doesn't apply to Node.js anymore. They've removed tail-call optimization from the engine in version 8. See this answer for some more info.


问:
PrimeFaces DialogFramework top positioning
I use PrimeFaces 6 and want to position the dialog on top:

options.put("position", "top");

However this does not work. Is there any way to center the dialog on top?

I am quite desperate now

答:
I know, you would like to set position to primefaces external dialog(dialog framework).
You cannot style or css to dialog because which is wrap by ifram.

But, it is OK to apply css to generated div. This div id is formId + commendLinkId or commendButtonId + _dlg

Example

```<code><h:form id="myForm">

    <p:commandButton id="myDialgoBtm" value="Select" action="...." immediate="true">
        <p:ajax ..../>
    </p:commandButton>

</h:form>
</code>```

Client/Brower Source

```<code><div id="myForm:myDialogBtn_dlg" ..>
    <div ....>
        //this is bor title bar of dialog
    </div>
    <div ....>
        //this is bor content of dialog
        <ifarm ....>
            //here your external dialog page
        </ifarm>
    </div>
</div>
</code>```

if so, the id of div will be myForm:myDialogBtn_dlg. You can inspect in browser.

Example CSS for your dialog

```<code>#myForm\:myDialogBtn_dlg {
    top: 0px!important
}
</code>```

I don't think, it will be better solution, Currently, I solve this issue by above way.

Body:
I know, you would like to set position to primefaces external dialog(dialog framework).
You cannot style or css to dialog because which is wrap by ifram.

But, it is OK to apply css to generated div. This div id is formId + commendLinkId or commendButtonId + _dlg

Example

<h:form id="myForm">

    <p:commandButton id="myDialgoBtm" value="Select" action="...." immediate="true">
        <p:ajax ..../>
    </p:commandButton>

</h:form>

Client/Brower Source

<div id="myForm:myDialogBtn_dlg" ..>
    <div ....>
        //this is bor title bar of dialog
    </div>
    <div ....>
        //this is bor content of dialog
        <ifarm ....>
            //here your external dialog page
        </ifarm>
    </div>
</div>

if so, the id of div will be myForm:myDialogBtn_dlg. You can inspect in browser.

Example CSS for your dialog

#myForm\:myDialogBtn_dlg {
    top: 0px!important
}

I don't think, it will be better solution, Currently, I solve this issue by above way.


问:
Create a form dynamically with jquery and submit
I am trying to create a form dynamically via jquery and submit it to a PHP file. This creates the form but nothing happens when i click the submit button. What is going wrong here ?

Method i am using to create a form dynamically is :-

```<code>    $('#share').append("<form action='sharer.php' method='POST'/>");
    $('#share').append("<div class= 'appm'>Save this/div/>");
    $('#share').append("<input type='text' placeholder='Name' name='routename' id='rname'/>");
    $('#share').append("<input type='text' placeholder='description' id='rdescription' name='routedescription' class= 'address'/>");
    $('#share').append("<input type='text' placeholder='tags' id='tags' name='routetags'  />");
    $('#share').append("<br><input type='submit' id='savebutton' value = 'Save' />");
    $('#share').append("</form>");
</code>```

答:
I would submit the form using the jQuery on() method, it allows you to bind events to dynamically created elements anchored by static elements such as the body tag

```<code>$("body").on("submit", "#share form", function(event){
    event.preventDefault();
});
</code>```

In your case, if the form isn't submitting I would use ajax to submit the form instead of the standard form submit. You could even execute a javascript page refresh after its done if you want a refresh to happen

```<code>$("body").on("submit", "#share form", function(event){
    event.preventDefault();
    // Grab all form data
    var formInputData = $(this).serializeObject();
    // send form data to php file in $_POST array
    $.post("sharer.php", formInputData, function(data){
        // log errors or anything that is echoed back from php file
        console.log(data);
        // refresh the page
        window.location.reload();
    });
});
</code>```

Don't forget to put it all in a document ready function and have the jQuery library included in your HTML head tag

```<code>$(document).ready(function(){
    $("body").on("submit", "#share form", function(event){
        event.preventDefault();
        // Grab all form data
        var formInputData = $(this).serializeObject();
        // send form data to php file in $_POST array
        $.post("sharer.php", formInputData, function(data){
            // log errors or anything that is echoed back from php file
            console.log(data);
            // refresh the page
            window.location.reload();
        });
    });
});
</code>```

jQuery include example

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</code>```

Body:
I am trying to create a form dynamically via jquery and submit it to a PHP file. This creates the form but nothing happens when i click the submit button. What is going wrong here ?

Method i am using to create a form dynamically is :-

    $('#share').append("<form action='sharer.php' method='POST'/>");
    $('#share').append("
Save this/div/>");
    $('#share').append("<input type='text' placeholder='Name' name='routename' id='rname'/>");
    $('#share').append("<input type='text' placeholder='description' id='rdescription' name='routedescription' class= 'address'/>");
    $('#share').append("<input type='text' placeholder='tags' id='tags' name='routetags'  />");
    $('#share').append("
<input type='submit' id='savebutton' value = 'Save' />");
    $('#share').append("</form>");

Body:
I would submit the form using the jQuery on() method, it allows you to bind events to dynamically created elements anchored by static elements such as the body tag

$("body").on("submit", "#share form", function(event){
    event.preventDefault();
});

In your case, if the form isn't submitting I would use ajax to submit the form instead of the standard form submit. You could even execute a javascript page refresh after its done if you want a refresh to happen

$("body").on("submit", "#share form", function(event){
    event.preventDefault();
    // Grab all form data
    var formInputData = $(this).serializeObject();
    // send form data to php file in $_POST array
    $.post("sharer.php", formInputData, function(data){
        // log errors or anything that is echoed back from php file
        console.log(data);
        // refresh the page
        window.location.reload();
    });
});

Don't forget to put it all in a document ready function and have the jQuery library included in your HTML head tag

$(document).ready(function(){
    $("body").on("submit", "#share form", function(event){
        event.preventDefault();
        // Grab all form data
        var formInputData = $(this).serializeObject();
        // send form data to php file in $_POST array
        $.post("sharer.php", formInputData, function(data){
            // log errors or anything that is echoed back from php file
            console.log(data);
            // refresh the page
            window.location.reload();
        });
    });
});

jQuery include example

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


问:
The best way to let asp.net fire events and methods automatically -according to a schedule-
Well, I'm sure this is not the first time to see this question. and TBH you can find this question answered on many other websites and blogs -not only here-

But I never saw a complete answer for this question, I mean no one talked about the advantages and the disadvantages. no one shared a real experience.

Although Quartz.NET seems like a good solution but yet, there's no enough reviews or a good comparison between the different ways to achieve such a thing.

As far as I read about it I found this are the possible ways of doing this :

Using a:  Web Service, Windows Appliction, Console Application, Quartz.NET.

Examples of stuff I want to achieve with the scheduled or automatic methods/events are like archiving after a certain period, auto deleting/moving records in the database, setting a property of an object after a certain time, automatically run some methods according to my holiday schedule.

I hope you'd share your experience either with one of those approaches or share a new way of doing this.

答:
At the e-commerce Web site that I work for, we use Quartz.NET in a Windows service called the "Worker". It executes Quartz.NET IJob implementations via the programmatically-defined schedule and runs independently of the Web site processes. It does things like dispatch e-mails in batches, update statistics, refresh the SOLR indexes, and so on.

This way, we don't have to worry about our schedules getting reset or missed as a result of worker processes recycling, or dealing with the madness of having multiple instances running simultaneously on the same machine as a result of a Web garden. The Worker is installed, started, and stopped independently of the Web site, and could even exist on a separate machine, giving flexibility in maintenance and deployment.

The Web site and the Worker both share a common Model DLL that contains the object model and NHibernate configuration, so there is not much logical duplication of business logic.

Before I created the Worker/Windows service, I relied on simple console applications that were executed via scheduled tasks. This worked well up to a point, but as the site became more complex and required more and more batch jobs to run periodically, I found myself maintaining a lot of independent console programs and a lot of independent scheduled tasks, which became more difficult as the number of jobs required increased. By consolidating scheduling with Quartz.NET into a single Windows service, I now only have one process to keep an eye on and can be assured that any business logic changes are "in sync" since the model only has to be updated in two places--the Worker and the Web site--instead of many--the Web site and lots of little console applications.

I explored options like storing runtimes in the ASP.NET cache or keeping references around in the worker process's memory, but I found that (1) this made the exact execution time of the task dependent on incoming requests to the Web site and (2) the use of a Web garden caused unnecessary duplication of effort (since the task would be "scheduled" in multiple worker processes on the same machine).

Creating a Windows service that can be started and stopped via the usual Windows mechanisms has proved to be, in my humble opinion, the most logical, intuitive, and maintainable result in the long run.

Both the Web site and Worker use WiX to compile down to two Windows Installer MSI files, so updating them is a snap--just double-click the MSI on the server, and our update is good to go.

Hope that helps!


问:
Pass an argument to task in C++/CLI?
I have this code for the C# in Visual Studio 2012.

```<code>public Task SwitchLaserAsync(bool on)
{
   return Task.Run(new Action(() => SwitchLaser(on)));
}
</code>```

This will execute SwitchLaser method (public nonstatic member of a class MyClass) as a task with argument bool on.

I would like to do something similar in managed C++/CLI. But I am not able to find out any way how to run a task, which will execute a member method taking one parameter.

Current solution is like this:

```<code>Task^ MyClass::SwitchLaserAsync( bool on )
{
    laserOn = on;   //member bool
    return Task::Run(gcnew Action(this, &MyClass::SwitchLaserHelper));
}
</code>```

Implementation of SwitchLaserHelper function:

```<code>void MyClass::SwitchLaserHelper()
{
     SwitchLaser(laserOn);
}
</code>```

There must be some solution like in C# and not to create helper functions and members (this is not threadsafe).

答:
I had a similar problem when I wanted to provide a parameter to a task executing a method which does not return a value (retuns void). Because of that Func<T, TResult> was not an option I could use. For more information, please check the page Using void return types with new Func.

So I ended up with a solution where I created a helper class

```<code>template <typename T>
ref class ActionArguments
{
public:
    ActionArguments(Action<T>^ func, T args) : m_func(func), m_args(args) {};
    void operator()() { m_func(m_args); };

private:
    Action<T>^ m_func;
    T m_args;
};
</code>```

which is using Action<T> delegate to encapsulate a method that has a single parameter and does not return a value.

I would then use this helper class in a following way

```<code>ref class DisplayActivationController
{
public:
    DisplayActivationController();

    void StatusChanged(EventArgs^ args) { };
}

Action<EventArgs^>^ action =
    gcnew Action<EventArgs^>(this, &DisplayActivationController::StatusChanged);
ActionArguments<EventArgs^>^ action_args =
    gcnew ActionArguments<EventArgs^>(action, args);
Threading::Tasks::Task::Factory->
    StartNew(gcnew Action(action_args, &ActionArguments<EventArgs^>::operator()));
</code>```

Approach using the helper class is probably not the most elegant solution, but is the best one I could find to be used in C++/CLI which does not support lambda expressions.

Title: Pass an argument to task in C++/CLI?

Body:
I have this code for the C# in Visual Studio 2012.

public Task SwitchLaserAsync(bool on)
{
   return Task.Run(new Action(() => SwitchLaser(on)));
}

This will execute SwitchLaser method (public nonstatic member of a class MyClass) as a task with argument bool on.

I would like to do something similar in managed C++/CLI. But I am not able to find out any way how to run a task, which will execute a member method taking one parameter.

Current solution is like this:

Task^ MyClass::SwitchLaserAsync( bool on )
{
    laserOn = on;   //member bool
    return Task::Run(gcnew Action(this, &MyClass::SwitchLaserHelper));
}

Implementation of SwitchLaserHelper function:

void MyClass::SwitchLaserHelper()
{
     SwitchLaser(laserOn);
}

There must be some solution like in C# and not to create helper functions and members (this is not threadsafe).

Body:
I had a similar problem when I wanted to provide a parameter to a task executing a method which does not return a value (retuns void). Because of that Func<T, TResult> was not an option I could use. For more information, please check the page Using void return types with new Func.

So I ended up with a solution where I created a helper class

template <typename T>
ref class ActionArguments
{
public:
    ActionArguments(Action<T>^ func, T args) : m_func(func), m_args(args) {};
    void operator()() { m_func(m_args); };

private:
    Action<T>^ m_func;
    T m_args;
};

which is using Action<T> delegate to encapsulate a method that has a single parameter and does not return a value.

I would then use this helper class in a following way

ref class DisplayActivationController
{
public:
    DisplayActivationController();

    void StatusChanged(EventArgs^ args) { };
}

Action<EventArgs^>^ action =
    gcnew Action<EventArgs^>(this, &DisplayActivationController::StatusChanged);
ActionArguments<EventArgs^>^ action_args =
    gcnew ActionArguments<EventArgs^>(action, args);
Threading::Tasks::Task::Factory->
    StartNew(gcnew Action(action_args, &ActionArguments<EventArgs^>::operator()));

Approach using the helper class is probably not the most elegant solution, but is the best one I could find to be used in C++/CLI which does not support lambda expressions.


问:
502 Bad Gateway on POST/PUT Web API Calls from ASP.NET Core MVC
I'm getting strange errors in ASP.NET Core when calling Web API that I have created for the application. GET requests go through fine and return all of the data that they should, but my POST/PUT commands all return a 502, specifically from the MVC application. I can call the API's from Postman and get a proper response and the object is created in the database.

502 - Web server received an invalid response while acting as a
  gateway or proxy server. There is a problem with the page you are
  looking for, and it cannot be displayed. When the Web server (while
  acting as a gateway or proxy) contacted the upstream content server,
  it received an invalid response from the content server.

I am impersonating an Integrated Windows Login with the following code for all web requests to the API:

```<code>async Task Action()
{
    response = await _service.CreateIncident(model);
}

await WindowsIdentity.RunImpersonated(identity.AccessToken, Action);
</code>```

CreateIncident(model):

```<code>using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
        {
            var newIncident = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
            var response = await client.PostAsync(hostUri, newIncident);
            return response;
        }
</code>```

There is also one GET Request that I make through Ajax to get an incremented ID to display to the user before they create their new Incident that returns a 502 Bad Gateway as well. Is this an IIS Setting that is incorrect?

答: I think it also depends on the size of the data. Smaller packages work, larger ones don't.</p>

Body:
I'm getting strange errors in ASP.NET Core when calling Web API that I have created for the application. GET requests go through fine and return all of the data that they should, but my POST/PUT commands all return a 502, specifically from the MVC application. I can call the API's from Postman and get a proper response and the object is created in the database.

502 - Web server received an invalid response while acting as a
  gateway or proxy server. There is a problem with the page you are
  looking for, and it cannot be displayed. When the Web server (while
  acting as a gateway or proxy) contacted the upstream content server,
  it received an invalid response from the content server.

I am impersonating an Integrated Windows Login with the following code for all web requests to the API:

async Task Action()
{
    response = await _service.CreateIncident(model);
}

await WindowsIdentity.RunImpersonated(identity.AccessToken, Action);

CreateIncident(model):

using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
        {
            var newIncident = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
            var response = await client.PostAsync(hostUri, newIncident);
            return response;
        }

There is also one GET Request that I make through Ajax to get an incremented ID to display to the user before they create their new Incident that returns a 502 Bad Gateway as well. Is this an IIS Setting that is incorrect?


问:
Send SQL Query output to email using PowerShell
I want to send SQL query output to email using PowerShell, how can I do this?

Here is what I have so far:

```<code>$query =  select name, surname, gender, accountNumber from table1
$Report = Invoke-Sqlcmd -ServerInstance "instance" -Database "db2" -Query $query

$MailUsername = "mail"
$MailPassword = "1234"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
Send-MailMessage -To "me@yahoo.com" -From "you@yahoo.com" -SmtpServer mail.net -Credential $cred -Subject "weekly Report:" -Body "$Report"
</code>```

I want to be able to send the report in form of a table or something that looks nice? How can I do that?

My code above is running into errors, can anyone help me please?

答:
Adding an attachment was all I needed, please see below:   </p>

```<code> $message = new-object System.Net.Mail.MailMessage
            $message.From = $fromaddress
            $message.To.Add($toaddress)
            $message.CC.Add($CCaddress)
            $message.Bcc.Add($bccaddress)
            $message.IsBodyHtml = $True
            $message.Subject = $Subject
            $attach = new-object Net.Mail.Attachment($attachment)
            $message.Attachments.Add($attach)
            $message.body = $body
            $smtp = new-object Net.Mail.SmtpClient($smtpserver)
            $smtp.Send($message)
</code>```

Body:
I want to send SQL query output to email using PowerShell, how can I do this?

Here is what I have so far:

$query =  select name, surname, gender, accountNumber from table1
$Report = Invoke-Sqlcmd -ServerInstance "instance" -Database "db2" -Query $query

$MailUsername = "mail"
$MailPassword = "1234"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
Send-MailMessage -To "me@yahoo.com" -From "you@yahoo.com" -SmtpServer mail.net -Credential $cred -Subject "weekly Report:" -Body "$Report"

I want to be able to send the report in form of a table or something that looks nice? How can I do that?

My code above is running into errors, can anyone help me please?

Body:
Adding an attachment was all I needed, please see below:

 $message = new-object System.Net.Mail.MailMessage
            $message.From = $fromaddress
            $message.To.Add($toaddress)
            $message.CC.Add($CCaddress)
            $message.Bcc.Add($bccaddress)
            $message.IsBodyHtml = $True
            $message.Subject = $Subject
            $attach = new-object Net.Mail.Attachment($attachment)
            $message.Attachments.Add($attach)
            $message.body = $body
            $smtp = new-object Net.Mail.SmtpClient($smtpserver)
            $smtp.Send($message)


问:
Spock framework throwing error while mocking a @component
I am using Spock with Spring and I am getting error while mocking one of my component class.

Please find the below stack trace.
It has nothing more than this and I thus I am not able to proceed.
Versions:

cglib-nodep : 3.2.0

cglib : 3.2.0

spock-core : 1.0-groovy-2.4

spring-test : 4.1.4.RELEASE

java.lang.NoClassDefFoundError: Could not initialize class org.spockframework.mock.runtime.ProxyBasedMockFactory$CglibMockFactory$ConstructorFriendlyEnhancer
at org.spockframework.mock.runtime.ProxyBasedMockFactory$CglibMockFactory.createMock(ProxyBasedMockFactory.java:80)
at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:49)
at org.spockframework.mock.runtime.JavaMockFactory.create(JavaMockFactory.java:51)
at org.spockframework.mock.runtime.CompositeMockFactory.create(CompositeMockFactory.java:44)
at org.spockframework.lang.SpecInternals.createMock(SpecInternals.java:45)
at org.spockframework.lang.SpecInternals.createMockImpl(SpecInternals.java:281)
at org.spockframework.lang.SpecInternals.MockImpl(SpecInternals.java:99)
at TermsAndConditionsControllerAPISpec.setup(TermsAndConditionsControllerAPISpec.groovy:19)

答:
Not sure why this happened but I just removed cglib and it just worked.
So final dependency list was :
cglib-nodep : 3.2.0
spock-core : 1.0-groovy-2.4
spring-test : 4.1.4.RELEASE

I am still not sure why this worked by removing cglib. In case someone has a detailed reason for this please share.


问:
Icons appear too small on Bootstrap navbar
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

```<code><header>
  <nav class = "navbar navbar-default navbar-fixed-top">
    <div class = "container">
      <div class = "navbar-header">
        <a class = "navbar-brand" href = "#">
          BRAND
        </a>
      </div>
      <ul class = "nav navbar-nav navbar-right">
        <li class = "text"><a href="#">ABCD</a></li>
        <li class = "text"><a href="#">EFGH</a></li>
        <li class = "text"><a href="#">IJKL</a></li>
        <li class = "text"><a href="#">MNOP</a></li>
        <li><i class = "fa fa-facebook"></i><li/>
        <li><i class = "fa fa-twitter"> </i><li/>
        <li><i class = "fa fa-instagram"> </i><li/>
      </ul>
    </div>
  </nav>
</header>
</code>```

答:
```<code>Try any of these classes => fa-lg,fa-2x,fa-3x,fa-4x,fa-5x .

Example :

<i class="fa fa-camera-retro fa-lg"></i> fa-lg
<i class="fa fa-camera-retro fa-2x"></i> fa-2x
<i class="fa fa-camera-retro fa-3x"></i> fa-3x
<i class="fa fa-camera-retro fa-4x"></i> fa-4x
<i class="fa fa-camera-retro fa-5x"></i> fa-5x
</code>```

Body:
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

          BRAND

ABCD

EFGH

IJKL

MNOP