问:
Windows Authentication Issue going from Edge to Edge Chromium
The problem

I have a web forms application that is a management application to monitor other applications on the network. Currently this is used in edge or internet explorer, but we will be using edge chromium in the near future.

It is using windows authentication at the moment and works ok on edge and internet explorer, however there is an edge in edge chromium.

When run the application everything is fine, but when i go to a new page i get prompted to enter my windows credentials. When i do this it does not work and simply asks again.

Enter Windows Credentials

Below is the authorization area of my web config.

```<code>  <authorization>
    <remove users="*" roles="" verbs="" />
    <add accessType="Allow" users="" roles="Sample group inserted here" />
  </authorization>
</code>```

If i hit cancel then i receive a 401. Below are the response and request headers. I did check these on IE as well and when it is trying to load this template it fails twice then succeeds on the third attempt.

Headers

I have tried adjusting the authorization area and look at it on all browsers.

Expected result

I would expect once i run the application my identity is recognised and i can go to any area without being prompted.

Here is my complete web config

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>

  </configSections>
  <appSettings>
    <add key="" value="https://localhost:44386" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="OracleUser" value="" />
    <add key="OraclePassword" value="" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.7.1" />
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <machineKey decryptionKey="Left out on purpose" validationKey="Left out on purpose" />
    <identity impersonate="true" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" users="" roles="Left out on purpose" />
      </authorization>
    </security>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.112.3.0" newVersion="4.112.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>```
</div>
</div>
</p>

<p>Successful request IE
IE 200</p>

<p>First 401 IE</p>

<p>First 401 IE</p>

<p>Second 401 IE</p>

<p>Second 401</p>

<p>I managed to find a solution (working locally in visual studio). I moved the authorization second to system.web and changed it to this. However this still only works in IE when i deploy to iis.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <authorization>
      <allow roles="" />
      <deny users="*" />
    </authorization></code>```

from this

  <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" users="" roles="" />
      </authorization>
    </security>```
</div>
</div>
</p>

<p>I would appreciate some information on this. I am not a web forms developer.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="" value="https://localhost:44386" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="OracleUser" value="" />
    <add key="OraclePassword" value="" />
  </appSettings>
  <!--
    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.7.1" />
      </system.Web>
  -->
  <system.web>
    <compilation debug="true" targetFramework="4.7.1" />
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <machineKey decryptionKey="" validationKey="" />
    <identity impersonate="false" />
    <authorization>
      <allow roles="Removed deliberately" />
      <deny users="*" />
    </authorization>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.112.3.0" newVersion="4.112.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration></code>```

答:
Perhaps the syntax is wrong? Try</p>

```<code><authorization>
        <deny users="*" />
        <allow roles="role" />
</authorization>
</code>```

Body:
The problem

I have a web forms application that is a management application to monitor other applications on the network. Currently this is used in edge or internet explorer, but we will be using edge chromium in the near future.

It is using windows authentication at the moment and works ok on edge and internet explorer, however there is an edge in edge chromium.

When run the application everything is fine, but when i go to a new page i get prompted to enter my windows credentials. When i do this it does not work and simply asks again.

Enter Windows Credentials

Below is the authorization area of my web config.

  <authorization>
    <remove users="*" roles="" verbs="" />
    <add accessType="Allow" users="" roles="Sample group inserted here" />
  </authorization>

If i hit cancel then i receive a 401. Below are the response and request headers. I did check these on IE as well and when it is trying to load this template it fails twice then succeeds on the third attempt.

Headers

I have tried adjusting the authorization area and look at it on all browsers.

Expected result

I would expect once i run the application my identity is recognised and i can go to any area without being prompted.

Here is my complete web config

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>

  </configSections>
  <appSettings>
    <add key="" value="https://localhost:44386" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="OracleUser" value="" />
    <add key="OraclePassword" value="" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.7.1" />
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <machineKey decryptionKey="Left out on purpose" validationKey="Left out on purpose" />
    <identity impersonate="true" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" users="" roles="Left out on purpose" />
      </authorization>
    </security>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.112.3.0" newVersion="4.112.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

Successful request IE
IE 200

First 401 IE

First 401 IE

Second 401 IE

Second 401

I managed to find a solution (working locally in visual studio). I moved the authorization second to system.web and changed it to this. However this still only works in IE when i deploy to iis.

 <authorization>
      <allow roles="" />
      <deny users="*" />
    </authorization>

from this

  <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" users="" roles="" />
      </authorization>
    </security>

I would appreciate some information on this. I am not a web forms developer.

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>

  </configSections>
  <appSettings>
    <add key="" value="https://localhost:44386" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="OracleUser" value="" />
    <add key="OraclePassword" value="" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.7.1" />
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <machineKey decryptionKey="" validationKey="" />
    <identity impersonate="false" />
    <authorization>
      <allow roles="Removed deliberately" />
      <deny users="*" />
    </authorization>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.112.3.0" newVersion="4.112.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

Body:
Perhaps the syntax is wrong? Try

<authorization>
        <deny users="*" />
        <allow roles="role" />
</authorization>


来源: stackexchange

问:
Laravel having column name in where clause static method
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

```<code>$user = User::whereName('john')->first(); // added `name` as a column name
</code>```

When called this code to SQL it generates

```<code>$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?
</code>```

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

答:
you need to define this function in your model

```<code>//controller
$userObj=new \App\User();
$userObj->whereName('john');
//model
function whereName($name){
return $this->where('name',$name)->first();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

$user = User::whereName('john')->first(); // added `name` as a column name

When called this code to SQL it generates

$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

Body:
you need to define this function in your model

//controller
$userObj=new \App\User();
$userObj->whereName('john');
//model
function whereName($name){
return $this->where('name',$name)->first();
}


问:
Core MVC - Ajax unobtrusive does not exist
In my Core MVC 2.2 project I added jQuery Unobtrusive Ajax (v: 3.2.6) via Nuget packages. First thing I noticed there was no local folder added for it in wwwroot/lib, also if try something simple like:

@using (Ajax.BeginForm( ...
```

I get an error: CS0103 The name 'Ajax' does not exist in the current context

Please advise how to fix this.

答:
Installing packages via the NuGet Package Manager in windows will install them to the .nuget location on your machine.  In the case of unobtrusive-ajax this should be something like %userprofile%.nuget\packages\microsoft.jquery.unobtrusive.ajax

This folder can then be copied to wwwroot\lib as specified in Nan Yu's answer.

Body:
In my Core MVC 2.2 project I added jQuery Unobtrusive Ajax (v: 3.2.6) via Nuget packages. First thing I noticed there was no local folder added for it in wwwroot/lib, also if try something simple like:

@using (Ajax.BeginForm( ...

I get an error: CS0103 The name 'Ajax' does not exist in the current context

Please advise how to fix this.


问:
Using JMX or SNPM4J with OpenJDK 8
I was searching the internet to finding some resources to use JMX or SNMP4J with OpenJDK 8. Can someone help with this?

With Oracle JDK 8 we used SNMP to send the Heap status to Nagios monitoring. SNMP is proprietary to Oracle JDK. This leads us to think about JMX or SNMP4J with OpenJDK 8.

Any support will be highly welcomed !!!

答:
I think you are mixing up a couple of things.  The SNMP support in Java was an SNMP agent rather than a generic SNMP framework library (like SNMP4J).  And from what I can tell from looking at the OpenJDK source code:

the SNMP agent was present in OpenJDK until at least OpenJDK 8, and

it is not proprietary (according to the copyright headers).

Either way, SNMP support has been removed:

Bug tracker issue JDK-820621 says:

"JVM-MANAGEMENT-MIB.mib was defined by JSR 163 / JSR 174 in Java SE 5 while the implementation is optional.  The implementation for JVM SNMP monitoring and management is provided by jdk.snmp module.  There has been nearly zero inquiry and bug issues w.r.t. SNMP monitoring support for JVM.  Due to the lack of customer usage, SNMP monitoring support for JVM has been deprecated in JDK 10 and removed in JDK 11."

(My trawling of the source trees suggests that SNMP might have been removed from OpenJDK before Oracle JDK, but I might have missed something.  I am doing this rather crudely.)

I don't think there is much chance that you will find a direct replacement for the the Oracle / OpenJDK SNMP agent, for either Oracle JDK or OpenJDK in Java 11 or later.

You might be able to extract the code from (say) the OpenJDK 10 source tree and port it to a later version of Java.  But this might entail making your own custom OpenJDK builds.

But you certainly can use JMX to monitor an OpenJDK.  It should be the same as for an Oracle JDK:

Monitoring and Management Using JMX Technology

Title: Using JMX or SNPM4J with OpenJDK 8


问:
Recursive rendering of JSON tree with HTML elements (Input, Radio, etc.)
I am quite new to React and working with JSON structures. I am trying to construct a recursive render of a JSON tree structure that dynamically renders individual HTML elements (e.g. radio buttons, dropdown menus, etc.) from the tree. I have seen other implementations, but they do not have nested HTML elements that differ from li, ul, etc. They also do not typically have different naming conventions further down the tree (e.g. attributes, options).

The tree looks like this:

```<code>    {
        "id": "1",
        "name": "Animals",
        "color": "#e37939",
        "shape": "bounding_box",
        "attributes": [
            {
                "id": "1.1",
                "name": "Type",
                "type": "radio",
                "required": false,
                "options": [
                    {
                        "id": "1.1.1",
                        "optionName": "Cats",
                        "optionValue": "cats",
                        "options": [.... and so on

    };
</code>```

What I ultimately what to achieve is to get to a format where one clicks the 'Animals button', which then renders the nested radio button, and if one selects the 'cats' option value it'd render the next dropdown menu. I have set up an initial set of methods, but I can't quite figure out how to dynamically render the next set of nested options when an option is clicked. I have created a React fiddle here: https://codesandbox.io/s/vigilant-grothendieck-jknym

The biggest challenge is to get the nested recursive options embedded in an options group. I haven't been able to figure out how to do that yet.

答:
I have created a datastructure for what you want to achieve , altho i have tweaked it a bit as there are parts of it redundant but you can still keep both data structure and convert between them.it goes recursively as deep as you want it to go.

```<code>const prodList = [
 {
    id: "1",
    name: "Animals",
    options: [
      {
        id: "1.1",
        name: "Type",
        inputType: "radio",
        options: [
          {
            id: "1.1.1",
            name: "Cats",
            value: "Cats",
            inputType: "select",
            options: [
              { id: "1.1.1.1", name: "Siamese Grey", value: "Siamese Grey" },
              { id: "1.1.1.2", name: "Siamese Black", value: "Siamese Black" },
              { id: "1.1.1.3", name: "Siamese Cute", value: "Siamese Cute" },
              { id: "1.1.1.4", name: "House Cat", value: "House Cat" },
              { id: "1.1.1.5", name: "House Cat", value: "House Cat" }
            ]
          },
          { id: "1.1.2", name: "Dogs", value: "Dogs" },
          { id: "1.1.3", name: "Cows", value: "Cows" }
        ]
      }
    ]
  }
];
</code>```

above is the data structure where you have "inputType" property that helps determining what component to show. we will have a basic component , a radio component and a select component of each type which can render each other inside them.

```<code>export default class ProductsPage extends Component {
  render() {
    let prodItems = prodList.map(p => {
      return <MainContentManager data={p} key={p.id} />;
    });
    return <div>{prodItems}</div>;
  }
}

class MainContentManager extends Component {
  render() {
    let renderObj = null;
    renderObj = basicMethod(renderObj, this.props.data);
    return (
      <div>
        <h6> {this.props.data.name}</h6>
        {renderObj}
      </div>
    );
  }
}

class RadioButtonManager extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeOptionIndex: 0
    };
    this.handleInputClick = this.handleInputClick.bind(this);
  }
  handleInputClick(index) {
    this.setState({
      activeOptionIndex: index
    });
  }
  render() {
    let renderObj = null;
    let renderDat = null;
    renderDat = this.props.data.options.map((op, index) => {
      return (
        <label key={op.id}>
          <input
            type="radio"
            onChange={e => {
              this.handleInputClick(index);
            }}
            checked={index == this.state.activeOptionIndex ? true : false}
          />
          {op.name}
        </label>
      );
    });

    renderObj = basicMethod(renderObj, {
      options: [this.props.data.options[this.state.activeOptionIndex]]
    });
    return (
      <div>
        <h6> {this.props.data.name}</h6>
        {renderDat}
        {renderObj}
      </div>
    );
  }
}

class SelectManager extends Component {
  constructor(props) {
    super(props);
    this.state = { value: "", activeOptionIndex: 0 };
    this.handleInputClick = this.handleInputClick.bind(this);
  }

  handleInputClick(value) {
    let activeOptionIndex = this.state.activeOptionIndex;
    if (this.props.data.options) {
      for (let i = 0; i < this.props.data.options.length; i++) {
        if (this.props.data.options[i].value == value) {
          activeOptionIndex = i;
        }
      }
    }
    this.setState({
      value: value,
      activeOptionIndex: activeOptionIndex
    });
  }
  render() {
    let renderObj = null;
    let selectOptions = this.props.data.options.map((op, index) => {
      return (
        <option key={op.value} value={op.value}>
          {op.name}
        </option>
      );
    });
    renderObj = basicMethod(renderObj, {
      options: [this.props.data.options[this.state.activeOptionIndex]]
    });
    return (
      <div>
        <select
          onChange={e => {
            this.handleInputClick(e.target.value);
          }}
        >
          {selectOptions}
        </select>
        {renderObj}
      </div>
    );
  }
}

function basicMethod(renderObj, data) {
  if (data && data.options) {
    renderObj = data.options.map(op => {
      !op && console.log(data);
      let comp = null;
      if (op.inputType == "radio") {
        comp = <RadioButtonManager data={op} key={op.id} />;
      } else if (op.inputType == "select") {
        comp = <SelectManager data={op} key={op.id} />;
      } else {
        comp = <MainContentManager data={op} key={op.id} />;
      }
      return comp;
    });
  }

  return renderObj;
}
</code>```

ask anything if it is unclear or you want it a bit different.

Body:
I am quite new to React and working with JSON structures. I am trying to construct a recursive render of a JSON tree structure that dynamically renders individual HTML elements (e.g. radio buttons, dropdown menus, etc.) from the tree. I have seen other implementations, but they do not have nested HTML elements that differ from li, ul, etc. They also do not typically have different naming conventions further down the tree (e.g. attributes, options).

The tree looks like this:

    {
        "id": "1",
        "name": "Animals",
        "color": "#e37939",
        "shape": "bounding_box",
        "attributes": [
            {
                "id": "1.1",
                "name": "Type",
                "type": "radio",
                "required": false,
                "options": [
                    {
                        "id": "1.1.1",
                        "optionName": "Cats",
                        "optionValue": "cats",
                        "options": [.... and so on

    };

What I ultimately what to achieve is to get to a format where one clicks the 'Animals button', which then renders the nested radio button, and if one selects the 'cats' option value it'd render the next dropdown menu. I have set up an initial set of methods, but I can't quite figure out how to dynamically render the next set of nested options when an option is clicked. I have created a React fiddle here: https://codesandbox.io/s/vigilant-grothendieck-jknym

The biggest challenge is to get the nested recursive options embedded in an options group. I haven't been able to figure out how to do that yet.

Body:
I have created a datastructure for what you want to achieve , altho i have tweaked it a bit as there are parts of it redundant but you can still keep both data structure and convert between them.it goes recursively as deep as you want it to go.

const prodList = [
 {
    id: "1",
    name: "Animals",
    options: [
      {
        id: "1.1",
        name: "Type",
        inputType: "radio",
        options: [
          {
            id: "1.1.1",
            name: "Cats",
            value: "Cats",
            inputType: "select",
            options: [
              { id: "1.1.1.1", name: "Siamese Grey", value: "Siamese Grey" },
              { id: "1.1.1.2", name: "Siamese Black", value: "Siamese Black" },
              { id: "1.1.1.3", name: "Siamese Cute", value: "Siamese Cute" },
              { id: "1.1.1.4", name: "House Cat", value: "House Cat" },
              { id: "1.1.1.5", name: "House Cat", value: "House Cat" }
            ]
          },
          { id: "1.1.2", name: "Dogs", value: "Dogs" },
          { id: "1.1.3", name: "Cows", value: "Cows" }
        ]
      }
    ]
  }
];

above is the data structure where you have "inputType" property that helps determining what component to show. we will have a basic component , a radio component and a select component of each type which can render each other inside them.

export default class ProductsPage extends Component {
  render() {
    let prodItems = prodList.map(p => {
      return <MainContentManager data={p} key={p.id} />;
    });
    return <div>{prodItems}</div>;
  }
}

class MainContentManager extends Component {
  render() {
    let renderObj = null;
    renderObj = basicMethod(renderObj, this.props.data);
    return (
      <div>
        <h6> {this.props.data.name}</h6>
        {renderObj}
      </div>
    );
  }
}

class RadioButtonManager extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeOptionIndex: 0
    };
    this.handleInputClick = this.handleInputClick.bind(this);
  }
  handleInputClick(index) {
    this.setState({
      activeOptionIndex: index
    });
  }
  render() {
    let renderObj = null;
    let renderDat = null;
    renderDat = this.props.data.options.map((op, index) => {
      return (
        <label key={op.id}>
          <input
            type="radio"
            onChange={e => {
              this.handleInputClick(index);
            }}
            checked={index == this.state.activeOptionIndex ? true : false}
          />
          {op.name}
        </label>
      );
    });

    renderObj = basicMethod(renderObj, {
      options: [this.props.data.options[this.state.activeOptionIndex]]
    });
    return (
      <div>
        <h6> {this.props.data.name}</h6>
        {renderDat}
        {renderObj}
      </div>
    );
  }
}

class SelectManager extends Component {
  constructor(props) {
    super(props);
    this.state = { value: "", activeOptionIndex: 0 };
    this.handleInputClick = this.handleInputClick.bind(this);
  }

  handleInputClick(value) {
    let activeOptionIndex = this.state.activeOptionIndex;
    if (this.props.data.options) {
      for (let i = 0; i < this.props.data.options.length; i++) {
        if (this.props.data.options[i].value == value) {
          activeOptionIndex = i;
        }
      }
    }
    this.setState({
      value: value,
      activeOptionIndex: activeOptionIndex
    });
  }
  render() {
    let renderObj = null;
    let selectOptions = this.props.data.options.map((op, index) => {
      return (
        <option key={op.value} value={op.value}>
          {op.name}
        </option>
      );
    });
    renderObj = basicMethod(renderObj, {
      options: [this.props.data.options[this.state.activeOptionIndex]]
    });
    return (
      <div>
        <select
          onChange={e => {
            this.handleInputClick(e.target.value);
          }}
        >
          {selectOptions}
        </select>
        {renderObj}
      </div>
    );
  }
}

function basicMethod(renderObj, data) {
  if (data && data.options) {
    renderObj = data.options.map(op => {
      !op && console.log(data);
      let comp = null;
      if (op.inputType == "radio") {
        comp = <RadioButtonManager data={op} key={op.id} />;
      } else if (op.inputType == "select") {
        comp = <SelectManager data={op} key={op.id} />;
      } else {
        comp = <MainContentManager data={op} key={op.id} />;
      }
      return comp;
    });
  }

  return renderObj;
}

ask anything if it is unclear or you want it a bit different.


问:
The default change to DataTable
i'm using in library  dataTables  In the folder jquery.dataTables.min
And there is the option to display 10 rows or 25 or 50 or 100
10 rows are the default
How do I change the default to 50 rows?
Below is just the code that shows the options:

```<code>    aLengthMenu: [10, 25, 50, 100],
    iDisplayLength: 10,
</code>```

答: Change its iDisplayLength to 50</p>

Title: The default change to DataTable

Body:
i'm using in library  dataTables  In the folder jquery.dataTables.min
And there is the option to display 10 rows or 25 or 50 or 100
10 rows are the default
How do I change the default to 50 rows?
Below is just the code that shows the options:

    aLengthMenu: [10, 25, 50, 100],
    iDisplayLength: 10,

Body: Change its iDisplayLength to 50


问:
(P)react trigger method in functional ChildComponent
i'm building a form in Preact and struggle to validate the inputs on form submit.

The <TextInput> Component gets passed a validation object from validate.js and handle the validation on it's own.

The parent Component is a form that stores the data in a formData state and submits the values to an API.

Before submitting I want to validate the data again to prevent the user skipping some required inputs.

Question: What's the "react-way" to solve this problem?

Input:

export default function TextInput({ onChange, validation }) {
  const [value, setValue] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    onChange && onChange(value);
  }, [value]);

  const handleBlur = (e) => {
    const value = e.currentTarget.value;

    if (validation) {
      const errors = validate.single(value, validation);

      if (errors) {
        setError(errors[0]);
      }
    }
  };

  return (
    <input
      type="text"
      onBlur={handleBlur}
      onInput={e => setValue(e.target.value)}
      onFocus={() => setError(null)}
    />
    // show some error msg. if error is set
  );
}
```
<p>Form:</p>
<pre class="lang-js prettyprint-override"><code>export default function CompetitionForm() {
  const [formData, setFormData] = useState({});

  const submitForm = async (e) => {
    e.preventDefault();
    // validate data, submit the form
  };

  const competitionTextInput = (key) => {
    return (
      <TextInput
        name={key}
        validation={RULES[key]}
        onChange={value => {
          formData[key] = value;
          setFormData(formData);
        }}
      />
    );
  };

  return (
    <form className="c-form" onSubmit={submitForm}>
      <div className="row mb-4">
        <div className="col-12 col-md-6">
          {competitionTextInput('firstName')}
        </div>
        <div className="col-12 col-md-6">
          {competitionTextInput('lastName')}
        </div>
      </div>
    </form>
  );
}
</code>```

答:
try below . hope it will help</p>

```<code>  //Form:

  const submitForm = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    // validate data, submit the form
  };

  render() {
    const { validated } = this.state;
    ......
   return (
    <Form noValidate validated={validated} onSubmit={submitForm}>
    </form>
     );
  }
</code>```

Body:
i'm building a form in Preact and struggle to validate the inputs on form submit.

The <TextInput> Component gets passed a validation object from validate.js and handle the validation on it's own.

The parent Component is a form that stores the data in a formData state and submits the values to an API.

Before submitting I want to validate the data again to prevent the user skipping some required inputs.

Question: What's the "react-way" to solve this problem?

Input:

export default function TextInput({ onChange, validation }) {
  const [value, setValue] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    onChange && onChange(value);
  }, [value]);

  const handleBlur = (e) => {
    const value = e.currentTarget.value;

    if (validation) {
      const errors = validate.single(value, validation);

      if (errors) {
        setError(errors[0]);
      }
    }
  };

  return (
    <input
      type="text"
      onBlur={handleBlur}
      onInput={e => setValue(e.target.value)}
      onFocus={() => setError(null)}
    />
    // show some error msg. if error is set
  );
}

Form:

export default function CompetitionForm() {
  const [formData, setFormData] = useState({});

  const submitForm = async (e) => {
    e.preventDefault();
    // validate data, submit the form
  };

  const competitionTextInput = (key) => {
    return (
      <TextInput
        name={key}
        validation={RULES[key]}
        onChange={value => {
          formData[key] = value;
          setFormData(formData);
        }}
      />
    );
  };

  return (
    <form className="c-form" onSubmit={submitForm}>

          {competitionTextInput('firstName')}

          {competitionTextInput('lastName')}

    </form>
  );
}

Body:
try below . hope it will help

  //Form:

  const submitForm = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    // validate data, submit the form
  };

  render() {
    const { validated } = this.state;
    ......
   return (
    <Form noValidate validated={validated} onSubmit={submitForm}>
    </form>
     );
  }


问:
How can i export 2 tables in a single excel sheet using reactjs / javascript
I am trying to export 2 tables in a single excel sheet using reactjs , can anyone suggest me any library or any idea how to acheieve this

答:
```<code> function toExcel() {

    if ("ActiveXObject" in window) {
        alert("This is Internet Explorer!");
    } else {

        var cache = {};
        this.tmpl = function tmpl(str, data) {
            var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
            new Function("obj",
                         "var p=[],print=function(){p.push.apply(p,arguments);};" +
                         "with(obj){p.push('" +
                         str.replace(/[\r\t\n]/g, " ")
                         .split("{{").join("\t")
                         .replace(/((^|}})[^\t]*)'/g, "$1\r")
                         .replace(/\t=(.*?)}}/g, "',$1,'")
                         .split("\t").join("');")
                         .split("}}").join("p.push('")
                         .split("\r").join("\\'") + "');}return p.join('');");
            return data ? fn(data) : fn;
        };
        var tableToExcel = (function () {
            var uri = 'data:application/vnd.ms-excel;base64,',
                template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{{=worksheet}}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{{for(var i=0; i<tables.length;i++){ }}<table>{{=tables[i]}}</table>{{ } }}</body></html>',
                base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)));
                },
                format = function (s, c) {
                    return s.replace(/{(\w+)}/g, function (m, p) {
                        return c[p];
                    });
                };
            return function (tableList, name) {
                if (!tableList.length > 0 && !tableList[0].nodeType) table = document.getElementById(table);
                var tables = [];
                for (var i = 0; i < tableList.length; i++) {
                    tables.push(tableList[i].innerHTML);
                }
                var ctx = {
                    worksheet: name || 'Worksheet',
                    tables: tables
                };
                window.location.href = uri + base64(tmpl(template, ctx));
            };
        })();
        tableToExcel(document.getElementsByClassName("exportToExcel"), "one");
    }
}
</code>```


问:
Could not parse the JSON file ,Error in Progam.cs asp.net core
I have some issues with the program.cs file, with the version of ASP.NetCORE 2.0

Here's my code

```<code>     public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseKestrel()
            .UseStartup<Startup>()
            .UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build())
            .Build();

}
</code>```

When I run the project, following error occurs.

```<code>System.FormatException: 'Could not parse the JSON file. Error on line number '0': ''.'
</code>```

How to resolve it?

答:
There is a possibility it might happen when appsettings.json is not properly formated

In my case, I had the below configuration and got the error

```<code> {
"ConnectionStrings": {
"TransferDBConnection":
 "Server=INGBTCPIC5DT04D;Database=TransferDB;Trusted_Connection=true;
 },
  ***{***
   "Logging": {
   "LogLevel": {
    "Default": "Warning"
   }
 },
 "AllowedHosts": "*"
}
</code>```

ideally, it should be one extra { cause this problem

```<code> {
 "ConnectionStrings": {
 "TransferDBConnection":
 "Server=INGBTCPIC5DT04D;Database=TransferDB;Trusted_Connection=true;"
 },
  "Logging": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"AllowedHosts": "*"
}
</code>```

Body:
I have some issues with the program.cs file, with the version of ASP.NetCORE 2.0

Here's my code

     public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseKestrel()
            .UseStartup<Startup>()
            .UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build())
            .Build();

}

When I run the project, following error occurs.

System.FormatException: 'Could not parse the JSON file. Error on line number '0': ''.'

How to resolve it?

Body:
There is a possibility it might happen when appsettings.json is not properly formated

In my case, I had the below configuration and got the error

 {
"ConnectionStrings": {
"TransferDBConnection":
 "Server=INGBTCPIC5DT04D;Database=TransferDB;Trusted_Connection=true;
 },
  ***{***
   "Logging": {
   "LogLevel": {
    "Default": "Warning"
   }
 },
 "AllowedHosts": "*"
}

ideally, it should be one extra { cause this problem

 {
 "ConnectionStrings": {
 "TransferDBConnection":
 "Server=INGBTCPIC5DT04D;Database=TransferDB;Trusted_Connection=true;"
 },
  "Logging": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"AllowedHosts": "*"
}


问:
How to calculate the distance between two points, for many consequent points, within groups in python
I have the following df

```<code>       id             xx            yy  time
0       1  553343.041098  4.178420e+06     1
1       1  553343.069815  4.178415e+06     2
2       1  553343.069815  4.178415e+06     3
3       2  553343.950755  4.178415e+06     1
4       2  553341.343829  4.178410e+06     6
</code>```

The xx and yy is the position of each id at a certain point in time.

I would like to create an extra column in this df, which will be the difference in distance from one point of time to another (going from the smallest value of time to the next bigger, to the next bigger one etc), within the id group.

Is there a Pythonic way of doing so ?

Body:
I have the following df

       id             xx            yy  time
0       1  553343.041098  4.178420e+06     1
1       1  553343.069815  4.178415e+06     2
2       1  553343.069815  4.178415e+06     3
3       2  553343.950755  4.178415e+06     1
4       2  553341.343829  4.178410e+06     6

The xx and yy is the position of each id at a certain point in time.

I would like to create an extra column in this df, which will be the difference in distance from one point of time to another (going from the smallest value of time to the next bigger, to the next bigger one etc), within the id group.

Is there a Pythonic way of doing so ?

Body:
You can do like below.

I didn't do df['distance_meters'] because it is straight forward.

df['xx_diff']=df.groupby('id')['xx'].diff()**2
df['yy_diff']=df.groupby('id')['yy'].diff()**2

If you don't need ['xx_diff'] & ['yy_diff'] columns in your dataframe, you can directly use the code below.

df['distance']= np.sqrt(df.groupby('id')['xx'].diff()**2+df.groupby('id')['yy'].diff()**2)

Output

    id            xx         yy time    xx_diff3    yy_diff3    distance
0   1   553343.041098   4178420.0   1   NaN            NaN      NaN
1   1   553343.069815   4178415.0   2   0.000825       25.0     5.000082
2   1   553343.069815   4178415.0   3   0.000000       0.0      0.000000
3   2   553343.950755   4178415.0   1   NaN            NaN      NaN
4   2   553341.343829   4178410.0   6   6.796063      25.0      5.638800


问:
Is there a way to set locales in cluster in r?
I have to run a piece of code using parallel processing to reduce the execution time. Each steps are independent of each other. I have created a cluster,

```<code> cl = makeCluster(cores)
 registerDoParallel(cl)
 invisible(clusterEvalQ(cl, sapply(list.files("./Src/LibrariesAndFunctions/",
                                             full.names = TRUE,
                                             recursive = TRUE),
                                  function(x) {
                                    source(x, encoding = "UTF-8")
                                  })))
</code>```

Now I need to read a set of functions available in the same directory. The problem is that the data is in japanese and I have set the locale globally outside the cluster as

```<code>Sys.setlocale("LC_ALL","japanese_JAPAN")
</code>```

This works outside the cluster but not within the cluster and it throws an error like this,

```<code>2020/02/12 20:10:27.742   [INFO ]   2020/02/12 20:10:27.497   |main        |  [xxx] 結合 開始
Error in checkForRemoteErrors(lapply(cl, recvResult)) :
  4 nodes produced errors;irst error: ./Src/LibrariesAndFunctions//01_Setup_Logging_Milestone/I103_Setup.R:15:0: unexpected end of input
13:   ##
14:   ##
   ^
</code>```

This error tells that there is an unexpected end of input at line 14 but there are japanese comments there. This can be solved only if the comments are translated to english. So my question here is, How to set the locale in a cluster node?

答:
I have found the solution for this problem. The solution is this.

```<code>clusterCall(cl,function(){ Sys.setlocale("LC_ALL","japanese_JAPAN")})
</code>```

The locale were set in the cluster.

Body:
I have to run a piece of code using parallel processing to reduce the execution time. Each steps are independent of each other. I have created a cluster,

 cl = makeCluster(cores)
 registerDoParallel(cl)
 invisible(clusterEvalQ(cl, sapply(list.files("./Src/LibrariesAndFunctions/",
                                             full.names = TRUE,
                                             recursive = TRUE),
                                  function(x) {
                                    source(x, encoding = "UTF-8")
                                  })))

Now I need to read a set of functions available in the same directory. The problem is that the data is in japanese and I have set the locale globally outside the cluster as

Sys.setlocale("LC_ALL","japanese_JAPAN")

This works outside the cluster but not within the cluster and it throws an error like this,

2020/02/12 20:10:27.742   [INFO ]   2020/02/12 20:10:27.497   |main        |  [xxx] 結合 開始
Error in checkForRemoteErrors(lapply(cl, recvResult)) :
  4 nodes produced errors;irst error: ./Src/LibrariesAndFunctions//01_Setup_Logging_Milestone/I103_Setup.R:15:0: unexpected end of input
13:   ##
14:   ##
   ^

This error tells that there is an unexpected end of input at line 14 but there are japanese comments there. This can be solved only if the comments are translated to english. So my question here is, How to set the locale in a cluster node?

Body:
I have found the solution for this problem. The solution is this.

clusterCall(cl,function(){ Sys.setlocale("LC_ALL","japanese_JAPAN")})

The locale were set in the cluster.


问:
C# MVVM ASP.net API implicit conversion error
New to web app API's and trying to build a web app that exposes data from our DWH environment to the application via an API.

My models:

bed_data_dbconnect - context model:

```<code>     using Microsoft.EntityFrameworkCore;

     namespace BED_MGMT_WEBAPP_APIs.Models
       {
         public class bed_data_dbconnect : DbContext
         {
         public bed_data_dbconnect(DbContextOptions options) : base(options)
         { }

         public DbSet<Bed_Data> tblBase_BEDMGMT_BEDS_BY_WARD { get; set; }
     }
 }
</code>```

bed_data model

```<code> using System;

 namespace BED_MGMT_WEBAPP_APIs.Models
 {
     public class Bed_Data
     {
    public string HOSPITAL {get;set;}
    public string WARD_CODE {get;set;}
    public string WARD {get;set;}
    public string REALTIME_BED_STOCK {get;set;}
    public string ACTUAL_BED_STOCK {get;set;}
    public string AVAILABLE_BEDS_M {get;set;}
    public string AVAILABLE_BEDS_F {get;set;}
    public string AVAILABLE_BEDS_C {get;set;}
    public string TOTAL_BEDS_CLOSED {get;set;}
    public string CLOSED_AND_UNOCCUPIED {get;set;}
    public string ESCALATION_BEDS_IN_USE {get;set;}
    public string DISCHARGES_CONFIRMED_M {get;set;}
    public string DISCHARGES_CONFIRMED_F {get;set;}
    public string DISCHARGES_CONFIRMED_C {get;set;}
    public string DISCHARGES_POTENTIAL_M {get;set;}
    public string DISCHARGES_POTENTIAL_F {get;set;}
    public string DISCHARGES_POTENTIAL_C {get;set;}
    public string AWAITING_ADMISSION_AE_M {get;set;}
    public string AWAITING_ADMISSION_AE_F {get;set;}
    public string AWAITING_ADMISSION_AE_C {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_C {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_C {get;set;}
    public string AWAITING_REPATRIATION_IN {get;set;}
    public string AWAITING_REPATRIATION_OUT {get;set;}
    public string OUTLIERS_MED {get;set;}
    public string OUTLIERS_SURG {get;set;}
    public string OUTLIERS_ORTH {get;set;}
    public string STAFFING_SHORTAGES {get;set;}
    public string USER_CODE {get;set;}
    public string DATETIME_RECORD_INSERTED {get;set;} //= System.Convert.ToDateTime()

    }
 }
</code>```

db connection string in my startup file:

```<code>  public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<bed_data_dbconnect>(opt => opt.UseSqlServer(connectionString));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    }
</code>```

Controller:

```<code> using Microsoft.AspNetCore.Mvc;
 using System.Collections.Generic;
 using System.Linq;
 using BED_MGMT_WEBAPP_APIs.Models;

 namespace BED_MGMT_WEBAPP_APIs.Controllers
 {
   [Route("api/[Controller]")]
   [ApiController]

    public class bed_data_controller : Controller
    {
    private bed_data_dbconnect _bed_data;

    public bed_data_controller(bed_data_dbconnect context)
    {

    _bed_data = context;

    }

    //Get api/values
    [HttpGet]

    public ActionResult<IEnumerable<bed_data_dbconnect>> Get()
    {

        return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();

    }

    ~bed_data_controller()
    {

        _bed_data.Dispose();

    }

     }
 }
</code>```

I am trying to return the contents of this table to a list to validate the api is working as expected, but the controller above generates an error:

Cannot implicitly convert type
       'System.Collections.Generic.List' to 'Microsoft.AspNetCore.Mvc.ActionResult>' [BED_MGMT_WEBAPP_APIs]

on this line:

```<code> return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();
</code>```

答:
I expect the returntype of your endpoint is wrong. The returntype of your endpoint is ActionResult<IEnumerable<bed_data_dbconnect>>.

Where bed_data_dbconnect is a DbContext class.

Shouldn't the returntype be ActionResult<IEnumerable<Bed_Data>>?

Body:
New to web app API's and trying to build a web app that exposes data from our DWH environment to the application via an API.

My models:

bed_data_dbconnect - context model:

     using Microsoft.EntityFrameworkCore;

     namespace BED_MGMT_WEBAPP_APIs.Models
       {
         public class bed_data_dbconnect : DbContext
         {
         public bed_data_dbconnect(DbContextOptions options) : base(options)
         { }

         public DbSet<Bed_Data> tblBase_BEDMGMT_BEDS_BY_WARD { get; set; }
     }
 }

bed_data model

 using System;

 namespace BED_MGMT_WEBAPP_APIs.Models
 {
     public class Bed_Data
     {
    public string HOSPITAL {get;set;}
    public string WARD_CODE {get;set;}
    public string WARD {get;set;}
    public string REALTIME_BED_STOCK {get;set;}
    public string ACTUAL_BED_STOCK {get;set;}
    public string AVAILABLE_BEDS_M {get;set;}
    public string AVAILABLE_BEDS_F {get;set;}
    public string AVAILABLE_BEDS_C {get;set;}
    public string TOTAL_BEDS_CLOSED {get;set;}
    public string CLOSED_AND_UNOCCUPIED {get;set;}
    public string ESCALATION_BEDS_IN_USE {get;set;}
    public string DISCHARGES_CONFIRMED_M {get;set;}
    public string DISCHARGES_CONFIRMED_F {get;set;}
    public string DISCHARGES_CONFIRMED_C {get;set;}
    public string DISCHARGES_POTENTIAL_M {get;set;}
    public string DISCHARGES_POTENTIAL_F {get;set;}
    public string DISCHARGES_POTENTIAL_C {get;set;}
    public string AWAITING_ADMISSION_AE_M {get;set;}
    public string AWAITING_ADMISSION_AE_F {get;set;}
    public string AWAITING_ADMISSION_AE_C {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_C {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_C {get;set;}
    public string AWAITING_REPATRIATION_IN {get;set;}
    public string AWAITING_REPATRIATION_OUT {get;set;}
    public string OUTLIERS_MED {get;set;}
    public string OUTLIERS_SURG {get;set;}
    public string OUTLIERS_ORTH {get;set;}
    public string STAFFING_SHORTAGES {get;set;}
    public string USER_CODE {get;set;}
    public string DATETIME_RECORD_INSERTED {get;set;} //= System.Convert.ToDateTime()

    }
 }

db connection string in my startup file:

  public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<bed_data_dbconnect>(opt => opt.UseSqlServer(connectionString));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    }

Controller:

 using Microsoft.AspNetCore.Mvc;
 using System.Collections.Generic;
 using System.Linq;
 using BED_MGMT_WEBAPP_APIs.Models;

 namespace BED_MGMT_WEBAPP_APIs.Controllers
 {
   [Route("api/[Controller]")]
   [ApiController]

    public class bed_data_controller : Controller
    {
    private bed_data_dbconnect _bed_data;

    public bed_data_controller(bed_data_dbconnect context)
    {

    _bed_data = context;

    }

    //Get api/values
    [HttpGet]

    public ActionResult<IEnumerable<bed_data_dbconnect>> Get()
    {

        return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();

    }

    ~bed_data_controller()
    {

        _bed_data.Dispose();

    }

     }
 }

I am trying to return the contents of this table to a list to validate the api is working as expected, but the controller above generates an error:

Cannot implicitly convert type
       'System.Collections.Generic.List' to 'Microsoft.AspNetCore.Mvc.ActionResult>' [BED_MGMT_WEBAPP_APIs]

on this line:

 return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();


问:
How to set 'hardwareBackPress' to another Stack

```<code>//TermsPage.tsx
const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});
componentWillUnmount() {
    BackHandler.addEventListener('hardwareBackPress',()=>{
      this.props.navigation.dispatch(resetAction)
      return true
    })
  }

</code>```

How to set 'hardwareBackPress' eventListenner to navigate to another StackNavigator. If I set like above. This backpress work in all Pages. I want to set this listener only for TermsPage. And set this listener to navigate to another StackNavigator

答:
you can use this example, here we bind this method in Constructer and also call this function whenever the screen is rendering back

```<code> constructor(props) {
        super(props);
        this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
        this.state = {
        };

      }
      componentWillMount() {
        BackHandler.addEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
      componentWillUnmount() {
        BackHandler.removeEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
      handleBackButtonClick() {
        this.props.navigation.navigate('name of page where you want to nav');
        return true;
      }
</code>```

From where you don't want to go back use this..

```<code> componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }
 componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }
  handleBackButton() {
    return true;
  }
</code>```

It will not let you go back from the page where you are, please import BackHandler from react-native.
hope it helps, feel free for Doubts.

Body:
//TermsPage.tsx
const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});
componentWillUnmount() {
    BackHandler.addEventListener('hardwareBackPress',()=>{
      this.props.navigation.dispatch(resetAction)
      return true
    })
  }

How to set 'hardwareBackPress' eventListenner to navigate to another StackNavigator. If I set like above. This backpress work in all Pages. I want to set this listener only for TermsPage. And set this listener to navigate to another StackNavigator

Body:
you can use this example, here we bind this method in Constructer and also call this function whenever the screen is rendering back

 constructor(props) {
        super(props);
        this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
        this.state = {
        };

      }
      componentWillMount() {
        BackHandler.addEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
      componentWillUnmount() {
        BackHandler.removeEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
      handleBackButtonClick() {
        this.props.navigation.navigate('name of page where you want to nav');
        return true;
      }

From where you don't want to go back use this..

 componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }
 componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }
  handleBackButton() {
    return true;
  }

It will not let you go back from the page where you are, please import BackHandler from react-native.
hope it helps, feel free for Doubts.


问:
How do I pass MySQL data on Fusion Chart using JavaScript and Node.Js?
Here I have uploaded two screenshots. I want to display MySQL data in this gauge. I am using JavaScript and Node.Js for MySQL database connectivity.

Fusion Chart Code

```<code>    <script type="text/javascript">

    let fusionCharts= document.querySelector('#chart-container')

    FusionCharts.ready(function() {

        var fusionCharts = new FusionCharts("chart-container",{
            "type": "angulargauge",
            "renderAt": "chart-container",
            "width": "450",
            "height": "250",
            "dataFormat": "json",
            "dataSource": {
                // Chart Configuration
                "chart": {
                    "caption": "",
                    "lowerLimit": "0",
                    "upperLimit": "100",
                    "showValue": "1",
                    "numberSuffix": "%",
                    "theme": "fusion",
                    "showToolTip": "0"
                },
                // Chart Data
                "colorRange": {
                    "color": [{
                        "minValue": "0",
                        "maxValue": "50",
                        "code": "#F2726F"
                    }, {
                        "minValue": "50",
                        "maxValue": "75",
                        "code": "#FFC533"
                    }, {
                        "minValue": "75",
                        "maxValue": "100",
                        "code": "#62B58F"
                    }]
                },
                "dials": {
                    "dial": [{
                        "value": "80",
                    }]
                }
            }
        });
        fusionCharts.render();
    });
</code>```

How to replace chart value('80') by MySQL data.

MySQL Database Connectivity Code

```<code>const mysql=require("mysql");
const express=require("express");
const bodyParser=require("body-parser");

var app=express();
app.use(bodyParser.json());
var mysqlConnection=mysql.createConnection({
    host: "localhost",
    port: 3306,
    user: "username",
    database: "mydb",
    password: "password",
});

mysqlConnection.connect((err)=>{
    if (!err){
        console.log("Wow! Connection Established");
    }
    else{
        console.log("Opps! Connection Failed");
    }
});

mysqlConnection.connect(function(err){
    if (!err);
    mysqlConnection.query("SELECT Temperature FROM ISL201 ORDER BY ISL201.Timestamp DESC", function(err, results){
        if (!err);
        console.log(results);
    });
});
</code>```

答:
Here is a snippet that you can use to render FusionCharts using the above technologies

Server.js

```<code>const mysql = require("mysql");
const express = require("express");
const bodyparser = require("body-parser");
const path = require("path");
var app = express();
//Configuring express server
app.use(bodyparser.json());

//MySQL details
var mysqlConnection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "fusioncharts_jspsample",
  multipleStatements: true
});

mysqlConnection.connect(err => {
  if (!err) console.log("Connection Established Successfully");
  else console.log("Connection Failed!" + JSON.stringify(err, undefined, 2));
});

//Establish the server connection
//PORT ENVIRONMENT VARIABLE
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));

app.use(express.static("public"));

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "/index.html"));
});

app.get("/api/number_of_visitor/:id", (req, res) => {
  mysqlConnection.query(
    "SELECT * FROM number_of_visitor WHERE id = ?",
    [req.params.id],
    (err, rows, fields) => {
      if (!err) {
        res.json(rows);
      } else console.log(err);
    }
  );
});
</code>```

Client Snippet

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
  </head>

  <body>
    <h1>Angular Gauge</h1>

    <script type="text/javascript">
      async function fetchData(id = 1) {
        const { data } = await axios.get(
          `http://localhost:8080/api/number_of_visitor/${id}`
        );
        return data;
      }

      Promise.all([fetchData()]).then(v => {
        console.log(v);
        let val = v[0][0].bakersfield_central;
        const ds = {
          chart: {
            caption: "Customer Satisfaction Score",
            subcaption: "Last week",
            lowerLimit: "0",
            upperLimit: "22500",
            lowerLimitDisplay: "Bad",
            upperLimitDisplay: "Good",
            showValue: "1",
            valueBelowPivot: "1",
            theme: "fusion"
          },
          colorRange: {
            color: [
              {
                minValue: "0",

            maxValue: "7500",
            code: "#e44a00"
          },
          {
            minValue: "7500",
            maxValue: "15000",
            code: "#f8bd19"
          },
          {
            minValue: "15000",
            maxValue: "22500",
            code: "#6baa01"
          }
        ]
      },
      dials: {
        dial: [
          {
            value: val
          }
        ]
      }
    };

    FusionCharts.ready(function() {
      var cSatScoreChart = new FusionCharts({
        type: "angulargauge",
        renderAt: "container",
        width: "400",
        height: "250",
        dataFormat: "json",
        dataSource: ds
      }).render();
    });
  });
</script>
<div id="container"></div>
</code>```

Used POSTMAN for serving the requests.

In case you are still facing a problem, here is a demo (SQL file included) - https://www.dropbox.com/s/6am59m3cemfslat/database_demo.zip?dl=0

Body:
Here is a snippet that you can use to render FusionCharts using the above technologies

Server.js

const mysql = require("mysql");
const express = require("express");
const bodyparser = require("body-parser");
const path = require("path");
var app = express();
//Configuring express server
app.use(bodyparser.json());

//MySQL details
var mysqlConnection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "fusioncharts_jspsample",
  multipleStatements: true
});

mysqlConnection.connect(err => {
  if (!err) console.log("Connection Established Successfully");
  else console.log("Connection Failed!" + JSON.stringify(err, undefined, 2));
});

//Establish the server connection
//PORT ENVIRONMENT VARIABLE
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));

app.use(express.static("public"));

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "/index.html"));
});

app.get("/api/number_of_visitor/:id", (req, res) => {
  mysqlConnection.query(
    "SELECT * FROM number_of_visitor WHERE id = ?",
    [req.params.id],
    (err, rows, fields) => {
      if (!err) {
        res.json(rows);
      } else console.log(err);
    }
  );
});

Client Snippet

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
  </head>

  <body>
    <h1>Angular Gauge</h1>

    <script type="text/javascript">
      async function fetchData(id = 1) {
        const { data } = await axios.get(
          `http://localhost:8080/api/number_of_visitor/${id}`
        );
        return data;
      }

      Promise.all([fetchData()]).then(v => {
        console.log(v);
        let val = v[0][0].bakersfield_central;
        const ds = {
          chart: {
            caption: "Customer Satisfaction Score",
            subcaption: "Last week",
            lowerLimit: "0",
            upperLimit: "22500",
            lowerLimitDisplay: "Bad",
            upperLimitDisplay: "Good",
            showValue: "1",
            valueBelowPivot: "1",
            theme: "fusion"
          },
          colorRange: {
            color: [
              {
                minValue: "0",

            maxValue: "7500",
            code: "#e44a00"
          },
          {
            minValue: "7500",
            maxValue: "15000",
            code: "#f8bd19"
          },
          {
            minValue: "15000",
            maxValue: "22500",
            code: "#6baa01"
          }
        ]
      },
      dials: {
        dial: [
          {
            value: val
          }
        ]
      }
    };

    FusionCharts.ready(function() {
      var cSatScoreChart = new FusionCharts({
        type: "angulargauge",
        renderAt: "container",
        width: "400",
        height: "250",
        dataFormat: "json",
        dataSource: ds
      }).render();
    });
  });
</script>
<div id="container"></div>

Used POSTMAN for serving the requests.

In case you are still facing a problem, here is a demo (SQL file included) - https://www.dropbox.com/s/6am59m3cemfslat/database_demo.zip?dl=0


问:
soft keyboard not appearing
I have a following dialog:

```<code>import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}
</code>```

I open it from a different activity like this:

```<code>IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();
</code>```

And the layout of the dialog is the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>
</code>```

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

```<code>InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);
</code>```

What else can I try? What is the issue here?

答:
Try this</p>

```<code>    ipDiscoveryDialog .setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {

            ((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
        }
    });
</code>```

Title: soft keyboard not appearing

Body:
I have a following dialog:

import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}

I open it from a different activity like this:

IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();

And the layout of the dialog is the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);

What else can I try? What is the issue here?

Body:
Try this

    ipDiscoveryDialog .setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {

            ((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
        }
    });


问:
Where does 'Hello world' come from?
'hello, world' is usually the first example for any programming language. I've always wondered where this sentence came from and where was it first used.

I've once been told that it was the first sentence ever to be displayed on a computer screen, but I've not been able to find any reference to this.

So my question is:

Where does the practice to use 'hello, world' as the first example for computer languages originate from?

Where was it first used?

Update

Although the answers are quite interesting, I should have noted that I had read the Wikipedia article. It does answer the question about the first use in literature, but does not answer when 'hello world' was first used.

So I think that it is safe to conclude that it was not the first sentence ever to be displayed on a computer screen and that there is no record about when it was first used?

答:
According to wikipedia:

While small test programs existed
  since the development of programmable
  computers, the tradition of using the
  phrase "Hello world!" as a test
  message was influenced by an example
  program in the seminal book The C
  Programming Language. The example
  program from that book prints "hello,
  world" (without capital letters or
  exclamation mark), and was inherited
  from a 1974 Bell Laboratories internal
  memorandum by Brian Kernighan,
  Programming in C: A Tutorial, which
  contains the first known version:

```<code> main() {
        printf("hello, world");
 }
</code>```

The first known instance of the usage
  of the words "hello" and "world"
  together in computer literature
  occurred earlier, in Kernighan's 1972
  Tutorial Introduction to the Language
  B[1], with the following code:

```<code>main( ) {
  extrn a, b, c;
  putchar(a); putchar(b); putchar(c); putchar('!*n');
}
a 'hell';
b 'o, w';
c 'orld';
</code>```

OwnerDisplayName: Jacco

ContentLicense: CC BY-SA 3.0

Title: Where does 'Hello world' come from?

LastEditorDisplayName: Jacco

Body:
According to wikipedia:

While small test programs existed
  since the development of programmable
  computers, the tradition of using the
  phrase "Hello world!" as a test
  message was influenced by an example
  program in the seminal book The C
  Programming Language. The example
  program from that book prints "hello,
  world" (without capital letters or
  exclamation mark), and was inherited
  from a 1974 Bell Laboratories internal
  memorandum by Brian Kernighan,
  Programming in C: A Tutorial, which
  contains the first known version:

 main() {
        printf("hello, world");
 }

The first known instance of the usage
  of the words "hello" and "world"
  together in computer literature
  occurred earlier, in Kernighan's 1972
  Tutorial Introduction to the Language
  B[1], with the following code:

main( ) {
  extrn a, b, c;
  putchar(a); putchar(b); putchar(c); putchar('!*n');
}
a 'hell';
b 'o, w';
c 'orld';

OwnerDisplayName: therefromhere

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: therefromhere


问:
Why is this code calling an auto release pool?
I am seeing the following log...

"__NSAutoreleaseNoPool(): Object 0x58264b0 of class UITableViewCellContentView autoreleased with no pool in place - just leaking "

It is a huge release pool log, above is just one of the release log that i copied...

I have a CustomCell that adds tiles into itself depending on the business Logic. But the problem is when I call the creation of the cell, i see the above log messages. I don't see anything wrong with my code.. Does any one has any clue about it?

```<code>- (UITableViewCell *) tableView:(UITableView *)inTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UnSavedNoteListCell *cell;
    NSString *CellIdentifier = [@"Cell_" stringByAppendingString:[NSString stringWithFormat:@"%d", indexPath.row]];
     cell = (UnSavedNoteListCell *)[inTableView  dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{

    NSMutableArray *cellProgressNoteCollection = [self getcellProgressNoteCollectionForLandScape:indexPath];
    cell = [[[UnSavedNoteListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier cellTiles:cellProgressNoteCollection] autorelease];
    cell.backgroundColor = [UIColor clearColor];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

}

//    cell.textLabel.text = [NSString stringWithFormat:@"%d", rand()];
//    cell.textLabel.textColor = [UIColor redColor];
// Configure the cell...

return cell;
}
</code>```

答:
One thing I do notice is that you're not reusing any of your uitableviewcells, so you're probably taking on a big performance hit.  In your code above, you're creating a new cell identifier for every row.  Try this instead:

```<code>- (UITableViewCell *) tableView:(UITableView *)inTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"Cell";
    UnSavedNoteListCell  *cell = (UnSavedNoteListCell *)[inTableView  dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        NSMutableArray *cellProgressNoteCollection = [self getcellProgressNoteCollectionForLandScape:indexPath];
        cell = [[[UnSavedNoteListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier cellTiles:cellProgressNoteCollection] autorelease];
        cell.backgroundColor = [UIColor clearColor];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    }

    return cell;
}
</code>```

This way, your tableview can maintain a list of tablecells that are marked for reuse.

Body:
I am seeing the following log...

"__NSAutoreleaseNoPool(): Object 0x58264b0 of class UITableViewCellContentView autoreleased with no pool in place - just leaking "

It is a huge release pool log, above is just one of the release log that i copied...

I have a CustomCell that adds tiles into itself depending on the business Logic. But the problem is when I call the creation of the cell, i see the above log messages. I don't see anything wrong with my code.. Does any one has any clue about it?

- (UITableViewCell *) tableView:(UITableView *)inTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UnSavedNoteListCell *cell;
    NSString *CellIdentifier = [@"Cell_" stringByAppendingString:[NSString stringWithFormat:@"%d", indexPath.row]];
     cell = (UnSavedNoteListCell *)[inTableView  dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{

    NSMutableArray *cellProgressNoteCollection = [self getcellProgressNoteCollectionForLandScape:indexPath];
    cell = [[[UnSavedNoteListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier cellTiles:cellProgressNoteCollection] autorelease];
    cell.backgroundColor = [UIColor clearColor];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

}

//    cell.textLabel.text = [NSString stringWithFormat:@"%d", rand()];
//    cell.textLabel.textColor = [UIColor redColor];
// Configure the cell...

return cell;
}

Body:
One thing I do notice is that you're not reusing any of your uitableviewcells, so you're probably taking on a big performance hit.  In your code above, you're creating a new cell identifier for every row.  Try this instead:

- (UITableViewCell *) tableView:(UITableView *)inTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"Cell";
    UnSavedNoteListCell  *cell = (UnSavedNoteListCell *)[inTableView  dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        NSMutableArray *cellProgressNoteCollection = [self getcellProgressNoteCollectionForLandScape:indexPath];
        cell = [[[UnSavedNoteListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier cellTiles:cellProgressNoteCollection] autorelease];
        cell.backgroundColor = [UIColor clearColor];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    }

    return cell;
}

This way, your tableview can maintain a list of tablecells that are marked for reuse.


问:
TypeScript Property 'navigation' is missing in type but required in type 'Props' React Native
In a React Native App, I understand that when you pass your RootNavigator inside createAppContainer and export it, the navigation prop is implicitly made available in all child components.

```<code>export default createAppContainer(AppNavigator);
</code>```

I have this component that is supposed to navigate to another screen using the navigation prop. I defined an interface for the props of this component like this:

props interface for ComponentA:

```<code>interface Props {
  count: number;
  navigation: NavigationStackProp<{quizId: number}>;
}
</code>```

Now I render ComponentA like this:

```<code>...
render() {
    return (
        <ComponentA count={0} /> // TypeScript screams here that I am not passing the navigation props
    );
}
</code>```

If I pass the navigation prop with ComponentA like this:

```<code><ComponentA count={0} navigation={props.navigation} />
</code>```

TypeScript is satisfied.

My question therefore is, do I have to pass navigation prop explicitly like this? It doesn't feel right to me. Is there a way I can suppress TypeScript warnings for this particular situation.

I am new to TypeScript so this might be something trivial but I will appreciate any help.

Thanks

答:
You can use optional props by having ?

```<code>interface Props {
  count: number;
  navigation?: NavigationStackProp<{quizId: number}>;
}
</code>```

Body:
In a React Native App, I understand that when you pass your RootNavigator inside createAppContainer and export it, the navigation prop is implicitly made available in all child components.

export default createAppContainer(AppNavigator);

I have this component that is supposed to navigate to another screen using the navigation prop. I defined an interface for the props of this component like this:

props interface for ComponentA:

interface Props {
  count: number;
  navigation: NavigationStackProp<{quizId: number}>;
}

Now I render ComponentA like this:

...
render() {
    return (
        <ComponentA count={0} /> // TypeScript screams here that I am not passing the navigation props
    );
}

If I pass the navigation prop with ComponentA like this:

<ComponentA count={0} navigation={props.navigation} />

TypeScript is satisfied.

My question therefore is, do I have to pass navigation prop explicitly like this? It doesn't feel right to me. Is there a way I can suppress TypeScript warnings for this particular situation.

I am new to TypeScript so this might be something trivial but I will appreciate any help.

Thanks

Body:
You can use optional props by having ?

interface Props {
  count: number;
  navigation?: NavigationStackProp<{quizId: number}>;
}