问:
How can I disable authentication for a specific endpoint?
Many answers to similar questions explains that permitAll() means "allow all authenticated users", and that if you want to skip authentication, you need to do

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/chores");
}
</code>```

This does not work for me.

In particular, here is my controller test that I would like to pass.

```<code>@SpringBootTest
@AutoConfigureMockMvc
public class ChoreApplicationTest
{
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void choresShouldBeEmptyAtStart() throws Exception
    {
        this.mockMvc.perform(get("/chores")).
                andExpect(status().isOk());
    }
</code>```

Test results:

```<code>java.lang.AssertionError: Status expected:<200> but was:<401>
Expected :200
Actual   :401
</code>```

Here's how I'm setting up the security:

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web.ignoring().antMatchers("/chores");
        super.configure(web);
    }
}
</code>```

I reckon you can imagine what's in the Chores controller, but for completeness here's the relevant part:

```<code>@RestController
public class ChoreController
{
    private final ChoreRepository repository;

    ChoreController(ChoreRepository repository)
    {
        this.repository = repository;
    }

    @GetMapping("/chores")
    List<Chore> all()
    {
        return this.repository.findAll();
    }
}
</code>```

Here is the request that the test prints in the output:

```<code>MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /chores
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/chores]}
</code>```

So why is my test getting a return code of 401, and how can I fix it?

答:
Security configurations are correct in configure(WebSecurity web), but the issue was SecurityConfigurer does not get invoked due to packages were different.

Spring Boot starts execution from the main application that is ChoreApplication, also note that all classes are in package chore other than SecurityConfigurer (in package security)

Our main application class consists of @SpringBootApplication where

```<code>@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
</code>```

@ComponentScan

By default, spring will take care of all the classes which are in package chore, here the issue was spring does not know anything about classes resides in other packages. Here SecurityConfigurer in package security

To get invoked SecurityConfigurer, we have to add security package in as @ComponentScan(basePackages = {"chores", "security"})

ChoreApplication.java

```<code>package chores;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"chores", "security"})
public class ChoreApplication
{
    public static void main(String args[])
    {
        SpringApplication.run(ChoreApplication.class, args);
    }
}
</code>```

SecurityConfigurer.java

```<code>package security;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/chores");
    }
}
</code>```

You may love to explore

Spring Security Configuration: HttpSecurity-vs-Webecurity

How to scan multiple paths using the @ComponentScan annotation

Body:
Many answers to similar questions explains that permitAll() means "allow all authenticated users", and that if you want to skip authentication, you need to do

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/chores");
}

This does not work for me.

In particular, here is my controller test that I would like to pass.

@SpringBootTest
@AutoConfigureMockMvc
public class ChoreApplicationTest
{
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void choresShouldBeEmptyAtStart() throws Exception
    {
        this.mockMvc.perform(get("/chores")).
                andExpect(status().isOk());
    }

Test results:

java.lang.AssertionError: Status expected:<200> but was:<401>
Expected :200
Actual   :401

Here's how I'm setting up the security:

@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web.ignoring().antMatchers("/chores");
        super.configure(web);
    }
}

I reckon you can imagine what's in the Chores controller, but for completeness here's the relevant part:

@RestController
public class ChoreController
{
    private final ChoreRepository repository;

    ChoreController(ChoreRepository repository)
    {
        this.repository = repository;
    }

    @GetMapping("/chores")
    List<Chore> all()
    {
        return this.repository.findAll();
    }
}

Here is the request that the test prints in the output:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /chores
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/chores]}

So why is my test getting a return code of 401, and how can I fix it?

Body:
Security configurations are correct in configure(WebSecurity web), but the issue was SecurityConfigurer does not get invoked due to packages were different.

Spring Boot starts execution from the main application that is ChoreApplication, also note that all classes are in package chore other than SecurityConfigurer (in package security)

Our main application class consists of @SpringBootApplication where

@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan

@ComponentScan

By default, spring will take care of all the classes which are in package chore, here the issue was spring does not know anything about classes resides in other packages. Here SecurityConfigurer in package security

To get invoked SecurityConfigurer, we have to add security package in as @ComponentScan(basePackages = {"chores", "security"})

ChoreApplication.java

package chores;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"chores", "security"})
public class ChoreApplication
{
    public static void main(String args[])
    {
        SpringApplication.run(ChoreApplication.class, args);
    }
}

SecurityConfigurer.java

package security;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/chores");
    }
}

You may love to explore

Spring Security Configuration: HttpSecurity-vs-Webecurity

How to scan multiple paths using the @ComponentScan annotation


来源: stackexchange

问:
Updating multiple columns in dataframe with columns from another dataframe
I have a dataframe, df1, which certain columns having null values. To get the null values, I created another dataframe, df2, and in df2 I made those values non-null. I'll give an example of my dataframes here, bear in mind this is just an example as the actual dataframes are too long and this is simplified.

```<code>df1
   Col1 Col2 Col3
0    A    B    C
1    D    E    F
2  NaN    G  NaN
3  NaN    H  NaN

df2
       Col1 Col3
    0    A    C
    1    D    F
    2    I    J
    3    K    L
</code>```

Now to replace a single column in df1, I can just use the following code

```<code>df1[Col1] = df2[Col1]
</code>```

But how can I replace multiple columns like this at once? Is there a way I could replace Col1 and Col3 at the same time?

I tried some solutions from similar questions but they didn't work with mine.

答:
What I will do is update

```<code>df1.update(df2)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe, df1, which certain columns having null values. To get the null values, I created another dataframe, df2, and in df2 I made those values non-null. I'll give an example of my dataframes here, bear in mind this is just an example as the actual dataframes are too long and this is simplified.

df1
   Col1 Col2 Col3
0    A    B    C
1    D    E    F
2  NaN    G  NaN
3  NaN    H  NaN

df2
       Col1 Col3
    0    A    C
    1    D    F
    2    I    J
    3    K    L

Now to replace a single column in df1, I can just use the following code

df1[Col1] = df2[Col1]

But how can I replace multiple columns like this at once? Is there a way I could replace Col1 and Col3 at the same time?

I tried some solutions from similar questions but they didn't work with mine.

Body:
What I will do is update

df1.update(df2)


问:
Why exporting DataTable to Excel using NPOI cause to ERR_CONNECTION_RESET
I develop a web API with ASP.NET C# and angular 8.
I try to export some data from Oracle into Excel file on the server-side (using NPOI) and download it in client-side.
I can see that the memoryStream have the data but on the "return response" it doesnt returned to the client and instead of it the function is called again.
This is my code:

HTML:

 <button
            class="col-sm-2 button-style button-text"
            style="color: white; background-color: #19D893;height: 100%;"
            (click)="exportPriceList()">
        Export
        </button>```
</div>
</div>
</p>

<p>type script:</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-js lang-js prettyprint-override"><code>public exportPriceList(): void {

      let fileName='filename';
      const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

      console.log('before promise');

      const promise = new Promise((resolve, reject) => {
        this.export().subscribe(
          success => {
            console.log('start success');

            const blob = new Blob ([success], {type: fileType});

            console.log('window.navigator ', window.navigator  );
            console.log('window.navigator.msSaveOrOpenBlob ', window.navigator.msSaveOrOpenBlob  );

            if (window.navigator && window.navigator.msSaveOrOpenBlob) {

              window.navigator.msSaveOrOpenBlob(blob, );
            } else {
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                a.download = fileName ;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        },
        err => {
            alert(err);
        });

     });

      promise.then((res) => {
        console.log('promise!!!! ', res );
      });
      promise.catch((err) => {
      });
    }</code>```

public export()
  {
    console.log('start export to excel');

    const fileName = 'filename1';
    const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

    const url =  this.apiService.baseUrl + 'api/PriceList/Export?token=' + this.auth.authDetails.getValue().token +
        '&priceListType=' + this.selectedPriceListType.Key + '&fileType=' + fileType + '&bank=' + this.selectedBank.Key;

    return this.http.get(url, {responseType:  'arraybuffer'});// this.http.get(url, {responseType:  'blob'});
  }```
</div>
</div>
</p>

<p>API Controller:</p>

```[HttpGet]
    [Route("api/PriceList/Export")]
    public HttpResponseMessage Export([FromUri]string token, [FromUri]int priceListType,[FromUri]string fileType, [FromUri]int? bank=null)
    {
        try
        {
            var stream = dal.ExportPriceListServer(priceListType, bank);

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName= "PriceList_" + bank + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);

            return response;
        }
        catch (Exception ex)
        {
            exc.throwException(EventLogEntryType.Error, ex.ToString());
            throw;
        }
    }
```

<p>DAL: (The final function which generate the excel.)</p>

```public MemoryStream ExportToExcel(DataTable dt)
    {
        try
        {
            using (var stream = new MemoryStream())
            {
                // Declare XSSFWorkbook object for create sheet
                var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("sheet 1");

                int rowIndex = 0;
                var headerRow = sheet.CreateRow(1);

                //Below loop is create header
                foreach (DataColumn column in dt.Columns)
                {
                    XSSFCell xc = (XSSFCell)headerRow.CreateCell(column.Ordinal);
                    xc.SetCellValue(GetColumnTitle(column.ColumnName));
                    //xc.CellStyle = xstl;
                }

                rowIndex = 2;
                foreach (DataRow row in dt.Rows)
                {
                    XSSFRow dataRow = (XSSFRow)(sheet.CreateRow(rowIndex));

                    foreach (DataColumn column in dt.Columns)
                    {
                        XSSFCell c = (XSSFCell)dataRow.CreateCell(column.Ordinal);
                        string val = row[column].ToString();

                        int x;
                        if (Int32.TryParse(val, out x) && (!String.IsNullOrEmpty(val)))//column.IsNumeric()
                        {
                            c.SetCellValue(Int64.Parse(val));
                            c.SetCellType(CellType.Numeric);
                        }
                        else
                        {
                            c.SetCellValue(row[column].ToString());
                        }

                        // no need to auto size all the time, after 100 is ok... (it costs a lot)
                        if (rowIndex == 100)
                        {
                            sheet.AutoSizeColumn(column.Ordinal);
                        }

                    }

                    rowIndex++;
                }

                // Declare one MemoryStream variable for write file in stream

                workbook.Write(stream, true);

                return stream;
            }
        }
        catch (Exception ex)
        {

            Console.Write(ex);
            return null;
        }
    }
```

<p>This is what I see in chrome debugger:
[Network][1]</p>

<p>In Timing I see "Stallen":
[Stallen][2]</p>

<blockquote>
  <blockquote>
```rates.component.ts:100 before promise
zone.js:2969 GET .....     **net::ERR_CONNECTION_RESET**
scheduleTask @ zone.js:2969
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
onScheduleTask @ zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1114
(anonymous) @ zone.js:3001
proto.<computed> @ zone.js:1394
(anonymous) @ http.js:1630
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe
```

@ Observable.js:43
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:29
        push../node_modules/rxjs/_esm5/internal/operators/finalize.js.FinallyOperator.call
    @ finalize.js:13
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        (anonymous) @ subscribeTo.js:21
        subscribeToResult @ subscribeToResult.js:11
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub
    @ mergeMap.js:74
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext
    @ mergeMap.js:68
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next
    @ mergeMap.js:51
        push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next
    @ Subscriber.js:54
        (anonymous) @ scalar.js:5
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe
    @ Observable.js:43
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:29
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call
    @ mergeMap.js:29
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call
    @ filter.js:15
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call
    @ map.js:18
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        (anonymous) @ rates.component.ts:144
        ZoneAwarePromise @ zone.js:891
        push../src/app/Components/content/rates/rates.component.ts.RatesComponent.exportPriceList
    @ rates.component.ts:143
        eval @ RatesComponent.html:100
        handleEvent @ core.js:19545
        callWithDebugContext @ core.js:20639
        debugHandleEvent @ core.js:20342
        dispatchEvent @ core.js:16994
        (anonymous) @ core.js:17441
        (anonymous) @ platform-browser.js:993
        push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
        onInvokeTask @ core.js:14051
        push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
        push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
        push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
        invokeTask @ zone.js:1540
        globalZoneAwareCallback @ zone.js:1566

Do you have any solution for me?

Thanks,

答:
I solved the problem.
I change the code:

API CONTROLLER:

```<code>MemoryStream stream = dal.ExportPriceListServer(priceListType);

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

            response.Content = new ByteArrayContent(stream.ToArray());
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "test.xlsx"
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);

            return response;
</code>```

DAL: surrounded with using Just for write the stream

```<code> // Declare one MemoryStream variable for write file in stream
            using (var stream = new MemoryStream())
            {
                workbook.Write(stream, true);

                return stream;
            }
</code>```

Body:
I develop a web API with ASP.NET C# and angular 8.
I try to export some data from Oracle into Excel file on the server-side (using NPOI) and download it in client-side.
I can see that the memoryStream have the data but on the "return response" it doesnt returned to the client and instead of it the function is called again.
This is my code:

HTML:

 <button
            class="col-sm-2 button-style button-text"
            style="color: white; background-color: #19D893;height: 100%;"
            (click)="exportPriceList()">
        Export
        </button>

type script:

public exportPriceList(): void {

      let fileName='filename';
      const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

      console.log('before promise');

      const promise = new Promise((resolve, reject) => {
        this.export().subscribe(
          success => {
            console.log('start success');

            const blob = new Blob ([success], {type: fileType});

            console.log('window.navigator ', window.navigator  );
            console.log('window.navigator.msSaveOrOpenBlob ', window.navigator.msSaveOrOpenBlob  );

            if (window.navigator && window.navigator.msSaveOrOpenBlob) {

              window.navigator.msSaveOrOpenBlob(blob, );
            } else {
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                a.download = fileName ;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        },
        err => {
            alert(err);
        });

     });

      promise.then((res) => {
        console.log('promise!!!! ', res );
      });
      promise.catch((err) => {
      });
    }

public export()
  {
    console.log('start export to excel');

    const fileName = 'filename1';
    const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

    const url =  this.apiService.baseUrl + 'api/PriceList/Export?token=' + this.auth.authDetails.getValue().token +
        '&priceListType=' + this.selectedPriceListType.Key + '&fileType=' + fileType + '&bank=' + this.selectedBank.Key;

    return this.http.get(url, {responseType:  'arraybuffer'});// this.http.get(url, {responseType:  'blob'});
  }

API Controller:

[HttpGet]
    [Route("api/PriceList/Export")]
    public HttpResponseMessage Export([FromUri]string token, [FromUri]int priceListType,[FromUri]string fileType, [FromUri]int? bank=null)
    {
        try
        {
            var stream = dal.ExportPriceListServer(priceListType, bank);

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName= "PriceList_" + bank + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);

            return response;
        }
        catch (Exception ex)
        {
            exc.throwException(EventLogEntryType.Error, ex.ToString());
            throw;
        }
    }

DAL: (The final function which generate the excel.)

public MemoryStream ExportToExcel(DataTable dt)
    {
        try
        {
            using (var stream = new MemoryStream())
            {
                // Declare XSSFWorkbook object for create sheet
                var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("sheet 1");

                int rowIndex = 0;
                var headerRow = sheet.CreateRow(1);

                //Below loop is create header
                foreach (DataColumn column in dt.Columns)
                {
                    XSSFCell xc = (XSSFCell)headerRow.CreateCell(column.Ordinal);
                    xc.SetCellValue(GetColumnTitle(column.ColumnName));
                    //xc.CellStyle = xstl;
                }

                rowIndex = 2;
                foreach (DataRow row in dt.Rows)
                {
                    XSSFRow dataRow = (XSSFRow)(sheet.CreateRow(rowIndex));

                    foreach (DataColumn column in dt.Columns)
                    {
                        XSSFCell c = (XSSFCell)dataRow.CreateCell(column.Ordinal);
                        string val = row[column].ToString();

                        int x;
                        if (Int32.TryParse(val, out x) && (!String.IsNullOrEmpty(val)))//column.IsNumeric()
                        {
                            c.SetCellValue(Int64.Parse(val));
                            c.SetCellType(CellType.Numeric);
                        }
                        else
                        {
                            c.SetCellValue(row[column].ToString());
                        }

                        // no need to auto size all the time, after 100 is ok... (it costs a lot)
                        if (rowIndex == 100)
                        {
                            sheet.AutoSizeColumn(column.Ordinal);
                        }

                    }

                    rowIndex++;
                }

                // Declare one MemoryStream variable for write file in stream

                workbook.Write(stream, true);

                return stream;
            }
        }
        catch (Exception ex)
        {

            Console.Write(ex);
            return null;
        }
    }

This is what I see in chrome debugger:
[Network][1]

In Timing I see "Stallen":
[Stallen][2]

rates.component.ts:100 before promise
zone.js:2969 GET .....     **net::ERR_CONNECTION_RESET**
scheduleTask @ zone.js:2969
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
onScheduleTask @ zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1114
(anonymous) @ zone.js:3001
proto.<computed> @ zone.js:1394
(anonymous) @ http.js:1630
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe

@ Observable.js:43
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:29
        push../node_modules/rxjs/_esm5/internal/operators/finalize.js.FinallyOperator.call
    @ finalize.js:13
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        (anonymous) @ subscribeTo.js:21
        subscribeToResult @ subscribeToResult.js:11
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub
    @ mergeMap.js:74
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext
    @ mergeMap.js:68
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next
    @ mergeMap.js:51
        push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next
    @ Subscriber.js:54
        (anonymous) @ scalar.js:5
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe
    @ Observable.js:43
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:29
        push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call
    @ mergeMap.js:29
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call
    @ filter.js:15
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call
    @ map.js:18
        push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
    @ Observable.js:24
        (anonymous) @ rates.component.ts:144
        ZoneAwarePromise @ zone.js:891
        push../src/app/Components/content/rates/rates.component.ts.RatesComponent.exportPriceList
    @ rates.component.ts:143
        eval @ RatesComponent.html:100
        handleEvent @ core.js:19545
        callWithDebugContext @ core.js:20639
        debugHandleEvent @ core.js:20342
        dispatchEvent @ core.js:16994
        (anonymous) @ core.js:17441
        (anonymous) @ platform-browser.js:993
        push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
        onInvokeTask @ core.js:14051
        push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
        push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
        push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
        invokeTask @ zone.js:1540
        globalZoneAwareCallback @ zone.js:1566

Do you have any solution for me?

Thanks,

Body:
I solved the problem.
I change the code:

API CONTROLLER:

MemoryStream stream = dal.ExportPriceListServer(priceListType);

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

            response.Content = new ByteArrayContent(stream.ToArray());
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "test.xlsx"
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);

            return response;

DAL: surrounded with using Just for write the stream

 // Declare one MemoryStream variable for write file in stream
            using (var stream = new MemoryStream())
            {
                workbook.Write(stream, true);

                return stream;
            }


问:
How does HTML 5 Geolocation works?
I know many people have asked this question but i don't think i found a proper answer. My question is when you run the HTML 5 Geolocation API on desktop in firefox and you click on share location it takes your IP Address but how does it know which wireless points it has to use so it find your distance? i run the app at home and i get accuracy 50 m but i go next door to my neighbour who has same internet provider and on his desktop i receive back accuracy 18 km out? So if someone can explain this to me or point me where to read this information would be very helpful?

Thank you

答:
The geolocation API lets you share your location with trusted web sites. The latitude and longitude are available to JavaScript on the page, which in turn can send it back to the remote web server and do fancy location-aware things like finding local businesses or showing your location on a map.

What happens during that call to getCurrentPosition()? As I mentioned at the beginning of this chapter, geolocation support is opt-in. That means your browser will never force you to reveal your current physical location to a remote server. The user experience differs from browser to browser. In Mozilla Firefox, calling the getCurrentPosition() function of the geolocation API will cause the browser to pop up an “infobar” at the top of the browser window.

The call to getCurrentPosition() will return immediately, but that doesn’t mean that you have access to the user’s location. The callback function will be called with a single parameter, an object with two properties: coords and timestamp. The timestamp is just that, the date and time when the location was calculated. (Since this is all happening asynchronously, you can’t really know when that will happen in advance. It might take some time for the user to read the infobar and agree to share their location. Devices with dedicated GPS hardware may take some more time to connect to a GPS satellite. And so on.) The coords object has properties like latitude and longitude which are exactly what they sound like: the user’s physical location in the world.

You can refer this link from where i have taken the above information:
http://diveintohtml5.ep.io/geolocation.html

ContentLicense: CC BY-SA 3.0

Title: How does HTML 5 Geolocation works?


问:
Can't execute RScript from php
New here, also new to coding with php.
I am currently trying to execute an RScript from php using the exec() function.
When i run the php code in localhost it opens RStudio program but does not execute the code in the script.
(This makes me think it isn't a directory problem because it can actually locate the file)
Here is the classical example i tried.
Php code:

```<code><html>
  <head>
    <h1>PHP and R Integration Sample</h1>
  </head>
  <body>
        <?php
      // Execute the R script within PHP code
      // Generates output as test.png image.
    exec("RvsPHP.R");
    ?>
    <img src="test.png?var1.1" alt="R Graph">

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

Then, my Rscript (saved as "RvsPHP.R" in the same directory):

```<code>x <- rnorm(6,0,1)
png(filename="test.png", width=500, height=500)
hist(x, col="orange")
dev.off()
</code>```

I am not interested in the output of the Rscript, just that it is executed (i.e. creates the .png image)
Note: once the exec() opens the file with RStudio if i manually hit ctrl+enter and execute the script, the .png image is created and everything works just fine. If i don't do this, RStudio is left open with nothing going on and the browser is left loading until it reaches the timeout. I can't find the way to avoid the manual part of pressing ctrl+enter. I have also tried with passthru() and system() php functions with no luck.

Thanks in advance!
Regards, JuanFran

答:
Now it works, this does not mean that it is the best way, open for suggestions!

(As they mentioned RStudio is just the interface program)

Here is what made it work:

I changed the file extension from .R to .Rscript.
The php code remained the same except for the exec() part which now is: exec("RvsPHP.Rscript");

The shebang doesn't seem to affect it (Tried both with and without), but is probably a useful concept for a web server execution as they mention. (?)
I also added the RScript.exe and R.exe files as an environment variable, not sure if that did something as well.

Definetely the game changer was to change the file extension from .R to .Rscript (the default program that opens the file changes from RStudio to R)
Thanks to all, JF

Title: Can't execute RScript from php

Body:
New here, also new to coding with php.
I am currently trying to execute an RScript from php using the exec() function.
When i run the php code in localhost it opens RStudio program but does not execute the code in the script.
(This makes me think it isn't a directory problem because it can actually locate the file)
Here is the classical example i tried.
Php code:

PHP and R Integration Sample

        <?php
      // Execute the R script within PHP code
      // Generates output as test.png image.
    exec("RvsPHP.R");
    ?>

Then, my Rscript (saved as "RvsPHP.R" in the same directory):

x <- rnorm(6,0,1)
png(filename="test.png", width=500, height=500)
hist(x, col="orange")
dev.off()

I am not interested in the output of the Rscript, just that it is executed (i.e. creates the .png image)
Note: once the exec() opens the file with RStudio if i manually hit ctrl+enter and execute the script, the .png image is created and everything works just fine. If i don't do this, RStudio is left open with nothing going on and the browser is left loading until it reaches the timeout. I can't find the way to avoid the manual part of pressing ctrl+enter. I have also tried with passthru() and system() php functions with no luck.

Thanks in advance!
Regards, JuanFran


问:
How to install Homebrew Portable Ruby when your system version is too old
I'm trying to install Homebrew on macOS. Once the installation finished, when I typed help I got:

```<code>Already downloaded: /.../Library/Caches/Homebrew/portable-ruby-2.6.3.mavericks.bottle.tar.gz
Error: Checksum mismatch.
Expected: ab81211a2052ccaa6d050741c433b728d0641523d8742eef23a5b450811e5104
  Actual: f80fd4cc877a64b0ac1c105fdc212ca6be08bb034118900f2c2f58edcfe0dafd
 Archive: /.../Library/Caches/Homebrew/portable-ruby-2.6.3.mavericks.bottle.tar.gz
To retry an incomplete download, remove the file above.
Error: Failed to install Homebrew Portable Ruby (and your system version is too old)!
</code>```

答:
I had the same question, and the solution is simple: remove the portable-ruby-2.6.3.mavericks.bottle.tar.gz you downloaded before.

rm /.../Library/Caches/Homebrew/portable-ruby-2.6.3.mavericks.bottle.tar.gz
```

Body:
I'm trying to install Homebrew on macOS. Once the installation finished, when I typed help I got:

Already downloaded: /.../Library/Caches/Homebrew/portable-ruby-2.6.3.mavericks.bottle.tar.gz
Error: Checksum mismatch.
Expected: ab81211a2052ccaa6d050741c433b728d0641523d8742eef23a5b450811e5104
  Actual: f80fd4cc877a64b0ac1c105fdc212ca6be08bb034118900f2c2f58edcfe0dafd
 Archive: /.../Library/Caches/Homebrew/portable-ruby-2.6.3.mavericks.bottle.tar.gz
To retry an incomplete download, remove the file above.
Error: Failed to install Homebrew Portable Ruby (and your system version is too old)!


问:
Minifilter missing deleted files in particular scenarios Windows 10 1903 +
I have a minifilter driver that misses certain deletion of files, the problem lies with not knowing how they are deleted. This is the case for Windows 10 1903 and above. Tested Pre 1809 build and works fine.

For example MS C++ 2008 x86 redistributable https://www.microsoft.com/en-gb/download/details.aspx?id=29, on install the setup.exe extract files to C:{random GUID} (can be seen in the logs) and then installs. The files / directories get deleted afterwards in which I miss the IRP with the code below.

I currently monitor IRP_MJ_SET_INFORMATION with FileDispositionInformation for files deletions, you can test this by going to explorer and shift + delete.

Added IRP_MJ_CREATE for delete on close as well as per RbMm comments.

I also monitor for FileRenameInformation for moving files or renaming, again this is working if you move/rename a file in explorer.

My ideal solution would be to get the file on create and copy to another location, but I am not to sure where to start with it. I have looked at some minifilter examples and cannot find where  PreOperationCallback is in an example to copy a freshly created file.

My other option is to try and understand how I get these deleted files with the example above. Is there any other FileInformationClass case that I might check to identify this kind of delete.

My code is below for PreOperationCallback:

```<code>FLT_PREOP_CALLBACK_STATUS PreOperationCallback(_Inout_
PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID* CompletionContext)
{

  /* IRP-based I/O operation? */
  if (FLT_IS_IRP_OPERATION(Data)) {

   if (Data->Iopb->MajorFunction == IRP_MJ_CREATE) {

    if (Data->Iopb->Parameters.Create.Options & (FILE_DELETE_ON_CLOSE)) {
        DbgPrint("FILE_DELETE_ON_CLOSE");
        return process_irp(Data, FltObjects, CompletionContext, FALSE, FALSE);

   }else if (Data->Iopb->MajorFunction == IRP_MJ_SET_INFORMATION) {

   switch (Data->Iopb->Parameters.SetFileInformation.FileInformationClass) {

     case FileDispositionInformation:
        // deleting a file we need to action
        if (((FILE_DISPOSITION_INFORMATION*) Data->Iopb->Parameters.SetFileInformation.InfoBuffer)->DeleteFile) {
          return process_irp(Data, FltObjects, CompletionContext, FALSE, FALSE);
        }
        break;

     case FileRenameInformation:

       // Process the request according to our needs e.g copy the file
       return process_irp(Data, FltObjects, CompletionContext, FALSE, TRUE);
     }
   }
 }

  return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
</code>```

Update - I just created a very simple C# app to create a file and delete it using File.Delete("C:\test.txt"); The driver is not picking this up in current codebase on 1903 builds and above.

答:
You have to 'process_irp' for  FileRenameInformationEx and FileDispositionInformationEx like below.

```<code>switch (Data->Iopb->Parameters.SetFileInformation.FileInformationClass) {

 case FileDispositionInformation:
 case 64/*FileDispositionInformationEx*/:
    // deleting a file we need to action
    if (((FILE_DISPOSITION_INFORMATION*) Data->Iopb->Parameters.SetFileInformation.InfoBuffer)->DeleteFile) {
      return process_irp(Data, FltObjects, CompletionContext, FALSE, FALSE);
    }
    break;

 case FileRenameInformation:
 case 65/*FileRenameInformationEx*/:
   // Process the request according to our needs e.g copy the file
   return process_irp(Data, FltObjects, CompletionContext, FALSE, TRUE);
 }
</code>```

}

Body:
I have a minifilter driver that misses certain deletion of files, the problem lies with not knowing how they are deleted. This is the case for Windows 10 1903 and above. Tested Pre 1809 build and works fine.

For example MS C++ 2008 x86 redistributable https://www.microsoft.com/en-gb/download/details.aspx?id=29, on install the setup.exe extract files to C:{random GUID} (can be seen in the logs) and then installs. The files / directories get deleted afterwards in which I miss the IRP with the code below.

I currently monitor IRP_MJ_SET_INFORMATION with FileDispositionInformation for files deletions, you can test this by going to explorer and shift + delete.

Added IRP_MJ_CREATE for delete on close as well as per RbMm comments.

I also monitor for FileRenameInformation for moving files or renaming, again this is working if you move/rename a file in explorer.

My ideal solution would be to get the file on create and copy to another location, but I am not to sure where to start with it. I have looked at some minifilter examples and cannot find where  PreOperationCallback is in an example to copy a freshly created file.

My other option is to try and understand how I get these deleted files with the example above. Is there any other FileInformationClass case that I might check to identify this kind of delete.

My code is below for PreOperationCallback:

FLT_PREOP_CALLBACK_STATUS PreOperationCallback(_Inout_
PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID* CompletionContext)
{

  /* IRP-based I/O operation? */
  if (FLT_IS_IRP_OPERATION(Data)) {

   if (Data->Iopb->MajorFunction == IRP_MJ_CREATE) {

    if (Data->Iopb->Parameters.Create.Options & (FILE_DELETE_ON_CLOSE)) {
        DbgPrint("FILE_DELETE_ON_CLOSE");
        return process_irp(Data, FltObjects, CompletionContext, FALSE, FALSE);

   }else if (Data->Iopb->MajorFunction == IRP_MJ_SET_INFORMATION) {

   switch (Data->Iopb->Parameters.SetFileInformation.FileInformationClass) {

     case FileDispositionInformation:
        // deleting a file we need to action
        if (((FILE_DISPOSITION_INFORMATION*) Data->Iopb->Parameters.SetFileInformation.InfoBuffer)->DeleteFile) {
          return process_irp(Data, FltObjects, CompletionContext, FALSE, FALSE);
        }
        break;

     case FileRenameInformation:

       // Process the request according to our needs e.g copy the file
       return process_irp(Data, FltObjects, CompletionContext, FALSE, TRUE);
     }
   }
 }

  return FLT_PREOP_SUCCESS_NO_CALLBACK;
}

Update - I just created a very simple C# app to create a file and delete it using File.Delete("C:\test.txt"); The driver is not picking this up in current codebase on 1903 builds and above.

Body:
You have to 'process_irp' for  FileRenameInformationEx and FileDispositionInformationEx like below.

switch (Data->Iopb->Parameters.SetFileInformation.FileInformationClass) {

 case FileDispositionInformation:
 case 64/*FileDispositionInformationEx*/:
    // deleting a file we need to action
    if (((FILE_DISPOSITION_INFORMATION*) Data->Iopb->Parameters.SetFileInformation.InfoBuffer)->DeleteFile) {
      return process_irp(Data, FltObjects, CompletionContext, FALSE, FALSE);
    }
    break;

 case FileRenameInformation:
 case 65/*FileRenameInformationEx*/:
   // Process the request according to our needs e.g copy the file
   return process_irp(Data, FltObjects, CompletionContext, FALSE, TRUE);
 }

}


问:
Differences between null and NaN in spark? How to deal with it?
In my DataFrame, there are columns including values of null and NaN respectively, such as:

```<code>df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b"))
df.show()

+----+---+
|   a|  b|
+----+---+
|   1|NaN|
|null|1.0|
+----+---+
</code>```

Are there any difference between those? How can they be dealt with?

答:
you can deal with it using this code

```<code>df = df.where(pandas.notnull(df), None)
</code>```

The code will convert any NaN value into null

Below is the reffrence link

Link

Body:
In my DataFrame, there are columns including values of null and NaN respectively, such as:

df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b"))
df.show()

+----+---+
|   a|  b|
+----+---+
|   1|NaN|
|null|1.0|
+----+---+

Are there any difference between those? How can they be dealt with?

Body:
you can deal with it using this code

df = df.where(pandas.notnull(df), None)

The code will convert any NaN value into null

Below is the reffrence link

Link


问:
How do I force learning in the new UI when utterances are shown as Not Learned?

I want there to be a way to force these two items to become learned or at least to reveal to me why they are not Not Learned. But I can't figure out what if anything I am supposed to do.

答:
I have run into this a couple of times where I was "sure" my training was correct, yet I got the "not learned" status

I suggest you check to see if runs properly using the "Aligned NL" feature in the V2 training when you choose Run in the Simulator

If that works, the fix I'm using might work for you.

I found that if I add a vocab to work with my enum, then my training gets learned


问:
Unable to add permissions to Linkedin app and getting error unauthorized_scope_error
I want to add LinkedIn loggin button to my site which is made with React.

Thus, I've created a new app on Linkedin and I have CLIENT_ID and CLIENT_SECRET. I've also added REDIRECT_URL. But in the PERMISSIONS section I see no permissions and I cannot add them.

And now when I try to do an API call to the url from the docs:

```<code>const url = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${REACT_APP_CLIENT_ID}&redirect_uri=${REACT_APP_REDIRECT_URI}&scope=r_emailaddress`
</code>```

It doesn't work and I get error=unauthorized_scope_error

Any idea how to solve that?

I think that if I be able to add those permissions it would be solved.

Thanks in advance.

答: use this scope scope=r_liteprofile%20r_emailaddress%20w_member_social</p>

Body:
I want to add LinkedIn loggin button to my site which is made with React.

Thus, I've created a new app on Linkedin and I have CLIENT_ID and CLIENT_SECRET. I've also added REDIRECT_URL. But in the PERMISSIONS section I see no permissions and I cannot add them.

And now when I try to do an API call to the url from the docs:

const url = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${REACT_APP_CLIENT_ID}&redirect_uri=${REACT_APP_REDIRECT_URI}&scope=r_emailaddress`

It doesn't work and I get error=unauthorized_scope_error

Any idea how to solve that?

I think that if I be able to add those permissions it would be solved.

Thanks in advance.


问:
JSON - make subchild as a condition for IF Statement
I have a JSON from an API with this content:

```<code>"items":[
     {
      id: *id here*,
      variant: {
             variant_name: *name here*,
             variant_id: *id here*,
             stores: {
                   0:
                      store_id: *STOREID1*,
                      available_for_sale: true
                   1:
                      store_id: *STOREID2*,
                      available_for_sale: true
     }
   }
}]
</code>```

I want to select the items with the same store ID and Available for sale status. I have tried this but this isn't working:

```<code>if(items.variant.stores.store_id === "STOREID1" && items.variant.stores.available_for_sale === 'true'){
</code>```

But it says

```<code>Uncaught TypeError: Cannot read property 'store_id' of undefined
</code>```

EDIT:

I tried this:

```<code> if(items.variants.stores.store_id["******"] && items.variants.stores.available_for_sale['true']){
</code>```

But it still gives the same error.

EDIT 2:

Edited the Question for more clarification.

答:
Your JSON file is malformed.  I've tried to fix it to be valid. Next time take the object you get in the console.log, and instead use JSON.stringify(jsobject) for valid JSON output instead of trying to copy paste it verbatim.

It's not entirely clear if you want the whole object, or just the stores values.  But I've implemented both.

I've used Object.values, because your notation looks like objects (which would make it invalid JSON), but if they are really arrays, you shouldn't need Object.values.

data = {
  "items": [{
    id: "*id here*",
    variant: {
      variant_name: "*name here*",
      variant_id: "*id here*",
      stores: {
        0: {
          store_id: "*STOREID1*",
          available_for_sale: true
        },
        1: {
          store_id: "*STOREID2*",
          available_for_sale: true
        }
      }
    }
  }]
}

// filter for and return whole object for any that have the stores in question
// use some to to search for at least one match of store values
console.log(
  data.items.filter(item => Object.values(item.variant.stores).some(({
    store_id,
    available_for_sale
  }) => store_id === '*STOREID1*' && available_for_sale))
)

// get stores values
// Using flatMap to combine all the arrays returned from each stores object.
console.log(
  data.items.flatMap(item => Object.values(item.variant.stores).filter(({
    store_id,
    available_for_sale
  }) => store_id === '*STOREID1*' && available_for_sale))
)```

Body:
I have a JSON from an API with this content:

"items":[
     {
      id: *id here*,
      variant: {
             variant_name: *name here*,
             variant_id: *id here*,
             stores: {
                   0:
                      store_id: *STOREID1*,
                      available_for_sale: true
                   1:
                      store_id: *STOREID2*,
                      available_for_sale: true
     }
   }
}]

I want to select the items with the same store ID and Available for sale status. I have tried this but this isn't working:

if(items.variant.stores.store_id === "STOREID1" && items.variant.stores.available_for_sale === 'true'){

But it says

Uncaught TypeError: Cannot read property 'store_id' of undefined

EDIT:

I tried this:

 if(items.variants.stores.store_id["******"] && items.variants.stores.available_for_sale['true']){

But it still gives the same error.

EDIT 2:

Edited the Question for more clarification.


问:
Using another variable to store context inside a different variable
I want to add value inside a textbox.text variable only I don't want to use another variable for that issue:

```<code>$temp = '$textbox'

$textbox.text = "this will store this string exactly as I want"

# I want to use temp for that issue but this code of course won't work:

$temp.text = "this will not work"
</code>```

How can I use this $temp variable to call the $textbox variable?

EDIT:

I have a gui with 8 Textboxes, 2 on each row.
the left row are named textbox2 textbox4 textbox6 and so on
the right row are named textbox3 textbox5 textbox7 and so on.
the idea is this:
i have an array with 8 items.
if i have text inside a textbox to the left, i put an array item inside the corresponsing textbox to the right. E.g:

```<code>if (textbox2.textlength -gt 0) #meaning its not empty textbox
 {textbox3.text = $array[0]} #corresponding textbox to the right will get value from array
</code>```

so i have to check textbox2,4,6,8 and so on, and each time i see a value i need to take the next array item and put it inside the right textbox
im gonna add a picture:

i hope its clear.
i want to create a loop for this issue but i cannot do something like:

```<code>for ($i=2; $i -lt 17; $i=$i+2){
    if (textbox$i.textlength -gt 0 ) #of cours this wont work..
</code>```

MORE EDIT:
this is the code that i want to put inside a loop:

```<code> Function FillBoxes ($passarray) {

     if ($textbox2.textlength -gt 0) {
      $textbox3.text = $passarray[0]}

      if ($textbox4.textlength -gt 0) {
      $textbox5.text = $passarray[1]}

     if ($textbox6.textlength -gt 0) {
      $textbox7.text = $passarray[2]}

     if ($textbox8.textlength -gt 0) {
      $textbox9.text = $passarray[3]}

     if ($textbox10.textlength -gt 0) {
      $textbox11.text = $passarray[4]}

     if ($textbox12.textlength -gt 0) {
      $textbox13.text = $passarray[5]}

     if ($textbox14.textlength -gt 0) {
      $textbox15.text = $passarray[6]}

     if ($textbox16.textlength -gt 0) {
      $textbox17.text = $passarray[7]}
     }
</code>```

答:
Like what Lee_Dailey says, I am really taken aback by what you are saying here.

Without doing the logic check, is the looping effort you are after?

```<code>[array]$passarray = 1..17

for ($i=2; $i -lt 17; $i=$i+2){
    switch ($i)
        {
            2
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[0])"
            }
            4
                        {
                "Textbox_text$i"
                 "Value to assign to text box is: $($passarray[1])"
            }
            6
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[2])"
            }
            8
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[3])"
            }
            10
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[4])"
            }
            12
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[5])"
            }
            14
            {
                "Textbox_text$i"
                 "Value to assign to text box is: $($passarray[6])"
            }
            16
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[7])"
            }
            default {$PSItem | Out-Null}
        }
}

# Results

Textbox_text2
Value to assign to text box is: 1
Textbox_text4
Value to assign to text box is: 2
Textbox_text6
Value to assign to text box is: 3
Textbox_text8
Value to assign to text box is: 4
Textbox_text10
Value to assign to text box is: 5
Textbox_text12
Value to assign to text box is: 6
Textbox_text14
Value to assign to text box is: 7
Textbox_text16
Value to assign to text box is: 8
</code>```

Of course, You can easily extend that logic in the switch to whatever you choose.

Body:
I want to add value inside a textbox.text variable only I don't want to use another variable for that issue:

$temp = '$textbox'

$textbox.text = "this will store this string exactly as I want"

# I want to use temp for that issue but this code of course won't work:

$temp.text = "this will not work"

How can I use this $temp variable to call the $textbox variable?

EDIT:

I have a gui with 8 Textboxes, 2 on each row.
the left row are named textbox2 textbox4 textbox6 and so on
the right row are named textbox3 textbox5 textbox7 and so on.
the idea is this:
i have an array with 8 items.
if i have text inside a textbox to the left, i put an array item inside the corresponsing textbox to the right. E.g:

if (textbox2.textlength -gt 0) #meaning its not empty textbox
 {textbox3.text = $array[0]} #corresponding textbox to the right will get value from array

so i have to check textbox2,4,6,8 and so on, and each time i see a value i need to take the next array item and put it inside the right textbox
im gonna add a picture:

i hope its clear.
i want to create a loop for this issue but i cannot do something like:

for ($i=2; $i -lt 17; $i=$i+2){
    if (textbox$i.textlength -gt 0 ) #of cours this wont work..

MORE EDIT:
this is the code that i want to put inside a loop:

 Function FillBoxes ($passarray) {

     if ($textbox2.textlength -gt 0) {
      $textbox3.text = $passarray[0]}

      if ($textbox4.textlength -gt 0) {
      $textbox5.text = $passarray[1]}

     if ($textbox6.textlength -gt 0) {
      $textbox7.text = $passarray[2]}

     if ($textbox8.textlength -gt 0) {
      $textbox9.text = $passarray[3]}

     if ($textbox10.textlength -gt 0) {
      $textbox11.text = $passarray[4]}

     if ($textbox12.textlength -gt 0) {
      $textbox13.text = $passarray[5]}

     if ($textbox14.textlength -gt 0) {
      $textbox15.text = $passarray[6]}

     if ($textbox16.textlength -gt 0) {
      $textbox17.text = $passarray[7]}
     }

Body:
Like what Lee_Dailey says, I am really taken aback by what you are saying here.

Without doing the logic check, is the looping effort you are after?

[array]$passarray = 1..17

for ($i=2; $i -lt 17; $i=$i+2){
    switch ($i)
        {
            2
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[0])"
            }
            4
                        {
                "Textbox_text$i"
                 "Value to assign to text box is: $($passarray[1])"
            }
            6
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[2])"
            }
            8
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[3])"
            }
            10
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[4])"
            }
            12
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[5])"
            }
            14
            {
                "Textbox_text$i"
                 "Value to assign to text box is: $($passarray[6])"
            }
            16
            {
                "Textbox_text$i"
                "Value to assign to text box is: $($passarray[7])"
            }
            default {$PSItem | Out-Null}
        }
}

# Results

Textbox_text2
Value to assign to text box is: 1
Textbox_text4
Value to assign to text box is: 2
Textbox_text6
Value to assign to text box is: 3
Textbox_text8
Value to assign to text box is: 4
Textbox_text10
Value to assign to text box is: 5
Textbox_text12
Value to assign to text box is: 6
Textbox_text14
Value to assign to text box is: 7
Textbox_text16
Value to assign to text box is: 8

Of course, You can easily extend that logic in the switch to whatever you choose.


问:
How can I match the input entered by the user to the lists in dictionary
```<code>print('-----------smart health prediction using data mining------------------- ')
mydict = {
    'malaria': ['fever', 'headache', 'sweats', 'chills', 'vomiting'],
    'anxiety': ['restlessness', 'a sense of dread', 'feeling constantly on edge', 'difficulty concentrating', 'irritability'],
    'asthma': ['wheezing (a whistling sound when you breathe)', 'shortness of breath', 'a tight chest – which may feel like a band is tightening around it', 'Coughing'],
    'hepatitis C': ['shortness of breath', 'angina pectoris', 'anorexia', 'sinus rhythm'],
    'diabetes': ['feeling very thirsty', 'feeling very tired', 'wight loss and loss of muscle in mulk'],
    'migraine': ['increased sensitivity to light and sound', 'vomiting', 'feeling very tierd', 'headache']
}
print(mydict)
j = input("How many symptoms")
x = int(j)
list1 = []
for i in range(x):
    list1.append(input())
print (list1)
# From here I want the list to match the maximum symptoms with the lists in the dictionary
if list1 == mydict['malaria']
    print('true')
else:
    print('false')
mydict['malaria'], mydict['anxiety']
</code>```

答:
you can use check =  all(item in mydict[i] for item in list1) to check if all the elements of your list are in the list of the dictionary, even you can do this

```<code>print('-----------smart health prediction using data mining------------------- ')
mydict = {
    'malaria': ['fever', 'headache', 'sweats', 'chills', 'vomiting'],
    'anxiety': ['restlessness', 'a sense of dread', 'feeling constantly on edge', 'difficulty concentrating', 'irritability'],
    'asthma': ['wheezing (a whistling sound when you breathe)', 'shortness of breath', 'a tight chest – which may feel like a band is tightening around it', 'Coughing'],
    'hepatitis C': ['shortness of breath', 'angina pectoris', 'anorexia', 'sinus rhythm'],
    'diabetes': ['feeling very thirsty', 'feeling very tired', 'wight loss and loss of muscle in mulk'],
    'migraine': ['increased sensitivity to light and sound', 'vomiting', 'feeling very tierd', 'headache']
}
print(mydict)
j = input("How many symptoms")
x = int(j)

list1 = []

for i in range(x):
    list1.append(input("Type your "+str(i+1)+" symptom"))
print (list1)

for i in mydict:
    check =  all(item in mydict[i] for item in list1)
    if(check):
        print("you could have "+i)
</code>```

Body:
you can use check =  all(item in mydict[i] for item in list1) to check if all the elements of your list are in the list of the dictionary, even you can do this

print('-----------smart health prediction using data mining------------------- ')
mydict = {
    'malaria': ['fever', 'headache', 'sweats', 'chills', 'vomiting'],
    'anxiety': ['restlessness', 'a sense of dread', 'feeling constantly on edge', 'difficulty concentrating', 'irritability'],
    'asthma': ['wheezing (a whistling sound when you breathe)', 'shortness of breath', 'a tight chest – which may feel like a band is tightening around it', 'Coughing'],
    'hepatitis C': ['shortness of breath', 'angina pectoris', 'anorexia', 'sinus rhythm'],
    'diabetes': ['feeling very thirsty', 'feeling very tired', 'wight loss and loss of muscle in mulk'],
    'migraine': ['increased sensitivity to light and sound', 'vomiting', 'feeling very tierd', 'headache']
}
print(mydict)
j = input("How many symptoms")
x = int(j)

list1 = []

for i in range(x):
    list1.append(input("Type your "+str(i+1)+" symptom"))
print (list1)

for i in mydict:
    check =  all(item in mydict[i] for item in list1)
    if(check):
        print("you could have "+i)


问:
What is the best way to add a new column to an existing pandas df based on external function?
```<code>import pandas as pd

cd = ['DE','AU','US','FR','GB','KR','IQ']
df = pd.DataFrame({'country_cd': cd})

def get_continent(country_cd):
    return 'some value'

%timeit df['continent1'] = df['country_cd'].apply(get_continent)
%timeit df['continent2'] = df.apply(lambda x: get_continent(x['country_cd']), axis =1)
%timeit df['continent3'] = df['country_cd'].map(get_continent)

</code>```

288 µs ± 3.15 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
780 µs ± 8.44 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
263 µs ± 4.01 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

From the above results, map seem to perform best for a single column. Is there a better way to achieve better results?
Also is there any gotcha that i am missing?

Please advise!

答:
Is it wrong to not use a function?</p>

```<code>%timeit df['continent4'] = ['some value']*len(df['country_cd'])
188 µs ± 8.04 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Body:
import pandas as pd

cd = ['DE','AU','US','FR','GB','KR','IQ']
df = pd.DataFrame({'country_cd': cd})

def get_continent(country_cd):
    return 'some value'

%timeit df['continent1'] = df['country_cd'].apply(get_continent)
%timeit df['continent2'] = df.apply(lambda x: get_continent(x['country_cd']), axis =1)
%timeit df['continent3'] = df['country_cd'].map(get_continent)

288 µs ± 3.15 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
780 µs ± 8.44 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
263 µs ± 4.01 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

From the above results, map seem to perform best for a single column. Is there a better way to achieve better results?
Also is there any gotcha that i am missing?

Please advise!

Body:
Is it wrong to not use a function?

%timeit df['continent4'] = ['some value']*len(df['country_cd'])
188 µs ± 8.04 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
How to do reverse for get_absolute_url with many to many field?
I have a model with many-to-many fields and I need to get an ID selected from a many to many field. I decorated a get_absolute_url method with permaling decorator. And it doesn't work. So I understand that I need to reverse the relation, it is obvious from the trace, but I do not really understand what should I do?

Model:

```<code>class MenuItems(models.Model):
    reference_value = models.CharField(max_length=255)
    filter_ids = models.ManyToManyField(Filter, blank = True)

    def __unicode__(self):
        return u'%s' % self.reference_value

    @models.permalink
    def get_absolute_url(self):
        return ('homepage_ids', None, {'ids': self.filter_ids })
</code>```

I tried to do with the reverse(), but I have the behavior of the method didn't changed.

```<code>    @models.permalink
    def get_absolute_url(self):
        return reverse('homepage_ids', kwargs={'ids': self.filter_ids })
</code>```

答:
without seeing the url pattern.

self.filter_ids does not return a list of ids, something like.

self.filter_ids.all().values_list('id', flat=True)

would return [1,2,3]

Body:
I have a model with many-to-many fields and I need to get an ID selected from a many to many field. I decorated a get_absolute_url method with permaling decorator. And it doesn't work. So I understand that I need to reverse the relation, it is obvious from the trace, but I do not really understand what should I do?

Model:

class MenuItems(models.Model):
    reference_value = models.CharField(max_length=255)
    filter_ids = models.ManyToManyField(Filter, blank = True)

    def __unicode__(self):
        return u'%s' % self.reference_value

    @models.permalink
    def get_absolute_url(self):
        return ('homepage_ids', None, {'ids': self.filter_ids })

I tried to do with the reverse(), but I have the behavior of the method didn't changed.

    @models.permalink
    def get_absolute_url(self):
        return reverse('homepage_ids', kwargs={'ids': self.filter_ids })


问:
How to use computed field in syncfusion vue js data grid
How can i use computed value in syncfusion vue js data grid ?

For example

Suppose i have 5 column as QUANTITY, MRP, DISCOUNT, DISCOUNTED PRICE, TOTAL.
I want to calculate DISCOUNTED PRICE from given values MRP and DISCOUNT.
And also want to calculate TOTAL from given value QUANTITY and DISCOUNTED PRICE.

How can i achieve this in syncfusion vue js databgrid?
Thanks in advance for help.

答:
We understand on the initial page load you like to calculate the Total and Discount price based on the other three field values. Based on your query we have prepared a sample and achieved your requirement by using queryCellInfo event.

```<code>var templateGrid = Vue.component('ShowerTemplateList', {
        template: `
                <ejs-grid ref='grid' id='grid' :dataSource="data" :columns='columns'
                    :editSettings='editSettings' :toolbar='toolbar' :queryCellInfo='queryCellInfo' :actionComplete='actionComplete'>
                </ejs-grid>
            `,
        `data: function () {
            return {
                data: new ej.data.DataManager({
                    url: "/Home/UrlDatasourceone",
                    updateUrl: "Home/Updateone",
                    insertUrl: "Home/Insertone",
                    removeUrl: "Home/Removeone",
                    adaptor: new ejs.data.UrlAdaptor()
                }),
                columns: [
                    { field: 'OrderID', headerText: 'ID', isPrimaryKey: true, width: 100 },
                    { field: 'Quantity', headerText: 'Quantity', width: 100 },
                    { field: 'MRP', headerText: 'MRP', width: 100 },
                    { field: 'Discount', headerText: 'Discount', width: 100 },
                    { field: 'Discountprice', headerText: 'Discount price', width: 100 },
                    { field: 'Total', headerText: 'Total', width: 100 }
                ],
                editSettings: {
                    allowEditing: true,
                    allowAdding: true,
                    allowDeleting: true,
                    mode: "Normal"
                },
                toolbar: ["Add", "Edit", "Delete", "Update", "Cancel"]
            }
        },
        methods: {
            actionComplete: function (args) {
                if (args.requestType === "beginEdit") {
                    var grid = document.getElementsByClassName("e-grid")[0]
                        .ej2_instances[0];
                    grid.editModule.formObj.element[1].addEventListener("keyup", function (
                        e
                    ) {
                       var grid = document.getElementsByClassName("e-grid")[0]
                            .ej2_instances[0];
                        var Totalquantity = +e.target.value;
                        var GivenMrp = +grid.editModule.formObj.element[2].value;
                        var Discount = +grid.editModule.formObj.element[3].value;
                        var offerprice = (GivenMrp * Discount) / 100;
                        var Res = GivenMrp - offerprice;
                        grid.editModule.formObj.element[5].value = Res * Totalquantity;
                    });
                    grid.editModule.formObj.element[2].addEventListener("keyup", function (
                        e
                    ) {
                        //For calculating price
                        var grid = document.getElementsByClassName("e-grid")[0]
                            .ej2_instances[0];
                        var GivenMrp = +e.target.value;
                        var Totalquantity = grid.editModule.formObj.element[1].value;
                        var Discount = +grid.editModule.formObj.element[3].value;
                        var offerprice = (GivenMrp * Discount) / 100;
                        var discountprice = GivenMrp - offerprice;
                        grid.editModule.formObj.element[4].value = discountprice;
                        grid.editModule.formObj.element[5].value =
                            Totalquantity * discountprice;
                    });
                    grid.editModule.formObj.element[3].addEventListener("keyup", function (
                        e
                    ) {
                       var grid = document.getElementsByClassName("e-grid")[0]
                            .ej2_instances[0];
                        var discount = +e.target.value;
                        var GivenMrp = +grid.editModule.formObj.element[2].value;
                        var Totalquantity = grid.editModule.formObj.element[1].value;
                        var offerprice = (GivenMrp * discount) / 100;
                        var prc = GivenMrp - offerprice;
                        grid.editModule.formObj.element[4].value = prc;
                        grid.editModule.formObj.element[5].value = Totalquantity * prc;
                    });
                }
            },
            queryCellInfo: function (args) {
                if (args.column.field === "Discountprice") {          //the querycellinfo triggers for every cell rendering
                    var discount = (args.data.MRP * args.data.Discount) / 100;
                    var discountprice = args.data.MRP - discount;
                    args.data.Discountprice = discountprice;  //here we have calculated the discount price and updated the value to datasource
                    args.cell.innerText = discountprice;     //here we have set the discount price to the cell value for UI changes
                }
                if (args.column.field === "Total") {
                    var discountprice = (args.data.Discountprice * args.data.Quantity);
                    args.data.Total = discountprice;          //here we have calculated the Total price and updated the value to datasource
                    args.cell.innerText = discountprice;      //here we have set the Total price to the cell value for UI changes
                }
            }
        }
    }); `
</code>```

Sample:  https://www.syncfusion.com/downloads/support/forum/154221/ze/1542211673557847.zip

Documentation: https://ej2.syncfusion.com/documentation/api/grid/#querycellinfo

Body:
We understand on the initial page load you like to calculate the Total and Discount price based on the other three field values. Based on your query we have prepared a sample and achieved your requirement by using queryCellInfo event.

var templateGrid = Vue.component('ShowerTemplateList', {
        template: `
                <ejs-grid ref='grid' id='grid' :dataSource="data" :columns='columns'
                    :editSettings='editSettings' :toolbar='toolbar' :queryCellInfo='queryCellInfo' :actionComplete='actionComplete'>
                </ejs-grid>
            `,
        `data: function () {
            return {
                data: new ej.data.DataManager({
                    url: "/Home/UrlDatasourceone",
                    updateUrl: "Home/Updateone",
                    insertUrl: "Home/Insertone",
                    removeUrl: "Home/Removeone",
                    adaptor: new ejs.data.UrlAdaptor()
                }),
                columns: [
                    { field: 'OrderID', headerText: 'ID', isPrimaryKey: true, width: 100 },
                    { field: 'Quantity', headerText: 'Quantity', width: 100 },
                    { field: 'MRP', headerText: 'MRP', width: 100 },
                    { field: 'Discount', headerText: 'Discount', width: 100 },
                    { field: 'Discountprice', headerText: 'Discount price', width: 100 },
                    { field: 'Total', headerText: 'Total', width: 100 }
                ],
                editSettings: {
                    allowEditing: true,
                    allowAdding: true,
                    allowDeleting: true,
                    mode: "Normal"
                },
                toolbar: ["Add", "Edit", "Delete", "Update", "Cancel"]
            }
        },
        methods: {
            actionComplete: function (args) {
                if (args.requestType === "beginEdit") {
                    var grid = document.getElementsByClassName("e-grid")[0]
                        .ej2_instances[0];
                    grid.editModule.formObj.element[1].addEventListener("keyup", function (
                        e
                    ) {
                       var grid = document.getElementsByClassName("e-grid")[0]
                            .ej2_instances[0];
                        var Totalquantity = +e.target.value;
                        var GivenMrp = +grid.editModule.formObj.element[2].value;
                        var Discount = +grid.editModule.formObj.element[3].value;
                        var offerprice = (GivenMrp * Discount) / 100;
                        var Res = GivenMrp - offerprice;
                        grid.editModule.formObj.element[5].value = Res * Totalquantity;
                    });
                    grid.editModule.formObj.element[2].addEventListener("keyup", function (
                        e
                    ) {
                        //For calculating price
                        var grid = document.getElementsByClassName("e-grid")[0]
                            .ej2_instances[0];
                        var GivenMrp = +e.target.value;
                        var Totalquantity = grid.editModule.formObj.element[1].value;
                        var Discount = +grid.editModule.formObj.element[3].value;
                        var offerprice = (GivenMrp * Discount) / 100;
                        var discountprice = GivenMrp - offerprice;
                        grid.editModule.formObj.element[4].value = discountprice;
                        grid.editModule.formObj.element[5].value =
                            Totalquantity * discountprice;
                    });
                    grid.editModule.formObj.element[3].addEventListener("keyup", function (
                        e
                    ) {
                       var grid = document.getElementsByClassName("e-grid")[0]
                            .ej2_instances[0];
                        var discount = +e.target.value;
                        var GivenMrp = +grid.editModule.formObj.element[2].value;
                        var Totalquantity = grid.editModule.formObj.element[1].value;
                        var offerprice = (GivenMrp * discount) / 100;
                        var prc = GivenMrp - offerprice;
                        grid.editModule.formObj.element[4].value = prc;
                        grid.editModule.formObj.element[5].value = Totalquantity * prc;
                    });
                }
            },
            queryCellInfo: function (args) {
                if (args.column.field === "Discountprice") {          //the querycellinfo triggers for every cell rendering
                    var discount = (args.data.MRP * args.data.Discount) / 100;
                    var discountprice = args.data.MRP - discount;
                    args.data.Discountprice = discountprice;  //here we have calculated the discount price and updated the value to datasource
                    args.cell.innerText = discountprice;     //here we have set the discount price to the cell value for UI changes
                }
                if (args.column.field === "Total") {
                    var discountprice = (args.data.Discountprice * args.data.Quantity);
                    args.data.Total = discountprice;          //here we have calculated the Total price and updated the value to datasource
                    args.cell.innerText = discountprice;      //here we have set the Total price to the cell value for UI changes
                }
            }
        }
    }); `

Sample:  https://www.syncfusion.com/downloads/support/forum/154221/ze/1542211673557847.zip

Documentation: https://ej2.syncfusion.com/documentation/api/grid/#querycellinfo


问:
How to enable CORS in ASP.net Core WebAPI
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

```<code>    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });
</code>```

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

```<code>    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }
</code>```

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

```<code>[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller
</code>```

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

```<code>.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")
</code>```

These are other headers I tried which failed

```<code>.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")
</code>```

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

```<code>app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));
</code>```

答:
Use a custom Action/Controller Attribute to set the CORS headers.

Example:

```<code>public class AllowMyRequestsAttribute : ControllerAttribute, IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // check origin
        var origin = context.HttpContext.Request.Headers["origin"].FirstOrDefault();
        if (origin == someValidOrigin)
        {
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", origin);
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "*");
            // Add whatever CORS Headers you need.
        }
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // empty
    }
}
</code>```

Then on the Web API Controller / Action:

```<code>[ApiController]
[AllowMyRequests]
public class MyController : ApiController
{
    [HttpGet]
    public ActionResult<string> Get()
    {
        return "Hello World";
    }
}
</code>```

Body:
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")

These are other headers I tried which failed

.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));

Body:
Use a custom Action/Controller Attribute to set the CORS headers.

Example:

public class AllowMyRequestsAttribute : ControllerAttribute, IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // check origin
        var origin = context.HttpContext.Request.Headers["origin"].FirstOrDefault();
        if (origin == someValidOrigin)
        {
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", origin);
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "*");
            // Add whatever CORS Headers you need.
        }
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // empty
    }
}

Then on the Web API Controller / Action:

[ApiController]
[AllowMyRequests]
public class MyController : ApiController
{
    [HttpGet]
    public ActionResult<string> Get()
    {
        return "Hello World";
    }
}


问:
How can I initialize a mixin's immutable data in Dart?
I am programming in Flutter using Dart 2.1.0, and come across this situation:

```<code>mixin Salt {
  final int pinches;  // Immutable, and I want to delay initialization.

  // Cannot declare constructors for mixin
}

class Meat with Salt {
  Meat(int pinches) ... // How to initialize it?
}
</code>```

Salt has no constructor, so I cannot use initializer list. pinches is final, so I cannot set it in Meat's constructor.

I don't want to make Salt a class because Meat may need to extend from something else.

And I want to keep pinches immutable.

Any way to do it? Thanks in advance.

答:
Similar to attdona's suggestion, but a little bit closer to what you really wanted, you could do it like

mixin Salt {
  int _pinches;
  int get pinches => _pinches;
  void initSalt(int pinches) {
    assert(_pinches == null);
    _pinches = pinches;
  }
}

class Meat with Salt {
  Meat(int pinches) {
    initSalt(pinches);
  }
}
```

It's still not strictly final, but (so long as the mixin's in a different library so you can't change the private member directly) it's immutable at runtime. Not as good as if it could be properly final, but maybe close enough.

Body:
I am programming in Flutter using Dart 2.1.0, and come across this situation:

mixin Salt {
  final int pinches;  // Immutable, and I want to delay initialization.

  // Cannot declare constructors for mixin
}

class Meat with Salt {
  Meat(int pinches) ... // How to initialize it?
}

Salt has no constructor, so I cannot use initializer list. pinches is final, so I cannot set it in Meat's constructor.

I don't want to make Salt a class because Meat may need to extend from something else.

And I want to keep pinches immutable.

Any way to do it? Thanks in advance.

Body:
Similar to attdona's suggestion, but a little bit closer to what you really wanted, you could do it like

mixin Salt {
  int _pinches;
  int get pinches => _pinches;
  void initSalt(int pinches) {
    assert(_pinches == null);
    _pinches = pinches;
  }
}

class Meat with Salt {
  Meat(int pinches) {
    initSalt(pinches);
  }
}

It's still not strictly final, but (so long as the mixin's in a different library so you can't change the private member directly) it's immutable at runtime. Not as good as if it could be properly final, but maybe close enough.


问:
OpenLayers: how can be ol.FeatureOverlay replaced in 3.13v?
Here there is an overlay feature example.

It doesn't work on 3.13 OpenLayers version because of no more supported ol.FeatureOverlay.

How can be it replaced? Could you give me an example?

答: For OL 6.3.1 Vector Layer demonstrates the highlighting on mouseover</p>