问:
Python script called from VBA called from Python is not working
I maintain an Excel with macro's that download some data from the internet. The downloading is done within Python (I will call this Python A), stored intermediately, and picked up by the Excel again. This Python flow is triggered by a macro within that Excel. Because I have to do this at specific times I wanted to automatize this by using another Python scheduler. The scheduler opens a
Nothing fancy, did that before, at least so I thought. The problem I am currently facing is that Python A is not running correctly when triggered from Python B. The Excel macro is running fine. I know that because some files are being exported, which is also done within a macro.

What I have tried so far:

Running the macro's manually is all fine

Setting all paths absolute, but that was already the case, so nothing to be improved there.

Calling the Python B flow from a bat file. This does work (?!)

Calling the bat from the scheduled flow does not work

Code in VBA:

```<code>cmdLine = "python ""path_with_spaces_to_file"" "

lngResult = ShellAndWait(cmdLine, 0, vbNormalFocus, AbandonWait)
</code>```

Code in Python B to call Macro:

```<code>import win32com.client
def func():
    filename_excel = r"filename_to_excel_with_spaces.xlsm"
    xl = win32com.client.DispatchEx('Excel.Application')
    xl.Visible = False

    xl.Workbooks.Open(Filename=filename_excel, ReadOnly=1)

    sheet = xl.ActiveWorkbook.Sheets("Sheetname")

    xl.Application.Run("Macroname")
    xl.DisplayAlerts = False
    xl.Application.Quit()
</code>```

How I call this function from the scheduler:

```<code>subprocess.run(["python3_location.bat", "-c", 'from python_B_file import func; func()'],
                stdout=subprocess.PIPE,
                cwd=r"path_to_python_B_file",
                universal_newlines=True,
                timeout=60)
</code>```

I see an extra cmd window popping up, but there is no new file downloaded. I cannot see an error message

答: Trying out different things, I found out that in the normal namespace the command python refers to the system defaults Python 2.7 installation, while the Python B is 3.7. Python A code was not Python 3 compatible (something with urllib, easily solved to something working in both Python versions). Calling the Excel macro from Python B changed the namespace somehow, and the ShellAndWait command referred to Python 3.7.

Body:
I maintain an Excel with macro's that download some data from the internet. The downloading is done within Python (I will call this Python A), stored intermediately, and picked up by the Excel again. This Python flow is triggered by a macro within that Excel. Because I have to do this at specific times I wanted to automatize this by using another Python scheduler. The scheduler opens a
Nothing fancy, did that before, at least so I thought. The problem I am currently facing is that Python A is not running correctly when triggered from Python B. The Excel macro is running fine. I know that because some files are being exported, which is also done within a macro.

What I have tried so far:

Running the macro's manually is all fine

Setting all paths absolute, but that was already the case, so nothing to be improved there.

Calling the Python B flow from a bat file. This does work (?!)

Calling the bat from the scheduled flow does not work

Code in VBA:

cmdLine = "python ""path_with_spaces_to_file"" "

lngResult = ShellAndWait(cmdLine, 0, vbNormalFocus, AbandonWait)

Code in Python B to call Macro:

import win32com.client
def func():
    filename_excel = r"filename_to_excel_with_spaces.xlsm"
    xl = win32com.client.DispatchEx('Excel.Application')
    xl.Visible = False

    xl.Workbooks.Open(Filename=filename_excel, ReadOnly=1)

    sheet = xl.ActiveWorkbook.Sheets("Sheetname")

    xl.Application.Run("Macroname")
    xl.DisplayAlerts = False
    xl.Application.Quit()

How I call this function from the scheduler:

subprocess.run(["python3_location.bat", "-c", 'from python_B_file import func; func()'],
                stdout=subprocess.PIPE,
                cwd=r"path_to_python_B_file",
                universal_newlines=True,
                timeout=60)

I see an extra cmd window popping up, but there is no new file downloaded. I cannot see an error message


来源: stackexchange

问:
Blazor WebAssembly: The provided ContentType is not supported;
I have installed the Blazor WebAssembly Example Project (WeatherForecast) today by the following command line:

```<code>dotnet new blazorwasm --hosted -o ProjectName
</code>```

I started the SPA directly after the installation via Visual Studio 2019 in Debug Mode. The Browser is: Chrome. The Browser shows the app, but when I select the Nav Menu "Fetch Data" then nothing happens. Chrome shows 1 Error:

```<code>Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.
System.NotSupportedException: The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.
  at System.Net.Http.Json.HttpContentJsonExtensions.ValidateContent (System.Net.Http.HttpContent content) <0x2e87f38 + 0x0009a> in <filename unknown>:0
  at System.Net.Http.Json.HttpContentJsonExtensions.ReadFromJsonAsync[T] (System.Net.Http.HttpContent content, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken) <0x2e87d30 + 0x00006> in <filename unknown>:0
  at System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsyncCore[T] (System.Threading.Tasks.Task`1[TResult] taskResponse, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken) <0x2e40838 + 0x0011c> in <filename unknown>:0
  at BlazorIssue.Client.Pages.FetchData.OnInitializedAsync () [0x00033] in D:\Projects\BlazorIssue\Client\Pages\FetchData.razor:43
  at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x2b8cb98 + 0x0013a> in <filename unknown>:0
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2dd8340 + 0x000b6> in <filename unknown>:0
</code>```

Chrome shows the following Request Headers:

Context-Information:

Chrome: V83.0.4103.61 (64bit)

Blazor: V3.2.0

Visual Studio: V16.6.0

DotNet V3.1.300

DotNet SDK: V3.1.300

That is curious because a fresh installation of this example project worked yesterday with no problems.

答: This can happen in the ASP.NET Hosted version of the Web Assembly template project if the Client project is designated as the Startup project. Ensure that the Server project is set as the Startup project.

ContentLicense: CC BY-SA 4.0

Body:
I have installed the Blazor WebAssembly Example Project (WeatherForecast) today by the following command line:

dotnet new blazorwasm --hosted -o ProjectName

I started the SPA directly after the installation via Visual Studio 2019 in Debug Mode. The Browser is: Chrome. The Browser shows the app, but when I select the Nav Menu "Fetch Data" then nothing happens. Chrome shows 1 Error:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.
System.NotSupportedException: The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.
  at System.Net.Http.Json.HttpContentJsonExtensions.ValidateContent (System.Net.Http.HttpContent content) <0x2e87f38 + 0x0009a> in <filename unknown>:0
  at System.Net.Http.Json.HttpContentJsonExtensions.ReadFromJsonAsync[T] (System.Net.Http.HttpContent content, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken) <0x2e87d30 + 0x00006> in <filename unknown>:0
  at System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsyncCore[T] (System.Threading.Tasks.Task`1[TResult] taskResponse, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken) <0x2e40838 + 0x0011c> in <filename unknown>:0
  at BlazorIssue.Client.Pages.FetchData.OnInitializedAsync () [0x00033] in D:\Projects\BlazorIssue\Client\Pages\FetchData.razor:43
  at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x2b8cb98 + 0x0013a> in <filename unknown>:0
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2dd8340 + 0x000b6> in <filename unknown>:0

Chrome shows the following Request Headers:

Context-Information:

Chrome: V83.0.4103.61 (64bit)

Blazor: V3.2.0

Visual Studio: V16.6.0

DotNet V3.1.300

DotNet SDK: V3.1.300

That is curious because a fresh installation of this example project worked yesterday with no problems.


问:
Spark JDBC: DataFrameReader fails to read Oracle table with datatype as ROWID
I am trying to read a Oracle table using spark.read.format and it works great for all tables except few tables which has any column with datatype as ROWID.

Below is my Code

```<code>var df = spark.read.format("jdbc").
        option("url", url).
        option("driver", driver).
        option("dbtable", dbTable).load()
println(df.first)
</code>```

I am getting the below error

```<code>18/09/08 11:38:17 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 5.0 (TID 23, gbrdsr000002985.intranet.barcapint.com, executor 21): java.sql.SQLException: Invalid column type: getLong not implemented for class oracle.jdbc.driver.T4CRowidAccessor
    at oracle.jdbc.driver.GeneratedAccessor.getLong(GeneratedAccessor.java:440)
    at oracle.jdbc.driver.GeneratedStatement.getLong(GeneratedStatement.java:228)
    at oracle.jdbc.driver.GeneratedScrollableResultSet.getLong(GeneratedScrollableResultSet.java:620)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$org$apache$spark$sql$execution$datasources$jdbc$JdbcUtils$$makeGetter$8.apply(JdbcUtils.scala:365)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$org$apache$spark$sql$execution$datasources$jdbc$JdbcUtils$$makeGetter$8.apply(JdbcUtils.scala:364)
</code>```

Analysis: I have checked JdbcUtils object and found that case java.sql.Types.ROWID is mapped to LongType of spark. But getLong is not implemented for ROWID type in Oracle JDBC driver.
I am confident that if i manage to map it to StringType then it will work but I could not found any workaround for this. Please suggest the solution here.

As of now, I am reading the data using ResultSet and later converting it to DataFrame using custom schema but it kills parallelism. Also wanted to check if any option to modify code of JdbcUtils as I am not able to extend DataFrameReader to create a custom one since "private[sql]" is mentioned in class definition.

答:
```<code>val df=spark.read
  .format("jdbc")
  .option("driver","oracle.jdbc.OracleDriver")
  .option("url","jdbc:oracle:thin:@localhost:1521:orcl")
  .option("user","oracle1")
  .option("password","oracle1")
  .option("dbtable","(select Cast(RID as VARCHAR2(18)) from sample.ALL_RESULTS_DATA)  my_table")
  .load()
</code>```

RID is a column name of data type ROWID in oracle.

The above code will cast the ROWID data type to String so that we can read it using Spark

RESULT:

```<code>-------------------------+
|CAST(RIDASVARCHAR2(18))AS|
+-------------------------+
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
</code>```

Body:
I am trying to read a Oracle table using spark.read.format and it works great for all tables except few tables which has any column with datatype as ROWID.

Below is my Code

var df = spark.read.format("jdbc").
        option("url", url).
        option("driver", driver).
        option("dbtable", dbTable).load()
println(df.first)

I am getting the below error

18/09/08 11:38:17 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 5.0 (TID 23, gbrdsr000002985.intranet.barcapint.com, executor 21): java.sql.SQLException: Invalid column type: getLong not implemented for class oracle.jdbc.driver.T4CRowidAccessor
    at oracle.jdbc.driver.GeneratedAccessor.getLong(GeneratedAccessor.java:440)
    at oracle.jdbc.driver.GeneratedStatement.getLong(GeneratedStatement.java:228)
    at oracle.jdbc.driver.GeneratedScrollableResultSet.getLong(GeneratedScrollableResultSet.java:620)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$org$apache$spark$sql$execution$datasources$jdbc$JdbcUtils$$makeGetter$8.apply(JdbcUtils.scala:365)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$org$apache$spark$sql$execution$datasources$jdbc$JdbcUtils$$makeGetter$8.apply(JdbcUtils.scala:364)

Analysis: I have checked JdbcUtils object and found that case java.sql.Types.ROWID is mapped to LongType of spark. But getLong is not implemented for ROWID type in Oracle JDBC driver.
I am confident that if i manage to map it to StringType then it will work but I could not found any workaround for this. Please suggest the solution here.

As of now, I am reading the data using ResultSet and later converting it to DataFrame using custom schema but it kills parallelism. Also wanted to check if any option to modify code of JdbcUtils as I am not able to extend DataFrameReader to create a custom one since "private[sql]" is mentioned in class definition.

Body:
val df=spark.read
  .format("jdbc")
  .option("driver","oracle.jdbc.OracleDriver")
  .option("url","jdbc:oracle:thin:@localhost:1521:orcl")
  .option("user","oracle1")
  .option("password","oracle1")
  .option("dbtable","(select Cast(RID as VARCHAR2(18)) from sample.ALL_RESULTS_DATA)  my_table")
  .load()

RID is a column name of data type ROWID in oracle.

The above code will cast the ROWID data type to String so that we can read it using Spark

RESULT:

-------------------------+
|CAST(RIDASVARCHAR2(18))AS|
+-------------------------+
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|
|       AAAIVuAABAAAMhCAAA|


问:
Convert a vertical data in a excel sheet with one header
I have a problem converting a long list of vertical address data into a a standard horizontal excel sheet with a header file.

What I have is this:

```<code>Name     Text Doe
Email    me@you.com
Operator     Someone
Product/Service  name of product
Phone   123 1234567
Company  ABC Company
Referrer URL     https://www.google.com.my/
Search Engine    Google
IP   210.186.133.177
Country/Region   Malaysia
State    Kuala Lumpur
City     Kuala Lumpur[Client Info]
Language     en-GB
Time Zone    GMT +08
Name     Text Doe
Email    me@you.com
Operator     Someone
Product/Service  name of product
Phone   123 1234567
Company  ABC Company
Referrer URL     https://www.google.com.my/
Search Engine    Google
IP   210.186.133.177
Country/Region   Malaysia
State    Kuala Lumpur
City     Kuala Lumpur[Client Info]
Language     en-GB
Time Zone    GMT +08
Name     Text Doe
Email    me@you.com
Operator     Someone
Product/Service  name of product
Phone   123 1234567
Company  ABC Company
Referrer URL     https://www.google.com.my/
Search Engine    Google
IP   210.186.133.177
Country/Region   Malaysia
State    Kuala Lumpur
City     Kuala Lumpur[Client Info]
Language     en-GB
Time Zone    GMT +08
</code>```

I try to find some automated way to parse this into a standard excel sheet where the labels on the side are horizontal on the top with the info below so that I can import it to a crm.

```<code>Name     Email   Operator    Product/Service     Phone  Company  Referrer URL    Search Engine   Google    IP    Country/Region  State   City    Language    Time Zone
</code>```

with the info on the cells below. Is there a easy way to do this in a VB script or any other way?

答:
I have accomplished my task.
I made a simple formula to parse the cells and repeat it every 14 rows since there is 14 labels that repeat over and over.

The formula I used is:

```<code>=INDEX($B:$B,ROW(B2)*14+COLUMN(B2))
</code>```

Because Column A are the labels and Column B is the data.
So this simply parses every 14th row to the list.

Body:
I have a problem converting a long list of vertical address data into a a standard horizontal excel sheet with a header file.

What I have is this:

Name     Text Doe
Email    me@you.com
Operator     Someone
Product/Service  name of product
Phone   123 1234567
Company  ABC Company
Referrer URL     https://www.google.com.my/
Search Engine    Google
IP   210.186.133.177
Country/Region   Malaysia
State    Kuala Lumpur
City     Kuala Lumpur[Client Info]
Language     en-GB
Time Zone    GMT +08
Name     Text Doe
Email    me@you.com
Operator     Someone
Product/Service  name of product
Phone   123 1234567
Company  ABC Company
Referrer URL     https://www.google.com.my/
Search Engine    Google
IP   210.186.133.177
Country/Region   Malaysia
State    Kuala Lumpur
City     Kuala Lumpur[Client Info]
Language     en-GB
Time Zone    GMT +08
Name     Text Doe
Email    me@you.com
Operator     Someone
Product/Service  name of product
Phone   123 1234567
Company  ABC Company
Referrer URL     https://www.google.com.my/
Search Engine    Google
IP   210.186.133.177
Country/Region   Malaysia
State    Kuala Lumpur
City     Kuala Lumpur[Client Info]
Language     en-GB
Time Zone    GMT +08

I try to find some automated way to parse this into a standard excel sheet where the labels on the side are horizontal on the top with the info below so that I can import it to a crm.

Name     Email   Operator    Product/Service     Phone  Company  Referrer URL    Search Engine   Google    IP    Country/Region  State   City    Language    Time Zone

with the info on the cells below. Is there a easy way to do this in a VB script or any other way?

Body:
I have accomplished my task.
I made a simple formula to parse the cells and repeat it every 14 rows since there is 14 labels that repeat over and over.

The formula I used is:

=INDEX($B:$B,ROW(B2)*14+COLUMN(B2))

Because Column A are the labels and Column B is the data.
So this simply parses every 14th row to the list.


问:
Using the Aftersave event
I have this sheet where I want to make a copy of it everytime you save the original sheet.

To achieve this I was trying to use AfterSave on ThisWorkBook which calls a macro on a module.

The code is below:

```<code>Private Sub Workbook_AfterSave(ByVal Success As Boolean)

If Success Then
Application.EnableEvents = False

Call CopiarNovaPlanilha

Application.EnableEvents = True
End If
End Sub
</code>```

The Application.EnableEvents is just to avoid a loop as I learnt  HERE. Here'S the macro inside the module :

```<code>Sub CopiarNovaPlanilha()

ActiveWorkbook.SaveCopyAs "I:\CGP\DEOPEX\01 - Supervisão\10 - Alocação das equipes\Consulta Alocados\ALOCACAO TECNICOS.xlsx"

End Sub
</code>```

This code is working perfectly although the AfterSave isn't, so when I save my original file it's not calling my sub as it should.

Anyone knows what is happening with this event?

答: I had the issue that the AfterSave event didn't fire and I found out that this happens only when the visual basic development environment is open. When I close the VBA editor, the AfterSave event fires as expected.

Title: Using the Aftersave event

Body:
I have this sheet where I want to make a copy of it everytime you save the original sheet.

To achieve this I was trying to use AfterSave on ThisWorkBook which calls a macro on a module.

The code is below:

Private Sub Workbook_AfterSave(ByVal Success As Boolean)

If Success Then
Application.EnableEvents = False

Call CopiarNovaPlanilha

Application.EnableEvents = True
End If
End Sub

The Application.EnableEvents is just to avoid a loop as I learnt  HERE. Here'S the macro inside the module :

Sub CopiarNovaPlanilha()

ActiveWorkbook.SaveCopyAs "I:\CGP\DEOPEX\01 - Supervisão\10 - Alocação das equipes\Consulta Alocados\ALOCACAO TECNICOS.xlsx"

End Sub

This code is working perfectly although the AfterSave isn't, so when I save my original file it's not calling my sub as it should.

Anyone knows what is happening with this event?


问:
Problem with Login control of ASP.NET
I set up a website to use SqlMembershipProvider as written on this page.

I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.

I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in.

I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.

I already tried to handle the events by myself and check, what is happening in them, but no success.

I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.

Any ideas?

Resolution: After some mailing with Rob we have the ideal solution, which is now the accepted answer.

答:
Do you have requireSSL="true" in your web.config?
I had similar symptoms to you. If you set requireSSL to true, there are some additional considerations.

OwnerDisplayName: Biri

ContentLicense: CC BY-SA 2.5

Title: Problem with Login control of ASP.NET

LastEditorDisplayName: Biri

OwnerDisplayName: Chris


问:
Linq To SQL Without Explicit Foreign Key Relationships
I am working with a few legacy tables that have relationships, but those relationships haven't been explicitly set as primary/foreign keys.  I created a .dbml file using "Linq To Sql Classes" and established the proper Case.CaseID = CaseInfo.CaseID association.  My resulting class is CasesDataContext.

My Tables (One to many):

```<code>Case
------------------
CaseID (int not null)
MetaColumn1 (varchar)
MetaColumn2 (varchar)
MetaColumn3 (varchar)
...

CaseInfo
------------------
CaseInfoID (int)
CaseID (int nulls allowed)
CaseInfoMeta (varchar)
...
</code>```

I'm new to LinqToSQL and am having trouble doing..

```<code>CasesDataContext db = new CasesDataContext();
var Cases = from c in db.Cases
            where c.CaseInfo.CaseInfoMeta == "some value"
            select c;
</code>```

(Edit) My problem being that CaseInfo or CaseInfos
is not available as a member of Cases.

I heard from a colleague that I might try ADO.Net Entity Data Model to create my Data Context class, but haven't tried that yet and wanted to see if I'd be wasting my time or should I go another route. Any tips, links, help would be most appreciated.

答:
Go back to the designer and check the relation is set up correctly. Here is one real life example, with BillStateMasters have "CustomerMasters1" property (customers for the state):

Ps. naming is being cleaned up ...

Update 1: You also need to make sure both tables have a primary defined. If the primary key isn't defined on the database (and can't be defined for whatever reason), make sure to define them in the designer. Open the column's properties, and set it as primary key. That said, entity tracking also won't work if you haven't a primary key for the entity, which for deletes means it silently doesn't updates the entity. So, make sure to review all entities and to have them all with a primary key (as I said, if it can't be on the db, then on the designer).

OwnerDisplayName: madcolor

Body:
I am working with a few legacy tables that have relationships, but those relationships haven't been explicitly set as primary/foreign keys.  I created a .dbml file using "Linq To Sql Classes" and established the proper Case.CaseID = CaseInfo.CaseID association.  My resulting class is CasesDataContext.

My Tables (One to many):

Case
------------------
CaseID (int not null)
MetaColumn1 (varchar)
MetaColumn2 (varchar)
MetaColumn3 (varchar)
...

CaseInfo
------------------
CaseInfoID (int)
CaseID (int nulls allowed)
CaseInfoMeta (varchar)
...

I'm new to LinqToSQL and am having trouble doing..

CasesDataContext db = new CasesDataContext();
var Cases = from c in db.Cases
            where c.CaseInfo.CaseInfoMeta == "some value"
            select c;

(Edit) My problem being that CaseInfo or CaseInfos
is not available as a member of Cases.

I heard from a colleague that I might try ADO.Net Entity Data Model to create my Data Context class, but haven't tried that yet and wanted to see if I'd be wasting my time or should I go another route. Any tips, links, help would be most appreciated.

LastEditorDisplayName: madcolor

OwnerDisplayName: Freddy Rios

LastEditorDisplayName: Freddy Rios


问:
.Net Core Automapper missing type map configuration or unsupported mapping
Net core application. I am trying to use Auto mapper but results in the below error.

```<code>.Net Core Automapper missing type map configuration or unsupported mapping
</code>```

I have below setup in startup.cs

```<code>var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);
</code>```

Then I am using profiles.

```<code>  public class MappingProfile : Profile
    {

        public MappingProfile()
        {
            this.CreateMap<Geography, GeographyEntity>();
            this.CreateMap<Model1, Model2>();
        }

    }
</code>```

I am using auto mapper as below

```<code> Model1 model = this.Mapper.Map<Model1>(Model2);
</code>```

Below are the models

```<code> public partial class Model1
    {
        public int SNo { get; set; }
        public string SarNo { get; set; }
        public string SiteName { get; set; }
        public string Client { get; set; }
        public int CId { get; set; }
        public DateTime StartDate { get; set; }
        public bool IsActive { get; set; }

        public virtual Model2 C { get; set; }
    }

public class Model2
{
    public int SNo { get; set; }

    public string SarNo { get; set; }

    public string SiteName { get; set; }

    public int CId { get; set; }

    public string Client { get; set; }

    public bool? IsActive { get; set; }

    public DateTime StartDate { get; set; }

}
</code>```

I get below error in auto mapper.

AutoMapper.AutoMapperMappingException: Missing type map configuration
  or unsupported mapping.

can someone help me to understand this error? Any help would be greatly appreciated. Thanks

答:
this.CreateMap<Model1, Model2>(); will create map from Model1 to Model2, so this should work:

```<code>Model2 model = this.Mapper.Map<Model2>(new Model1());
</code>```

If you want it vise versa either change the registration to:

```<code>this.CreateMap<Model2, Model1>();
</code>```

or add ReverseMap to have bidirectional one:

```<code>this.CreateMap<Model1, Model2>().ReverseMap();
</code>```

Body:
Net core application. I am trying to use Auto mapper but results in the below error.

.Net Core Automapper missing type map configuration or unsupported mapping

I have below setup in startup.cs

var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

Then I am using profiles.

  public class MappingProfile : Profile
    {

        public MappingProfile()
        {
            this.CreateMap<Geography, GeographyEntity>();
            this.CreateMap<Model1, Model2>();
        }

    }

I am using auto mapper as below

 Model1 model = this.Mapper.Map<Model1>(Model2);

Below are the models

 public partial class Model1
    {
        public int SNo { get; set; }
        public string SarNo { get; set; }
        public string SiteName { get; set; }
        public string Client { get; set; }
        public int CId { get; set; }
        public DateTime StartDate { get; set; }
        public bool IsActive { get; set; }

        public virtual Model2 C { get; set; }
    }

public class Model2
{
    public int SNo { get; set; }

    public string SarNo { get; set; }

    public string SiteName { get; set; }

    public int CId { get; set; }

    public string Client { get; set; }

    public bool? IsActive { get; set; }

    public DateTime StartDate { get; set; }

}

I get below error in auto mapper.

AutoMapper.AutoMapperMappingException: Missing type map configuration
  or unsupported mapping.

can someone help me to understand this error? Any help would be greatly appreciated. Thanks

Body:
this.CreateMap<Model1, Model2>(); will create map from Model1 to Model2, so this should work:

Model2 model = this.Mapper.Map<Model2>(new Model1());

If you want it vise versa either change the registration to:

this.CreateMap<Model2, Model1>();

or add ReverseMap to have bidirectional one:

this.CreateMap<Model1, Model2>().ReverseMap();


问:
why does my browser reloads when using ajax?
i created an ajax function that when clicked by a user it adds a messages to his favorites tab. i want it to work similar to a twitter like button so when a user clicks the favorite button it does not reload the page. i created everything correctly and even the ajax function calls the php file and inserts everything into the database, its just that it still reloads the page after the clicking.

my ajax code:

```<code> <script>
        function GetXmlHttpObject() {
      var xmlHttp=null;
      try
        {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
        }
    catch (e)
        {
        // Internet Explorer
        try
            { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e)
            { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
        }
    r  eturn xmlHttp;
   }
      function ajaxfav(){
       var xmlHttp=GetXmlHttpObject();
       var url="favorite.php?message="+document.msgidform.fav_message.value;
      xmlHttp.onreadystatechange=function(){
        if(xmlHttp.readyState==4){
        alert("Message is favorited");

        }
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);

}
  </script>
</code>```

my php code:

```<code>   $user_id = $_SESSION['active_user_id'];
    extract($_POST);
    extract($_GET);
    if(isset($_GET['message']))
    {
        $id=$_GET['message'];

        $q=$db->prepare("SELECT msgid,date,text

        FROM messages
        WHERE to_id=? and msgid=?");
        $q->bindValue(1,$user_id);
        $q->bindValue(2,$id);
        $q->execute();
        $row2=$q->fetch();
        $d=$row2['date'];

        $fav_questionq=$db->prepare("SELECT *
        FROM messages
        LEFT JOIN users
        ON messages.to_id=users.id
        WHERE users.id=? AND messages.msgid=?

        ");
        $fav_questionq->bindValue(1,$user_id);
        $fav_questionq->bindValue(2,$id);
        $fav_questionq->execute();
        $frow=$fav_questionq->fetch();

        $fquestion= $frow['text'];

        $result = $db->prepare("SELECT * FROM fav_messages
                            WHERE username=? AND message=?");
        $result-bindValue(1,$user_id);
        $result-bindValue(2,$id);
        $result->execute();

    if($result->rowCount()== 1 )
    {
        $deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
        $deletequery->bindValue(1,$id);
        $deletequery->execute();
    echo("<script>location.href = 'index.php?a=recieved';</script>");
    }
    else
    {
    $insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
    $insertquery->bindValue(1,$user_id);
    $insertquery->bindValue(2,$id);
    $insertquery->bindValue(3,$fquestion);
    $insertquery->bindValue(4,$d);
    $insertquery-execute();
    }
    echo("<script>location.href = 'index.php?a=recieved';</script>");
    }
</code>```

my html code:

```<code>     <form name="msgidform" method="post">
        <input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>></p>
    </form>

           <a class="msg-icon" href="" onclick="ajaxfav();"><img
            src="images/linedfav.png" id='img'></img></a>
</code>```

why does my browser still reloads even though i am using ajax?

答: It's is because you're using  tag, even in you don't provide a href attribute it will redirect you, in your case to homepage that's why you have the reload effect. A way to solve it would be to create a fake anchor tag by using tag that would have the styles of  tag and attaching your ajax function to the  tag

Body:
i created an ajax function that when clicked by a user it adds a messages to his favorites tab. i want it to work similar to a twitter like button so when a user clicks the favorite button it does not reload the page. i created everything correctly and even the ajax function calls the php file and inserts everything into the database, its just that it still reloads the page after the clicking.

my ajax code:

my php code:

   $user_id = $_SESSION['active_user_id'];
    extract($_POST);
    extract($_GET);
    if(isset($_GET['message']))
    {
        $id=$_GET['message'];

        $q=$db->prepare("SELECT msgid,date,text

        FROM messages
        WHERE to_id=? and msgid=?");
        $q->bindValue(1,$user_id);
        $q->bindValue(2,$id);
        $q->execute();
        $row2=$q->fetch();
        $d=$row2['date'];

        $fav_questionq=$db->prepare("SELECT *
        FROM messages
        LEFT JOIN users
        ON messages.to_id=users.id
        WHERE users.id=? AND messages.msgid=?

        ");
        $fav_questionq->bindValue(1,$user_id);
        $fav_questionq->bindValue(2,$id);
        $fav_questionq->execute();
        $frow=$fav_questionq->fetch();

        $fquestion= $frow['text'];

        $result = $db->prepare("SELECT * FROM fav_messages
                            WHERE username=? AND message=?");
        $result-bindValue(1,$user_id);
        $result-bindValue(2,$id);
        $result->execute();

    if($result->rowCount()== 1 )
    {
        $deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
        $deletequery->bindValue(1,$id);
        $deletequery->execute();
    echo("");
    }
    else
    {
    $insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
    $insertquery->bindValue(1,$user_id);
    $insertquery->bindValue(2,$id);
    $insertquery->bindValue(3,$fquestion);
    $insertquery->bindValue(4,$d);
    $insertquery-execute();
    }
    echo("");
    }

my html code:

     <form name="msgidform" method="post">
        <input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>>

    </form>

why does my browser still reloads even though i am using ajax?

Body: It's is because you're using <a> tag, even in you don't provide a href attribute it will redirect you, in your case to homepage that's why you have the reload effect. A way to solve it would be to create a fake anchor tag by using <span>tag that would have the styles of <a> tag and attaching your ajax function to the <span> tag


问:
Twilio Room does not recognize connected participants
I'm using twilio as a service for a video chat app.
The room is will contain only 2 participants P1 & P2

P1

Gets a generated access token from the backend( with room grants added)

Gets the room name from the server

Connects to room

```<code>let connectOptions = TVIConnectOptions.init(token: payload.twilioAccessToken) { (builder) in
    builder.roomName = payload.roomName
}
twilioLog("Will Connect to room with name \(String(describing: payload.roomName))")

self.room = TwilioVideo.connect(with: connectOptions, delegate:self)
</code>```

func didConnect(to room: TVIRoom) Called Successfully.

P2

Gets a different  generated access token from the backend( with room grants added)

Gets the same room name from the server

Connects to room

```<code>let connectOptions = TVIConnectOptions.init(token: payload.twilioAccessToken) { (builder) in
    builder.roomName = payload.roomName
}
twilioLog("Will Connect to room with name \(String(describing: payload.roomName))")

self.room = TwilioVideo.connect(with: connectOptions, delegate:self)
</code>```

func didConnect(to room: TVIRoom) Called Successfully.

However, func room(_ room: TVIRoom, participantDidConnect participant: TVIParticipant) Never gets called.
Also, room.participants returns an empty array.

答: The issue was that P1 & P2 had the same identifiers. They are treated as the same participant </p>

Body:
I'm using twilio as a service for a video chat app.
The room is will contain only 2 participants P1 & P2

P1

Gets a generated access token from the backend( with room grants added)

Gets the room name from the server

Connects to room

let connectOptions = TVIConnectOptions.init(token: payload.twilioAccessToken) { (builder) in
    builder.roomName = payload.roomName
}
twilioLog("Will Connect to room with name \(String(describing: payload.roomName))")

self.room = TwilioVideo.connect(with: connectOptions, delegate:self)

func didConnect(to room: TVIRoom) Called Successfully.

P2

Gets a different  generated access token from the backend( with room grants added)

Gets the same room name from the server

Connects to room

let connectOptions = TVIConnectOptions.init(token: payload.twilioAccessToken) { (builder) in
    builder.roomName = payload.roomName
}
twilioLog("Will Connect to room with name \(String(describing: payload.roomName))")

self.room = TwilioVideo.connect(with: connectOptions, delegate:self)

func didConnect(to room: TVIRoom) Called Successfully.

However, func room(_ room: TVIRoom, participantDidConnect participant: TVIParticipant) Never gets called.
Also, room.participants returns an empty array.


问:
Can input type object contains a property of interface type?
I've only started learning GraphQL on .net platform.
If input type object can contains property of interface type then how to configure it in HotChocolate library?

An example of model:

```<code>public interface ILocationFilter {
    double Lat { get; set;}
    double Lng { get; set;}
}

public class LocationFilter : ILocationFilter {
// ...
}

public class FilterModel {
    public string Search { get; set; }
    public ILocationFilter Location { get; set; } = new LocationFilter();
// ...
}
</code>```

GraphQL Query example:

```<code>public class Query {
    public IEnumerable<SomeModel> GetByFilter(FilterModel filter) {
// ...
    }
}
</code>```

Startup.cs example:

```<code>// ...
services.AddGraphQL(SchemaBuilder.New()
                        .AddQueryType<Query>()
                        .Create(),
                    new QueryExecutionOptions { IncludeExceptionDetails = true });
// ...
    app.UseGrapQL();
// ...
</code>```

Right now I get an exception "Unable to infer or resolve a schema type from the type reference Input: ILocationFilter".

BTW: If remove interface everything will be work.

What should I configure to correct working with properties of interface type?

答:
```<code>public class FilterModelType : InputObjectType<FilterModel> {
    protected override void Configure(IInputObjectTypeDescriptor<FilterModel> descriptor)
    {
        descriptor.Field(x => x.Location).Type(typeof(LocationFilter));
    }
}
</code>```

I've added a new class which describe a FilterModel. After that I also registered this type in Startup.cs

```<code> SchemaBuilder.New()
    .AddType<FilterModelType>()
    .AddQueryType<Query>()
    .Create()
</code>```

It works for me.

Body:
I've only started learning GraphQL on .net platform.
If input type object can contains property of interface type then how to configure it in HotChocolate library?

An example of model:

public interface ILocationFilter {
    double Lat { get; set;}
    double Lng { get; set;}
}

public class LocationFilter : ILocationFilter {
// ...
}

public class FilterModel {
    public string Search { get; set; }
    public ILocationFilter Location { get; set; } = new LocationFilter();
// ...
}

GraphQL Query example:

public class Query {
    public IEnumerable<SomeModel> GetByFilter(FilterModel filter) {
// ...
    }
}

Startup.cs example:

// ...
services.AddGraphQL(SchemaBuilder.New()
                        .AddQueryType<Query>()
                        .Create(),
                    new QueryExecutionOptions { IncludeExceptionDetails = true });
// ...
    app.UseGrapQL();
// ...

Right now I get an exception "Unable to infer or resolve a schema type from the type reference Input: ILocationFilter".

BTW: If remove interface everything will be work.

What should I configure to correct working with properties of interface type?

Body:
public class FilterModelType : InputObjectType<FilterModel> {
    protected override void Configure(IInputObjectTypeDescriptor<FilterModel> descriptor)
    {
        descriptor.Field(x => x.Location).Type(typeof(LocationFilter));
    }
}

I've added a new class which describe a FilterModel. After that I also registered this type in Startup.cs

 SchemaBuilder.New()
    .AddType<FilterModelType>()
    .AddQueryType<Query>()
    .Create()

It works for me.


问:
Numpy mask array multiple times and fill nans in 3D array with values from another 3D array
I have the following code:

```<code>import numpy as np

def fill(arr1, arr2, arr3, arr4, thresh= 0.5):
    out_arr = np.zeros(arr1.shape)
    for i in range(0,len(arr1)):
        arr1[i] = np.where(np.abs(arr1[i])<=thresh,np.nan,arr1[i])
        mask = np.isnan(arr1[i])
        arr1[i] = np.nan_to_num(arr1[i])
        merged1 = (arr2[i]*mask)+arr1[i]

        merged2 = np.where(np.abs(merged1)<=thresh,np.nan,merged1)
        mask = np.isnan(merged2)
        merged2 = np.nan_to_num(merged2)
        merged3 = (arr3[i]*mask)+merged2

        merged3 = np.where(np.abs(merged3)<=thresh,np.nan,merged3)
        mask = np.isnan(merged3)
        merged3 = np.nan_to_num(merged3)
        merged4 = (arr4[i]*mask)+merged3

        out_arr[i] = merged4

    return(out_arr)

arr1 = np.random.rand(10, 10, 10)
arr2 = np.random.rand(10, 10, 10)
arr3 = np.random.rand(10, 10, 10)
arr4 = np.random.rand(10, 10, 10)
arr = fill(arr1, arr2, arr3, arr4, 0.5)
</code>```

I wonder if there is a more efficient way of doing this maybe with masked arrays? Basically what I am doing is to replace values below the threshold in each layer of the 3D array with the next array, and this over 4 arrays. How would this look like for n arrays?
Thanks!

答:
Your function can be simplified in several ways. In terms of efficiency, the most significant aspect is that you do not need to iterate over the first dimension, you can operate on the whole arrays directly. Besides that, you can refactor the replacement logic to something much simpler, and use a a loop to avoid repeating the same code over and over:

import numpy as np

# Function accepts as many arrays as wanted, with at least one
# (threshold needs to be passed as keyword parameter)
def fill(arr1, *arrs, thresh=0.5):
    # Output array
    out_arr = arr1.copy()
    for arr in arrs:
        # Replace values that are still below threshold
        mask = np.abs(out_arr) <= thresh
        out_arr[mask] = arr[mask]
    return out_arr
```

<p>Since <code>thresh</code> needs to be passed as keyword parameter in this function, you would call it as:</p>

<pre class="lang-py prettyprint-override"><code>arr = fill(arr1, arr2, arr3, arr4, thresh=0.5)
</code>```

Body:
I have the following code:

import numpy as np

def fill(arr1, arr2, arr3, arr4, thresh= 0.5):
    out_arr = np.zeros(arr1.shape)
    for i in range(0,len(arr1)):
        arr1[i] = np.where(np.abs(arr1[i])<=thresh,np.nan,arr1[i])
        mask = np.isnan(arr1[i])
        arr1[i] = np.nan_to_num(arr1[i])
        merged1 = (arr2[i]*mask)+arr1[i]

        merged2 = np.where(np.abs(merged1)<=thresh,np.nan,merged1)
        mask = np.isnan(merged2)
        merged2 = np.nan_to_num(merged2)
        merged3 = (arr3[i]*mask)+merged2

        merged3 = np.where(np.abs(merged3)<=thresh,np.nan,merged3)
        mask = np.isnan(merged3)
        merged3 = np.nan_to_num(merged3)
        merged4 = (arr4[i]*mask)+merged3

        out_arr[i] = merged4

    return(out_arr)

arr1 = np.random.rand(10, 10, 10)
arr2 = np.random.rand(10, 10, 10)
arr3 = np.random.rand(10, 10, 10)
arr4 = np.random.rand(10, 10, 10)
arr = fill(arr1, arr2, arr3, arr4, 0.5)

I wonder if there is a more efficient way of doing this maybe with masked arrays? Basically what I am doing is to replace values below the threshold in each layer of the 3D array with the next array, and this over 4 arrays. How would this look like for n arrays?
Thanks!

Body:
Your function can be simplified in several ways. In terms of efficiency, the most significant aspect is that you do not need to iterate over the first dimension, you can operate on the whole arrays directly. Besides that, you can refactor the replacement logic to something much simpler, and use a a loop to avoid repeating the same code over and over:

import numpy as np

# Function accepts as many arrays as wanted, with at least one
# (threshold needs to be passed as keyword parameter)
def fill(arr1, *arrs, thresh=0.5):
    # Output array
    out_arr = arr1.copy()
    for arr in arrs:
        # Replace values that are still below threshold
        mask = np.abs(out_arr) <= thresh
        out_arr[mask] = arr[mask]
    return out_arr

Since thresh needs to be passed as keyword parameter in this function, you would call it as:

arr = fill(arr1, arr2, arr3, arr4, thresh=0.5)


问:
separate lines according to a string in them in python
I have a file containing (~1000) lines of data in the following -simplified- form:

```<code>movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
# Various comments
## Various comments
### Various comments
</code>```

And I need to separate the lines in two sets (for later conversion to pandas dataframes), one set consisting of the lines with the p -starting with "movej(p[" or "movel(p[" and the other consisting of the lines without the p -starting with "movej([" or "movel([".

```<code>movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)

and

movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
</code>```

To do so, I have created the following code that almost does the job.

The issue I am experiencing is that it stops or doesn't store everything in the TCP_lines and joint_lines strings.
I have also tried using list with the same result.

```<code>with open("SRP_Assemble all BUSH_BEARING onto HPC_FRONT_BOTTOM.script", "r") as f:
    lines = f.readlines()
    TCP_lines = ""
    joint_lines = ""

    for line in lines:
        if line.startswith(("movej(p" ,"movel(p")):
            TCP_lines += line
        elif line.startswith(("movej(" ,"movel(")):
            joint_lines += line

print (TCP_lines)
print (joint_lines)
</code>```

EDIT:
Does the console have a limited space to print results?
So it only prints the first couple of rows?

I used a redirector to print the results in a text box and it looks fine...

答:
Move the print statements inside the context manager and add a debugging line, Like so:

```<code>with open("SRP_Assemble all BUSH_BEARING onto HPC_FRONT_BOTTOM.script", "r") as f:
    lines = f.readlines()
    TCP_lines = ""
    joint_lines = ""

    for line in lines:
        if line.startswith(("movej(p", "movel(p")):
            TCP_lines += line
        elif line.startswith(("movej(", "movel(")):
            joint_lines += line
        else:
            print(line)  # Check all other lines if they failed to pass the check
    print(TCP_lines)
    print(joint_lines)
</code>```

This outputs:

```<code>movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)

movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
...
</code>```

Body:
I have a file containing (~1000) lines of data in the following -simplified- form:

movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
# Various comments
## Various comments
### Various comments

And I need to separate the lines in two sets (for later conversion to pandas dataframes), one set consisting of the lines with the p -starting with "movej(p[" or "movel(p[" and the other consisting of the lines without the p -starting with "movej([" or "movel([".

movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)

and

movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)

To do so, I have created the following code that almost does the job.

The issue I am experiencing is that it stops or doesn't store everything in the TCP_lines and joint_lines strings.
I have also tried using list with the same result.

with open("SRP_Assemble all BUSH_BEARING onto HPC_FRONT_BOTTOM.script", "r") as f:
    lines = f.readlines()
    TCP_lines = ""
    joint_lines = ""

    for line in lines:
        if line.startswith(("movej(p" ,"movel(p")):
            TCP_lines += line
        elif line.startswith(("movej(" ,"movel(")):
            joint_lines += line

print (TCP_lines)
print (joint_lines)

EDIT:
Does the console have a limited space to print results?
So it only prints the first couple of rows?

I used a redirector to print the results in a text box and it looks fine...

Body:
Move the print statements inside the context manager and add a debugging line, Like so:

with open("SRP_Assemble all BUSH_BEARING onto HPC_FRONT_BOTTOM.script", "r") as f:
    lines = f.readlines()
    TCP_lines = ""
    joint_lines = ""

    for line in lines:
        if line.startswith(("movej(p", "movel(p")):
            TCP_lines += line
        elif line.startswith(("movej(", "movel(")):
            joint_lines += line
        else:
            print(line)  # Check all other lines if they failed to pass the check
    print(TCP_lines)
    print(joint_lines)

This outputs:

movej(p[-0.2875, -0.4, 0.05, -0.0004, 3.1415, 0.0002],a=5.000000,v=5.000000,r=0.000000)
movel(p[-0.2875, -0.375, 0.0, -0.0004, 3.1415, 0.0002],a=0.500000,v=0.300000,r=0.000000)

movej([-1.3615, -2.0244, -1.5691, -2.6895, 0.2092, 1.2197],a=5.000000,v=5.000000,r=0.050000)
movel([-1.2437, -1.9458, -2.0485, -2.2887, 0.0128, 1.2197],a=5.000000,v=5.000000,r=0.050000)
...


问:
ModuleNotFound errorin falcon
I am following the official falcon tutorial and there, they have used waitress-serve --port=8000 falcon.app:api to run the server. However, when I run this line in my terminal, it says

There was an exception (ModuleNotFoundError) importing your module.

It had these arguments:

No module named 'falcon.app'

There's a falcon folder(the app.py lies here) inside falcon directory. When I go to the falcon folder then run app:api, it runs. I am so confused.

app.py file:

```<code>import falcon
from waitress import serve
from images import Resource
api = application = falcon.API()
images = Resource()
api.add_route('/images', images)
</code>```

答:
Try

```<code>waitress-serve --port=8000 app:api
</code>```

you don't need to specify the framework name. "app" is the name of the file and "api" is the name of object, you need to specify only these two things.

Title: ModuleNotFound errorin falcon

Body:
I am following the official falcon tutorial and there, they have used waitress-serve --port=8000 falcon.app:api to run the server. However, when I run this line in my terminal, it says

There was an exception (ModuleNotFoundError) importing your module.

It had these arguments:

No module named 'falcon.app'

There's a falcon folder(the app.py lies here) inside falcon directory. When I go to the falcon folder then run app:api, it runs. I am so confused.

app.py file:

import falcon
from waitress import serve
from images import Resource
api = application = falcon.API()
images = Resource()
api.add_route('/images', images)

Body:
Try

waitress-serve --port=8000 app:api

you don't need to specify the framework name. "app" is the name of the file and "api" is the name of object, you need to specify only these two things.


问:
TCPDF skipping items after a row and printing some lines of data only
I am using TCPDF in yii2, for one single data set, it is skipping rows after 3rd row. This is happening randomly and for just one data set, I tried printing the data set and it looks OK without any missed td/tr/any other closing syntax.

Not sure what is the issue.

答:
Ok, found out the issue, one of the row content had < in it and this was causing the whole issue.

So added htmlentities() around each of the content (make sure that this is added for content string only) and this resolved the issue.

So always make sure that while printing data in PDF sanitize < > ? ' " etc. special characters which might create issue in printing.

Hope it is of use to someone facing the same issue.


问:
Dark mode without JavaScript
I have a small website using only PHP, HTML, and CSS and want to add Dark Mode on it. I've found a lot solutions, but all of them use JavaScript. Is that possible to add Dark Mode without JS?</p>

答:
You already have all you need.  Browser detection is done with CSS following the Media Queries Level 5 specification using a prefers-color-scheme media query for detection.  If you're familiar with responsive web-design with CSS then you already have all the knowledge - the only difference is that responsive CSS is about geography (sizes, columns, padding, spacing, font-size, etc.) and prefers-color-scheme is about ... well ... color.  Thomas Steiner (@DenverCoder9) has an awesome article "prefers-color-scheme: Hello darkness, my old friend" that covers this.

If you are asking about PHP specifically then you are out of luck - there is no dark mode detection methodology for server side-processing.

All efforts thus-far by the W3C (and its sponsors) has been focused on client-side / Jamstack.

There is a recommendation by Thomas Steiner (same guy) to implement a Proposed server-side client hint, but this has not been adopted (yet?) by the W3C or the browsers.

Either way - there is a significant drawback in server-side detection (both with Thomas' recommendation and my solution below) in that the server will only know about a state change (e.g. macOS "Auto" mode when night fall happens) on the next server request, or more visibly, the first load of the page.

My recommendation is to leverage CSS / client-side only on this - Thomas gives some practical guidance on two methods,

1x CSS with both color schemes supported, and

2x CSS, with one being light and the other dark.  I've made a educative whitepaper applying some of these methods with the CSS framework Bootstrap at vinorodrigues/bootstrap-dark to show how easy that can be - without server-side processing.

Having said that - if you must insist on PHP or server-side detection there is no workaround - but one must use some JS.  The most efficient way is to leverage the js-cookie/js-cookie project, and include the following code into your HTML pages:

```

<p>And then your PHP will detect this cookie like this:</p>

<pre class="lang-php prettyprint-override"><code>  $color_scheme = isset($_COOKIE["color_scheme"]) ? $_COOKIE["color_scheme"] : false;
  if ($color_scheme === false) $color_scheme = 'light';  // fallback
</code>```

Which you can use to load the CSS:

  // Load the CSS for the correct color-scheme
  if ($color_scheme == 'dark') {
    ?><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/vinorodrigues/bootstrap-dark@0.0/dist/bootstrap-night.min.css"><?php
  } else {
    ?><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0.css/bootstrap.css"><?php
  }
```

<p>Or, like this:</p>

<pre class="lang-php prettyprint-override"><code>  ?>You are in <?= $color_scheme ?> mode.<?php
</code>```

Title: Dark mode without JavaScript

Body:
You already have all you need.  Browser detection is done with CSS following the Media Queries Level 5 specification using a prefers-color-scheme media query for detection.  If you're familiar with responsive web-design with CSS then you already have all the knowledge - the only difference is that responsive CSS is about geography (sizes, columns, padding, spacing, font-size, etc.) and prefers-color-scheme is about ... well ... color.  Thomas Steiner (@DenverCoder9) has an awesome article "prefers-color-scheme: Hello darkness, my old friend" that covers this.

If you are asking about PHP specifically then you are out of luck - there is no dark mode detection methodology for server side-processing.

All efforts thus-far by the W3C (and its sponsors) has been focused on client-side / Jamstack.

There is a recommendation by Thomas Steiner (same guy) to implement a Proposed server-side client hint, but this has not been adopted (yet?) by the W3C or the browsers.

Either way - there is a significant drawback in server-side detection (both with Thomas' recommendation and my solution below) in that the server will only know about a state change (e.g. macOS "Auto" mode when night fall happens) on the next server request, or more visibly, the first load of the page.

My recommendation is to leverage CSS / client-side only on this - Thomas gives some practical guidance on two methods,

1x CSS with both color schemes supported, and

2x CSS, with one being light and the other dark.  I've made a educative whitepaper applying some of these methods with the CSS framework Bootstrap at vinorodrigues/bootstrap-dark to show how easy that can be - without server-side processing.

Having said that - if you must insist on PHP or server-side detection there is no workaround - but one must use some JS.  The most efficient way is to leverage the js-cookie/js-cookie project, and include the following code into your HTML pages:

  <script src="https://cdn.jsdelivr.net/npm/js-cookie/dist/js.cookie.min.js"></script>
  <script>
    // code to set the `color_scheme` cookie
    var $color_scheme = Cookies.get("color_scheme");
    function get_color_scheme() {
      return (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light";
    }
    function update_color_scheme() {
      Cookies.set("color_scheme", get_color_scheme());
    }
    // read & compare cookie `color-scheme`
    if ((typeof $color_scheme === "undefined") || (get_color_scheme() != $color_scheme))
      update_color_scheme();
    // detect changes and change the cookie
    if (window.matchMedia)
      window.matchMedia("(prefers-color-scheme: dark)").addListener( update_color_scheme );
  </script>

And then your PHP will detect this cookie like this:

  $color_scheme = isset($_COOKIE["color_scheme"]) ? $_COOKIE["color_scheme"] : false;
  if ($color_scheme === false) $color_scheme = 'light';  // fallback

Which you can use to load the CSS:

  // Load the CSS for the correct color-scheme
  if ($color_scheme == 'dark') {
    ?><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/vinorodrigues/bootstrap-dark@0.0/dist/bootstrap-night.min.css"><?php
  } else {
    ?><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0.css/bootstrap.css"><?php
  }

Or, like this:

  ?>You are in <?= $color_scheme ?> mode.<?php


问:
How i will use If.....Else statement in MVC
I need to use If statement before div , if condition met go through the div else go to next condition like this :

```<code>@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "Details1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";

}

@if (Models.Orders_Tables.labCashView.Department_id in (1,2,3,4))
{
  <div>
   // code here
  </div>
}
else if (Models.Orders_Tables.labCashView.Department_id == 5)
{
  <div>
   // code here
  </div>
}
else if (Models.Orders_Tables.labCashView.Department_id == 6)
{
  <div>
   // code here
  </div>
}
</code>```

The issue when I try to call the Model its not show the model name like this

@if (Model.  here its not show the model name or table name why ?

答:
Update your code like below and it should work.

Here are the changes.

Added var ids = new List<int>() { 1, 2, 3, 4 }; which is used convert your condition to check in (1,2,3,4) with ids.Contains(Models.Orders_Tables.labCashView.Department_id)

Used == in both else if condition for compare.

Your Department_id might be int? that's why you are getting error cannot convert from int? to int. Use GetValueOrDefault() to retrieve int value.

```<code>@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "Details1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";
    var ids = new List<int>() { 1, 2, 3, 4 };
}

@if (ids.Contains(Model.First().labCashView.Department_id.GetValueOrDefault()))
{
  <div>
   // code here
  </div>
}
else if (Model.First().labCashView.Department_id == 5)
{
  <div>
   // code here
  </div>
}
else if (Model.First().labCashView.Department_id == 6)
{
  <div>
   // code here
  </div>
}
</code>```

Body:
I need to use If statement before div , if condition met go through the div else go to next condition like this :

@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "Details1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";

}

@if (Models.Orders_Tables.labCashView.Department_id in (1,2,3,4))
{

   // code here

}
else if (Models.Orders_Tables.labCashView.Department_id == 5)
{

   // code here

}
else if (Models.Orders_Tables.labCashView.Department_id == 6)
{

   // code here

}

The issue when I try to call the Model its not show the model name like this

@if (Model.  here its not show the model name or table name why ?

Body:
Update your code like below and it should work.

Here are the changes.

Added var ids = new List<int>() { 1, 2, 3, 4 }; which is used convert your condition to check in (1,2,3,4) with ids.Contains(Models.Orders_Tables.labCashView.Department_id)

Used == in both else if condition for compare.

Your Department_id might be int? that's why you are getting error cannot convert from int? to int. Use GetValueOrDefault() to retrieve int value.

@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "Details1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";
    var ids = new List<int>() { 1, 2, 3, 4 };
}

@if (ids.Contains(Model.First().labCashView.Department_id.GetValueOrDefault()))
{
  <div>
   // code here
  </div>
}
else if (Model.First().labCashView.Department_id == 5)
{
  <div>
   // code here
  </div>
}
else if (Model.First().labCashView.Department_id == 6)
{
  <div>
   // code here
  </div>
}


问:
How to plot a curve for a function in a 3D graphic - Python
I have this function:

```<code>z = 0.000855995633558468*x**2 + 0.0102702516120239*x + 0.00451027901725375*y**2 - 2.23785431578513*y + 251.029058292935
</code>```

I also have lists (X, Y, Z) of the coordinates of the points from this function. Then I made this code to do a plot, of that coordinates:

```<code>fig = plt.figure()
ax = fig.gca(projection='3d')
plt.plot(X, Y, Z)

plt.show()
</code>```

As you can see, with this code, I join the points by segments. How can I plot the curve that passes through those points?

答:
In short, Python does not know how all xyz points need to be connected to each other to create a surface, so it just plots lines between them.

If you want to plot a surface whose z-coordinates are a function of its x and y coordinates you need to create a grid of all the possible combinations of xy coordinates and get the resulting z-grid. Then you can plot the grids.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

def z_func(x, y):
    z = 0.000855995633558468 * x ** 2 + 0.0102702516120239 * x + \
        0.00451027901725375 * y ** 2 - 2.23785431578513 * y + \
        251.029058292935
    return z

# Creates a 1D array of all possible x and y coordinates
x_coords = np.linspace(-30, 30, 100)
y_coords = np.linspace(180, 220, 100)

# Creates 2D array with all possible combinations of x and y coordinates,
# so x_grid.shape = (100, 100) and y_grid.shape = (100, 100)
[x_grid, y_grid] = np.meshgrid(x_coords, y_coords)

# Evaluates z at all grid points
z_grid = z_func(x_grid, y_grid)

# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x_grid,y_grid,z_grid)
plt.show()
</code>```

Body:
I have this function:

z = 0.000855995633558468*x**2 + 0.0102702516120239*x + 0.00451027901725375*y**2 - 2.23785431578513*y + 251.029058292935

I also have lists (X, Y, Z) of the coordinates of the points from this function. Then I made this code to do a plot, of that coordinates:

fig = plt.figure()
ax = fig.gca(projection='3d')
plt.plot(X, Y, Z)

plt.show()

As you can see, with this code, I join the points by segments. How can I plot the curve that passes through those points?

Body:
In short, Python does not know how all xyz points need to be connected to each other to create a surface, so it just plots lines between them.

If you want to plot a surface whose z-coordinates are a function of its x and y coordinates you need to create a grid of all the possible combinations of xy coordinates and get the resulting z-grid. Then you can plot the grids.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

def z_func(x, y):
    z = 0.000855995633558468 * x ** 2 + 0.0102702516120239 * x + \
        0.00451027901725375 * y ** 2 - 2.23785431578513 * y + \
        251.029058292935
    return z

# Creates a 1D array of all possible x and y coordinates
x_coords = np.linspace(-30, 30, 100)
y_coords = np.linspace(180, 220, 100)

# Creates 2D array with all possible combinations of x and y coordinates,
# so x_grid.shape = (100, 100) and y_grid.shape = (100, 100)
[x_grid, y_grid] = np.meshgrid(x_coords, y_coords)

# Evaluates z at all grid points
z_grid = z_func(x_grid, y_grid)

# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x_grid,y_grid,z_grid)
plt.show()


问:
Talend MySQL flow keeps stopping at 11599 rows
I have created a job in Talend Open Studio for Data Integration. It runs and does the right thing but keeps stopping at 11599 rows when I run it. The only advanced setting I have used is Enable Stream to ease memory usage.

答: When you use Commit component, it will fetch all the records from the source and commits all together. 11599 entries are getting committed in one shot which reduces the performance of the job. Instead avoid using commit component and use advanced settings in output component and provide the commit interval. Eg: if you provide commit interval of 1000, it commits every 1000 records together in the target.


问:
Automating outlook
a task was thrown in my lap that requires me to:

Iterate through many (1000's) of message folders in outlook 2010

for each folder in a specific subfolder, right click a menu, select export as pdf (this is a plugin "DocumentExporter"), and click the ok button

I use outlook rarely, so I've never automated it to this extent.  I see you can do it with vba, and also potentially .net (i've installed the .net programmability extensions)

Any suggestions on the quickest way to go about this?

Thanks!

答:
I do not have Outlook here so the following is air-code.

Sub DoIt()
  Recurse ActiveExplorer.CurrentFolder ' select relevant folder in Outlook first
End Sub

Sub Recurse(f as MAPIFolder)
  Dim sf As MAPIFolder

  PrintPdf

  For Each sf In f.Folders
    ' open a potential sub-tree of folders, and move down one folder in the UI
    SendKeys "{RIGHT}{PAUSE 100}{DOWN}"
    Recurse sf
  Next f
End Sub

Sub PrintPdf()
  ' open the context menu, go down 4 entries, press enter, wait 10 seconds
  SendKeys "{APP}{PAUSE 100}{DOWN 4}{ENTER}{PAUSE 10000}"
End Sub
```

I have no idea if this will work, it's just an idea. Make sure that Outlook is in foreground while running this (by assigning the DoIt() routine to a custom toolbar button). The starting folder must be selected before you begin.

ContentLicense: CC BY-SA 3.0

Title: Automating outlook

Body:
I do not have Outlook here so the following is air-code.

Sub DoIt()
  Recurse ActiveExplorer.CurrentFolder ' select relevant folder in Outlook first
End Sub

Sub Recurse(f as MAPIFolder)
  Dim sf As MAPIFolder

  PrintPdf

  For Each sf In f.Folders
    ' open a potential sub-tree of folders, and move down one folder in the UI
    SendKeys "{RIGHT}{PAUSE 100}{DOWN}"
    Recurse sf
  Next f
End Sub

Sub PrintPdf()
  ' open the context menu, go down 4 entries, press enter, wait 10 seconds
  SendKeys "{APP}{PAUSE 100}{DOWN 4}{ENTER}{PAUSE 10000}"
End Sub

I have no idea if this will work, it's just an idea. Make sure that Outlook is in foreground while running this (by assigning the DoIt() routine to a custom toolbar button). The starting folder must be selected before you begin.


问:
How to run a loop by interlinking two lists?
I have two lists, one for contract names of a website and another one for its links. I have 3rd list which includes some contract names which can be present in list 1. So I want to run a loop that will take contract names from the 3rd list and will find a hyperlink and open that hyperlink. I fit does not find any link then it will return a string(not found).

li1 contract names(10 to 15)
li2 contract links(number is same as list 1)
li3 random contract name.

答:
```<code>names = ['apple', 'orange', 'pear', 'banana']
links = ['apple.gov', 'orange.net', 'pear.org', 'banana.com']
link_dict = {k:v for k,v in zip(names, links)}

selected_names = ['apple', 'banana', 'poodle']

results = [link_dict[n] if n in names else 'not found' for n in selected_names]
</code>```


问:
Facebook share - display wrong image
I have problem with display image while sharing link:

https://digital.nbbd.me/unit/zorica-joksimovic-from-water-and-stone-to-story-and-storytelling

Title and description display correct, but image not.
When I try with debug tool, it warns that og:image parameters are missing, but they appears in source code. Also, in debug, image is displayed correctly.
However, when I share it, it display logo image, not the one which is in code.
I would appreciate any advice how to solve it.
Project is made in Angular, also using Angular Universal.

答:
The url is not set correctly:

```<code><meta _ngcontent-sc324="" property="og:url" content="">
</code>```

Also, make sure to put your OG tags before any CSS or JS, Facebook does not parse the whole Page.

Sidenote: Not sure if it is normal in Angular, but you have 2 html tags, 2 head tags and 2 body tags in your source. Either way, make sure to put the OG tags in the main head section.

Title: Facebook share - display wrong image

Body:
The url is not set correctly:

<meta _ngcontent-sc324="" property="og:url" content="">

Also, make sure to put your OG tags before any CSS or JS, Facebook does not parse the whole Page.

Sidenote: Not sure if it is normal in Angular, but you have 2 html tags, 2 head tags and 2 body tags in your source. Either way, make sure to put the OG tags in the main head section.


问:
Calculate the results of one query as a percentage of another in SQL
I am trying to calculate the number of people with impaired eyesight against the number of people who have had an eye test. I have managed to calculate the totals for both the number of people with impaired eyesight (TotalDiagnosed) and the total number of evaluations (TotalEvaluated):

```<code>! impala-shell -q 'SELECT COUNT(*) FROM (SELECT DISTINCT eyesight_evaluation.patient_id FROM eyesight_evaluation WHERE severity_of_sight_loss IN ("Slight","Mild","Moderate","Moderately Severe","Severe","Profound")) AS TotalDiagnosed;'

! impala-shell -q 'SELECT COUNT(DISTINCT eyesight_evaluation.patient_id) AS TotalEvaluated FROM eyesight_evaluation;'
</code>```

What I am unsure of is how to work out the percentage. I attempted

```<code>! impala-shell -q 'SELECT COUNT(DISTINCT eyesight_evaluation.patient_id) AS TotalEvaluated FROM eyesight_evaluation;'
</code>```

but it returned

ERROR: AnalysisException: Syntax error in line 1:
  ...osed, TotalEvaluated ROUND(TotalDiagnosed * 100.0 /Tot...
                               ^
  Encountered: (
  Expected: CROSS, FROM, FULL, GROUP, HAVING, INNER, JOIN, LEFT, LIMIT, OFFSET, ON, ORDER, RIGHT, >STRAIGHT_JOIN, TABLESAMPLE, UNION, USING, WHERE, COMMA

CAUSED BY: Exception: Syntax error

Can anybody help me work out the percentage? I am using Impala and a Jupyter notebook.

答:
You can use conditional aggregation:</p>

```<code>SELECT (COUNT(DISTINCT CASE WHEN severity_of_sight_loss IN ('Slight', 'Mild', 'Moderate', 'Moderately Severe', 'Severe', 'Profound') THEN ee.patient_id END) * 1.0 /
        COUNT(DISTINCT eyesight_evaluation.patient_id)
       )
FROM eyesight_evaluation ee;
</code>```

Body:
I am trying to calculate the number of people with impaired eyesight against the number of people who have had an eye test. I have managed to calculate the totals for both the number of people with impaired eyesight (TotalDiagnosed) and the total number of evaluations (TotalEvaluated):

! impala-shell -q 'SELECT COUNT(*) FROM (SELECT DISTINCT eyesight_evaluation.patient_id FROM eyesight_evaluation WHERE severity_of_sight_loss IN ("Slight","Mild","Moderate","Moderately Severe","Severe","Profound")) AS TotalDiagnosed;'

! impala-shell -q 'SELECT COUNT(DISTINCT eyesight_evaluation.patient_id) AS TotalEvaluated FROM eyesight_evaluation;'

What I am unsure of is how to work out the percentage. I attempted

! impala-shell -q 'SELECT COUNT(DISTINCT eyesight_evaluation.patient_id) AS TotalEvaluated FROM eyesight_evaluation;'

but it returned

ERROR: AnalysisException: Syntax error in line 1:
  ...osed, TotalEvaluated ROUND(TotalDiagnosed * 100.0 /Tot...
                               ^
  Encountered: (
  Expected: CROSS, FROM, FULL, GROUP, HAVING, INNER, JOIN, LEFT, LIMIT, OFFSET, ON, ORDER, RIGHT, >STRAIGHT_JOIN, TABLESAMPLE, UNION, USING, WHERE, COMMA

CAUSED BY: Exception: Syntax error

Can anybody help me work out the percentage? I am using Impala and a Jupyter notebook.

Body:
You can use conditional aggregation:

SELECT (COUNT(DISTINCT CASE WHEN severity_of_sight_loss IN ('Slight', 'Mild', 'Moderate', 'Moderately Severe', 'Severe', 'Profound') THEN ee.patient_id END) * 1.0 /
        COUNT(DISTINCT eyesight_evaluation.patient_id)
       )
FROM eyesight_evaluation ee;


问:
adding placeholder variables to the appSettings.json file
So when generating a new .NET Core web project there is an appSettings.json and appSettings.Development.json for configuration parts. By default, those are not ignored by the .gitignore file so I think they should stay in the repository.

I'm using a database and want to store my connection string to those files. Obviously the parameters contain sensitive information and shouldn't be in the repository. If the environment is the development I can add the local connection string to the appSettings.Development.json (but then every developer would have to use the same settings until I add the dev file to the .gitignore)

```<code>"Database": {
    "Server": "localhost",
    "Port": 5432,
    "UserId": "admin",
    "Password": "admin",
    "Name": "myDb"
}
</code>```

How can I set-up the appSettings.json for production or other purposes? Is there a way for something like

```<code>"Database": {
    "Server": "$DB_SERVER",
    "Port": "$DB_PORT",
    "UserId": "$DB_USER_ID",
    "Password": "$DB_PASSWORD",
    "Name": "$DB_NAME"
}
</code>```

and those placeholders would be replaced with the values from the environment variables?

答:
Use secret

They save in a local file the configuration, so they aren't on repository.
When you go in production, you save this information in environment variable.

In visual studio on Project, select Manage user secret and add your connection

```<code>{
 "ConnectionStrings": {
   "MyConnection": "the connection"
}
</code>```

in startup use IConfiguration

```<code>configuration.GetConnectionString("MyConnection")
</code>```

and at production, in EnvironmentVariable of server, you save a new EnvironmentVariable

```<code>ConnectionStrings:MyConnection
</code>```

So only administrator know the connection.
If you use Azure, you could use Azure key vault.

Body:
So when generating a new .NET Core web project there is an appSettings.json and appSettings.Development.json for configuration parts. By default, those are not ignored by the .gitignore file so I think they should stay in the repository.

I'm using a database and want to store my connection string to those files. Obviously the parameters contain sensitive information and shouldn't be in the repository. If the environment is the development I can add the local connection string to the appSettings.Development.json (but then every developer would have to use the same settings until I add the dev file to the .gitignore)

"Database": {
    "Server": "localhost",
    "Port": 5432,
    "UserId": "admin",
    "Password": "admin",
    "Name": "myDb"
}

How can I set-up the appSettings.json for production or other purposes? Is there a way for something like

"Database": {
    "Server": "$DB_SERVER",
    "Port": "$DB_PORT",
    "UserId": "$DB_USER_ID",
    "Password": "$DB_PASSWORD",
    "Name": "$DB_NAME"
}

and those placeholders would be replaced with the values from the environment variables?

Body:
Use secret

They save in a local file the configuration, so they aren't on repository.
When you go in production, you save this information in environment variable.

In visual studio on Project, select Manage user secret and add your connection

{
 "ConnectionStrings": {
   "MyConnection": "the connection"
}

in startup use IConfiguration

configuration.GetConnectionString("MyConnection")

and at production, in EnvironmentVariable of server, you save a new EnvironmentVariable

ConnectionStrings:MyConnection

So only administrator know the connection.
If you use Azure, you could use Azure key vault.


问:
Thread spin-waits on time to pass error
Why does this happen with ehcache (latest version)? What should be done to get rid of this issue? This issue occurs when I am trying to do bulk upload of data.</p>

```<code>14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 57 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 58 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 59 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 60 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 61 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 62 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 63 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 64 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 65 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 66 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 67 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 68 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 69 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 70 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 71 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 72 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 73 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 74 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 75 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 76 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 77 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 78 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 79 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 80 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
</code>```

答: Looks like an Ehcache bug which has been fixed in version 2.4.3.</p>

Title: Thread spin-waits on time to pass error

Body:
Why does this happen with ehcache (latest version)? What should be done to get rid of this issue? This issue occurs when I am trying to do bulk upload of data.

14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 57 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 58 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 59 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 60 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 61 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 62 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 63 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 64 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 65 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 66 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 67 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 68 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 69 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 70 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 71 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 72 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 73 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 74 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 75 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 76 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 77 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 78 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 79 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift
14:38:52,359 INFO [Timestamper] Thread spin-waits on time to pas
s. Looped 80 times, you might want to increase -Dnet.sf.ehcache.u
til.Timestamper.shift