问:
Take the mean of the top 10% values according to the date
I have a dataframe that consist of the day column and a score column. So per day, there are many values. So I need to get the mean of the top 10% values per day. Simply means I need the output as a day column and mean of the top 10% values of that day.

this is a example dataset screenshot

```<code>`{'Date':
 [
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1)],
 'value': [
  3.35,
  1.85,
  1.3,
  1.85,
  1.85,
  1.17,
  1.17,
  2.8,
  1.43,
  2.54,
  1.22,
  2.54,
  1.17,
  1.17,
  2.71,
  5.98,
  1.39,
  1.48,
  16.46,
  1.43,
  8.39,
  33.99,
  2.54,
  11.8,
  2.13,
  2.24,
  2.92,
  1.35,
  1.54,
  2.52]}`
</code>```

答:
Should be pretty simple -

*Assuming you're using Pandas, and this is a pandas dataframe called df with columns date and value

Creating a demo dataframe and importing required packages, you would probably import your table as a dataframe!

import pandas as pd
import math
import statistics

df = pd.DataFrame({'date': ['2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02'],
                   'value': [12,32,12,23,12,14,15,54,43,64,21,15]})

#If you need to save results as a DataFrame later on
res = pd.DataFrame(columns = ['date','top_10p_mean'])
```
<ol>
<li>Filter based on dates</li>
</ol>
<p><em>Basically getting a list of different dates and iterating through them to get values in a list</em></p>
<pre class="lang-python prettyprint-override"><code>for date in df['date'].unique():
   temp = list(df['value'][df['date'] == date])
</code>```

Sort filtered set by values

Sorting the list in reverse order to have highest values at the top or you can just omit the reverse=True part to keep values as is

   temp.sort(reverse=True)
```
<ol start="3">
<li>Take mean of top 10% values</li>
</ol>
<p><em>This will calculate the number of items in top 10% of the list (the index is rounded up to the next integer), take those values and calculate the mean.</em></p>
<p><em>Further explanation of the functions for beginners -</em></p>
<p><em>First "round_up_to_next_integer(total_number_of_items(in_list) * 10%)"</em></p>
<p><em>Then "give_me_mean_of(list_items[from_index_0 : the_number_I_got_from_the_percentage_calculation])"</em></p>
<pre class="lang-python prettyprint-override"><code>   avg = statistics.mean(temp[0:math.ceil(len(temp)*0.1)])
</code>```

Print it or save in a new DataFrame

Printing the results and appending it to the previously created empty DataFrame

   print('Mean value on ' + str(date) + ' = ' + str(avg))
   res = res.append({'date': date, 'top_10p_mean': avg}, ignore_index=True)
```
<p>So in total it should work something like this -</p>
<pre class="lang-python prettyprint-override"><code>import pandas as pd
import math
import statistics

df = pd.DataFrame({'date': ['2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02'],
                   'value': [12,32,12,23,12,14,15,54,43,64,21,15]})

df
Out[]:
          date  value
0   2021-04-01     12
1   2021-04-01     32
2   2021-04-01     12
3   2021-04-01     23
4   2021-04-01     12
5   2021-04-02     14
6   2021-04-02     15
7   2021-04-02     54
8   2021-04-02     43
9   2021-04-02     64
10  2021-04-02     21
11  2021-04-02     15

res = pd.DataFrame(columns = ['date','top_10p_mean'])

for date in df['date'].unique():
   temp = list(df['value'][df['date'] == date])
   temp.sort(reverse=True)
   print(temp)                                            #Just to show what it looks like
   avg = statistics.mean(temp[0:math.ceil(len(temp)*0.1)])
   print('\nMean value on ' + str(date) + ' = ' + str(avg) + '\n')
   res = res.append({'date': date, 'top_10p_mean': avg}, ignore_index=True)

Out[]:
[32, 23, 12, 12, 12]

Mean value on 2021-04-01 = 32

[64, 54, 43, 21, 15, 15, 14]

Mean value on 2021-04-02 = 64

res
Out[]:
         date top_10p_mean
0  2021-04-01           32
1  2021-04-02           64
</code>```

Body:
I have a dataframe that consist of the day column and a score column. So per day, there are many values. So I need to get the mean of the top 10% values per day. Simply means I need the output as a day column and mean of the top 10% values of that day.

this is a example dataset screenshot

`{'Date':
 [
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1)],
 'value': [
  3.35,
  1.85,
  1.3,
  1.85,
  1.85,
  1.17,
  1.17,
  2.8,
  1.43,
  2.54,
  1.22,
  2.54,
  1.17,
  1.17,
  2.71,
  5.98,
  1.39,
  1.48,
  16.46,
  1.43,
  8.39,
  33.99,
  2.54,
  11.8,
  2.13,
  2.24,
  2.92,
  1.35,
  1.54,
  2.52]}`

Body:
Should be pretty simple -

*Assuming you're using Pandas, and this is a pandas dataframe called df with columns date and value

Creating a demo dataframe and importing required packages, you would probably import your table as a dataframe!

import pandas as pd
import math
import statistics

df = pd.DataFrame({'date': ['2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02'],
                   'value': [12,32,12,23,12,14,15,54,43,64,21,15]})

#If you need to save results as a DataFrame later on
res = pd.DataFrame(columns = ['date','top_10p_mean'])

Filter based on dates

Basically getting a list of different dates and iterating through them to get values in a list

for date in df['date'].unique():
   temp = list(df['value'][df['date'] == date])

Sort filtered set by values

Sorting the list in reverse order to have highest values at the top or you can just omit the reverse=True part to keep values as is

   temp.sort(reverse=True)

Take mean of top 10% values

This will calculate the number of items in top 10% of the list (the index is rounded up to the next integer), take those values and calculate the mean.

Further explanation of the functions for beginners -

First "round_up_to_next_integer(total_number_of_items(in_list) * 10%)"

Then "give_me_mean_of(list_items[from_index_0 : the_number_I_got_from_the_percentage_calculation])"

   avg = statistics.mean(temp[0:math.ceil(len(temp)*0.1)])

Print it or save in a new DataFrame

Printing the results and appending it to the previously created empty DataFrame

   print('Mean value on ' + str(date) + ' = ' + str(avg))
   res = res.append({'date': date, 'top_10p_mean': avg}, ignore_index=True)

So in total it should work something like this -

import pandas as pd
import math
import statistics

df = pd.DataFrame({'date': ['2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-01','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02','2021-04-02'],
                   'value': [12,32,12,23,12,14,15,54,43,64,21,15]})

df
Out[]:
          date  value
0   2021-04-01     12
1   2021-04-01     32
2   2021-04-01     12
3   2021-04-01     23
4   2021-04-01     12
5   2021-04-02     14
6   2021-04-02     15
7   2021-04-02     54
8   2021-04-02     43
9   2021-04-02     64
10  2021-04-02     21
11  2021-04-02     15

res = pd.DataFrame(columns = ['date','top_10p_mean'])

for date in df['date'].unique():
   temp = list(df['value'][df['date'] == date])
   temp.sort(reverse=True)
   print(temp)                                            #Just to show what it looks like
   avg = statistics.mean(temp[0:math.ceil(len(temp)*0.1)])
   print('\nMean value on ' + str(date) + ' = ' + str(avg) + '\n')
   res = res.append({'date': date, 'top_10p_mean': avg}, ignore_index=True)

Out[]:
[32, 23, 12, 12, 12]

Mean value on 2021-04-01 = 32

[64, 54, 43, 21, 15, 15, 14]

Mean value on 2021-04-02 = 64

res
Out[]:
         date top_10p_mean
0  2021-04-01           32
1  2021-04-02           64


来源: stackexchange

问:
Can Pyramid's Built-in Authentication/Authorization Implement Complex Security Schemes?
It seems like the security model fits very small projects, but that it is probably not feasible to write all possible registered users' hashed passwords in security.py.  Do you know any examples of scaling up Pyramid's authentication, or are there any benefits to calling through Pyramid's security scheme into my own database of security information?</p>

答:
I dont think the size of the project is related to the security model. Either you want a simple or a complex security model. Both can be applied to projects of any size. One of Pyramid's strong points is its extensibility.

Why would you store hashed passwords in security.py? (cmiiw here, I probably misunderstood) If you read this on someone's code, that's probably just an example. In real apps, you save them in a storage/persistence system of your choice.

Again, I don't understand what you mean by "scaling up authentication". My guess is you want some working examples:

tutorial from the docs

shootout application: small and good example with forms

pyramid auth demo: complex/granular/row-level permission

pyramid apex: 3rd party auth (google, twitter, etc) with velruse, forms etc

pyramid registration: unfinished library; you can steal some ideas from it

ContentLicense: CC BY-SA 3.0


问:
How to sum data by date filter in Javascript?
I try to find a solution to sum cost data (to group thme by day) with ISO date information in object.

My data object looks like :

```<code>0: {id: 45, title: 'abo', cost: 10, recurrent: true, date: '2022-02-09T20:43:30.139Z'}
1: {id: 123, title: 'test 4', cost: 20, recurrent: false, date: '2022-02-09T20:43:30.139Z'}
2: {id: 125, title: 'test 3', cost: 50, recurrent: false, date: '2022-02-06T23:00:00.000Z'}
3: {id: 125, title: 'test 2', cost: 100, recurrent: false, date: '2022-02-05T10:00:00.000Z'}
4: {id: 125, title: 'test 1', cost: 122, recurrent: false, date: '2022-02-04T23:00:00.000Z'}
</code>```

The expected result :
sumData = [222,50,30]

Total cost for the 2022-02-05 = 222

Total cost for the 2022-02-06 = 50

Total cost for the 2022-02-09 = 30

I try to sum with something like that :

```<code>    let currentDate     = '';
    let currentTotal    = 0;
    let sumData         = [];

    if(data) {
        for (let index = 0; index < data.length; index++) {

            //init date to compare with
            if(currentDate === '') {
                currentDate = new Date(data[index].date);
                currentTotal = data[index].cost;
            }
            else {
                const nextDate =  new Date(data[index].date);
                //test if is same day, sum expenses and add in sumData array
                if(currentDate.getFullYear() === nextDate.getFullYear() &&
                currentDate.getMonth() === nextDate.getMonth() &&
                currentDate.getDate() === nextDate.getDate())
                {
                    console.log('DATE = ' + currentDate.getDate());
                    console.log(data[index].date);
                    console.log('COST = ' + data[index].cost);
                    console.log('currentTotal = ' + currentTotal);
                    currentTotal = currentTotal + data[index].cost;
                    console.log(index + ' - COST = ' + data[index].cost);
                    console.log('TOTAL = ' + currentTotal);
                    console.log('===========');
                }
                else {
                    //push last valid sum before reset
                    currentTotal = 0;
                    //reset sum with last data
                    currentTotal = data[index].cost;
                }
                currentDate =  new Date(data[index].date);
            }
        }
    }
    console.log('== SUM data ==');
    sumData.push(currentTotal);

</code>```

答:
You can try to use .reduce() and Object.values() to achieve your goal:

const data = [
{id: 45, title: 'abo', cost: 10, recurrent: true, date: '2022-02-09T20:43:30.139Z'},
{id: 123, title: 'test 4', cost: 20, recurrent: false, date: '2022-02-09T20:43:30.139Z'},
{id: 125, title: 'test 3', cost: 50, recurrent: false, date: '2022-02-06T23:00:00.000Z'},
{id: 125, title: 'test 2', cost: 100, recurrent: false, date: '2022-02-05T10:00:00.000Z'},
{id: 125, title: 'test 1', cost: 122, recurrent: false, date: '2022-02-04T23:00:00.000Z'}
]

const res = Object.values(data.reduce((resMap, obj) => {
  const date = new Date(obj.date).toLocaleString().split(',')[0]
  if (resMap[date] !== undefined)
    resMap[date] += obj.cost
  else
    resMap[date] = obj.cost

  return resMap;
}, {}))

console.log(res)```

Update: use ISO8601 date

ContentLicense: CC BY-SA 4.0

Body:
I try to find a solution to sum cost data (to group thme by day) with ISO date information in object.

My data object looks like :

0: {id: 45, title: 'abo', cost: 10, recurrent: true, date: '2022-02-09T20:43:30.139Z'}
1: {id: 123, title: 'test 4', cost: 20, recurrent: false, date: '2022-02-09T20:43:30.139Z'}
2: {id: 125, title: 'test 3', cost: 50, recurrent: false, date: '2022-02-06T23:00:00.000Z'}
3: {id: 125, title: 'test 2', cost: 100, recurrent: false, date: '2022-02-05T10:00:00.000Z'}
4: {id: 125, title: 'test 1', cost: 122, recurrent: false, date: '2022-02-04T23:00:00.000Z'}

The expected result :
sumData = [222,50,30]

Total cost for the 2022-02-05 = 222

Total cost for the 2022-02-06 = 50

Total cost for the 2022-02-09 = 30

I try to sum with something like that :

    let currentDate     = '';
    let currentTotal    = 0;
    let sumData         = [];

    if(data) {
        for (let index = 0; index < data.length; index++) {

            //init date to compare with
            if(currentDate === '') {
                currentDate = new Date(data[index].date);
                currentTotal = data[index].cost;
            }
            else {
                const nextDate =  new Date(data[index].date);
                //test if is same day, sum expenses and add in sumData array
                if(currentDate.getFullYear() === nextDate.getFullYear() &&
                currentDate.getMonth() === nextDate.getMonth() &&
                currentDate.getDate() === nextDate.getDate())
                {
                    console.log('DATE = ' + currentDate.getDate());
                    console.log(data[index].date);
                    console.log('COST = ' + data[index].cost);
                    console.log('currentTotal = ' + currentTotal);
                    currentTotal = currentTotal + data[index].cost;
                    console.log(index + ' - COST = ' + data[index].cost);
                    console.log('TOTAL = ' + currentTotal);
                    console.log('===========');
                }
                else {
                    //push last valid sum before reset
                    currentTotal = 0;
                    //reset sum with last data
                    currentTotal = data[index].cost;
                }
                currentDate =  new Date(data[index].date);
            }
        }
    }
    console.log('== SUM data ==');
    sumData.push(currentTotal);

Body:
You can try to use .reduce() and Object.values() to achieve your goal:

const data = [
{id: 45, title: 'abo', cost: 10, recurrent: true, date: '2022-02-09T20:43:30.139Z'},
{id: 123, title: 'test 4', cost: 20, recurrent: false, date: '2022-02-09T20:43:30.139Z'},
{id: 125, title: 'test 3', cost: 50, recurrent: false, date: '2022-02-06T23:00:00.000Z'},
{id: 125, title: 'test 2', cost: 100, recurrent: false, date: '2022-02-05T10:00:00.000Z'},
{id: 125, title: 'test 1', cost: 122, recurrent: false, date: '2022-02-04T23:00:00.000Z'}
]

const res = Object.values(data.reduce((resMap, obj) => {
  const date = new Date(obj.date).toLocaleString().split(',')[0]
  if (resMap[date] !== undefined)
    resMap[date] += obj.cost
  else
    resMap[date] = obj.cost

  return resMap;
}, {}))

console.log(res)

Update: use ISO8601 date


问:
Azure durable function deployment options for multiple versions of a function app
I have an Azure functions app, which contains durable functions. I need to deploy multiple versions of durable functions side-by-side where they could be running for a while before they complete. I want to make sure I'm allowing the previous versions to complete without breaking orchestrations when the sequence or checkpoint data result changes. I'm aware of options like using slots and versioning inside of code, but that doesn't seem viable for longer running orchestrations.

I'm looking at the application router approach described here: Zero-downtime deployment for Durable Functions: Application Routing

Curious if anyone has used this approach and if there are other recommended approaches outside of the ones mentioned in that article.

Function proxies seem interesting here for the multiple version routing portion, but it not totally clear how to leverage it to perform something similar to the application router idea.

答: We are using 2 slots, 1 storage account, unique task hub names per slot. Has been working well so far for a few months.</p>


问:
Can I use @table variable in SQL Server Report Builder?
Using SQL Server 2008 Reporting services:

I'm trying to write a report that displays some correlated data so I thought to use a @table variable like so

```<code>DECLARE @Results TABLE (Number int
                       ,Name nvarchar(250)
                       ,Total1 money
                       ,Total2 money
                       )

insert into @Results(Number, Name, Total1)
select number, name, sum(total)
from table1
group by number, name

update @Results
set total2 = total
from
(select number, sum(total) from table2) s
where s.number = number

select from @results
</code>```

However, Report Builder keeps asking to enter a value for the variable @Results. It this at all possible?

EDIT: As suggested by KM I've used a stored procedure to solve my immediate problem, but the original question still stands: can I use @table variables in Report Builder?

答:
It's possible, only declare your table with '@@'. Example:</p>
```<code>DECLARE @@results TABLE (Number int
                       ,Name nvarchar(250)
                       ,Total1 money
                       ,Total2 money
                       )

insert into @@results (Number, Name, Total1)
select number, name, sum(total)
from table1
group by number, name

update @@results
set total2 = total
from
(select number, sum(total) from table2) s
where s.number = number

select * from @@results
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Using SQL Server 2008 Reporting services:

I'm trying to write a report that displays some correlated data so I thought to use a @table variable like so

DECLARE @Results TABLE (Number int
                       ,Name nvarchar(250)
                       ,Total1 money
                       ,Total2 money
                       )

insert into @Results(Number, Name, Total1)
select number, name, sum(total)
from table1
group by number, name

update @Results
set total2 = total
from
(select number, sum(total) from table2) s
where s.number = number

select from @results

However, Report Builder keeps asking to enter a value for the variable @Results. It this at all possible?

EDIT: As suggested by KM I've used a stored procedure to solve my immediate problem, but the original question still stands: can I use @table variables in Report Builder?

Body:
It's possible, only declare your table with '@@'. Example:

DECLARE @@results TABLE (Number int
                       ,Name nvarchar(250)
                       ,Total1 money
                       ,Total2 money
                       )

insert into @@results (Number, Name, Total1)
select number, name, sum(total)
from table1
group by number, name

update @@results
set total2 = total
from
(select number, sum(total) from table2) s
where s.number = number

select * from @@results


问:
Why does java force all interface members to be public?
Suppose I have a file test.java with the following:

interface IA {
  void f();
}

class A implements IA {
  public void f() {
    System.out.println("test");
  }
}
```

void f() in interface IA is public by default as mentioned in the docs:

All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

This forces me to include the public modifier in my implementation of f in class A. Why does java force all implementations of interface members to be fully public? What if I only wanted f to be accessible from my own package?

EDIT to clarify

Interfaces are by default package-private but interface members are by default public. In the code example I show above, this forces me to declare A's implementation of f as public. But I don't see why this has to be the case. Consider the following table from the docs:

Modifier
Class
Package
Subclass
World

public
Y
Y
Y
Y

protected
Y
Y
Y
N

no modifier
Y
Y
N
N

private
Y
N
N
N

Why can the interface member f not be package-private or protected? In this case the implementing class A is not in another package, but in the same package. Therefore public is too "public" for my purposes. Furthermore it breaks the rule of thumb mentioned in the docs:

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.

答:
Your A class has the default modifier. So you can start by reducing accessibility by the class modifier. An interface is a public contract (but interface itself does not need to have the public modifier. It can have the default modifier for example.). So, if it is a public contract and you implement it, is because you want to say to the world that you follow that contract. You can always implement a method without implementing the interface. You loose the interchange that interface allows.

So think for a second. You have class A that says it implements IA. Your class, since implements IA is used somewhere else, since follow the public contract. If you have reduced the visibility of that method what will occur? The implications of breaking the contract are too many. It's like you have a collection that implements List, and then you make all interface methods that you implement private. What happens when you try to use you class as an interface instance?

In Java you cannot reduce a method visibility when implementing an interface or extending a class.

Body:
Suppose I have a file test.java with the following:

interface IA {
  void f();
}

class A implements IA {
  public void f() {
    System.out.println("test");
  }
}

void f() in interface IA is public by default as mentioned in the docs:

All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

This forces me to include the public modifier in my implementation of f in class A. Why does java force all implementations of interface members to be fully public? What if I only wanted f to be accessible from my own package?

EDIT to clarify

Interfaces are by default package-private but interface members are by default public. In the code example I show above, this forces me to declare A's implementation of f as public. But I don't see why this has to be the case. Consider the following table from the docs:

Modifier
Class
Package
Subclass
World

public
Y
Y
Y
Y

protected
Y
Y
Y
N

no modifier
Y
Y
N
N

private
Y
N
N
N

Why can the interface member f not be package-private or protected? In this case the implementing class A is not in another package, but in the same package. Therefore public is too "public" for my purposes. Furthermore it breaks the rule of thumb mentioned in the docs:

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.


问:
How to make log10 ONLY first y-axis (not secondary y-axis) in ggplot in R
I would like to plot ONLY y-axis1 DATA (left axis, Var1, dotted line) as a log10 scale. The dotted line would therefore look higher on the y-axis and differences between 1 and 2 would be noticeable.

I have tried several things, but does not work ( I believe I am using them in the wrong order/place) such as:

+coord_trans(y='log10')--> empty plot

scale_y_continuous(trans = log10_trans(),... --> makes both Var1 and Var 2 log10

scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),labels = trans_format("log10", math_format(10^.x)))--> makes both y axis log10 and removes y-axis2 (Var2)

```<code>data<- data.frame(
      Day=c(1,2,3,1,2,3,1,2,3),
      Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
      Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
      Var2= c(4,16,39,2,22,39,41,10,3))

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2*1000, x=Day),stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, Var1), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    sec.axis=sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))
</code>```

答:
You absolutely should read the answer @teunbrand linked to in the comment to your question.  But for the matter of displaying log values on the left and original values on the right, you can use:</p>
```<code>tibble(Day = 1:10,
       Val1 =10*Day) %>%
    ggplot(aes(x = Day, y = log10(Val1))) +
    geom_col() +
    scale_y_log10(name = "log(Val1)",
                  sec.axis = sec_axis(~ 10^., name = "Val1"))
</code>```

Body:
I would like to plot ONLY y-axis1 DATA (left axis, Var1, dotted line) as a log10 scale. The dotted line would therefore look higher on the y-axis and differences between 1 and 2 would be noticeable.

I have tried several things, but does not work ( I believe I am using them in the wrong order/place) such as:

+coord_trans(y='log10')--> empty plot

scale_y_continuous(trans = log10_trans(),... --> makes both Var1 and Var 2 log10

scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),labels = trans_format("log10", math_format(10^.x)))--> makes both y axis log10 and removes y-axis2 (Var2)

data<- data.frame(
      Day=c(1,2,3,1,2,3,1,2,3),
      Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
      Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
      Var2= c(4,16,39,2,22,39,41,10,3))

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2*1000, x=Day),stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, Var1), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    sec.axis=sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))

Body:
You absolutely should read the answer @teunbrand linked to in the comment to your question.  But for the matter of displaying log values on the left and original values on the right, you can use:

tibble(Day = 1:10,
       Val1 =10*Day) %>%
    ggplot(aes(x = Day, y = log10(Val1))) +
    geom_col() +
    scale_y_log10(name = "log(Val1)",
                  sec.axis = sec_axis(~ 10^., name = "Val1"))


问:
Filter array of associative rows to retain only rows with unique value in specified column
I have the following array:

```<code>$array = [
    ['id' => 1, 'code' => '342'],
    ['id' => 2, 'code' => '765'],
    ['id' => 3, 'code' => '134'],
    ['id' => 1, 'code' => '999'],
];
</code>```

Here Array[0]['id'] and Array[3]['id'] are duplicates with respect to ['id']. I want to remove one of them (doesn't matter which).

Actually I thought I found a solution with this code:

```<code>//data
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);

$ids = array();
for($i = 0;$i < count($row); $i++ )
{
    if (in_array($row[$i]['id'], $ids))
        {
            unset($row[$i]);
            continue;
        }

    $ids[] = $row[$i]['id'];

}

print_r($row);
</code>```

For some reason it works well with small arrays, but if I have a lot of values in it with multiple duplicates, it fails. Any suggestion to what I am missing?

答:
I want to remove one of them (doesn't matter which).

Okay, use array_column() to assign temporary first level keys using the id values.  Because PHP will not allow two elements in the same level to share the same key, each subsequent duplicate will overwrite the earlier encountered row.  Wrap that call in array_values() to remove the temporary keys (re-index the array).

Code: (Demo)

```<code>var_export(
    array_values(array_column($rows, null, 'id'))
);
</code>```

Output:

```<code>array (
  0 =>
  array (
    'id' => 1,
    'code' => '999',
  ),
  1 =>
  array (
    'id' => 2,
    'code' => '765',
  ),
  2 =>
  array (
    'id' => 3,
    'code' => '134',
  ),
)
</code>```

Body:
I have the following array:

$array = [
    ['id' => 1, 'code' => '342'],
    ['id' => 2, 'code' => '765'],
    ['id' => 3, 'code' => '134'],
    ['id' => 1, 'code' => '999'],
];

Here Array[0]['id'] and Array[3]['id'] are duplicates with respect to ['id']. I want to remove one of them (doesn't matter which).

Actually I thought I found a solution with this code:

//data
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);

$ids = array();
for($i = 0;$i < count($row); $i++ )
{
    if (in_array($row[$i]['id'], $ids))
        {
            unset($row[$i]);
            continue;
        }

    $ids[] = $row[$i]['id'];

}

print_r($row);

For some reason it works well with small arrays, but if I have a lot of values in it with multiple duplicates, it fails. Any suggestion to what I am missing?

Body:
I want to remove one of them (doesn't matter which).

Okay, use array_column() to assign temporary first level keys using the id values.  Because PHP will not allow two elements in the same level to share the same key, each subsequent duplicate will overwrite the earlier encountered row.  Wrap that call in array_values() to remove the temporary keys (re-index the array).

Code: (Demo)

var_export(
    array_values(array_column($rows, null, 'id'))
);

Output:

array (
  0 =>
  array (
    'id' => 1,
    'code' => '999',
  ),
  1 =>
  array (
    'id' => 2,
    'code' => '765',
  ),
  2 =>
  array (
    'id' => 3,
    'code' => '134',
  ),
)


问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答:
Of course profile to know for sure in each case.

That said, I think in general it will be the former because you aren't repeatedly parsing the format string.

However, the difference would be very small.  To the point that you really should consider using AppendFormat in most cases anyway.

OwnerDisplayName: Sergio

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

OwnerDisplayName: Joel Coehoorn


问:
Url rewriting question
This is my rule set up in web.config:

```<code>   <rule name="RedirectPopups" stopProcessing="true">
              <match url="^webforms/visitor/popup/*" />
              <conditions>
                <add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
                <add input="{QUERY_STRING}" pattern="^([^=&]+)=([^=&]+)$" />
              </conditions>
              <action type="Redirect" url="jwelery/INEEDTHEPAGEVARIABLEHERE/{C:1}/{C:2}" appendQueryString="false" redirectType="Permanent" />
            </rule>
</code>```

Basically I have my popups in webforms\visitor\popup. I want to write a rule that when  any page is request within this popup directory. It gets redirected to some custom url.

For Eg.

If user requests webforms/visitor/popup/HelloWorld.aspx?a=1

He should be redirected to jwelery/HelloWorld/a/1

I just need the solution for what should I write in "INEEDTHEPAGEVARIABLEHERE" in Redirect action. Is there any special variable that I can use? I am using IIS7

Thanks.

答:
Why don't you use

```<code><match url="^webforms/visitor/popup/([a-zA-Z0-9]+).aspx\?([a-zA-Z0-9]+)=([a-zA-Z0-9]+)$" />
<action type="Rewrite" url="jwelery/{R:1}/{R:2}/{R:3}" />
</code>```

?

Title: Url rewriting question

Body:
This is my rule set up in web.config:

   <rule name="RedirectPopups" stopProcessing="true">
              <match url="^webforms/visitor/popup/*" />
              <conditions>
                <add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
                <add input="{QUERY_STRING}" pattern="^([^=&]+)=([^=&]+)$" />
              </conditions>
              <action type="Redirect" url="jwelery/INEEDTHEPAGEVARIABLEHERE/{C:1}/{C:2}" appendQueryString="false" redirectType="Permanent" />
            </rule>

Basically I have my popups in webforms\visitor\popup. I want to write a rule that when  any page is request within this popup directory. It gets redirected to some custom url.

For Eg.

If user requests webforms/visitor/popup/HelloWorld.aspx?a=1

He should be redirected to jwelery/HelloWorld/a/1

I just need the solution for what should I write in "INEEDTHEPAGEVARIABLEHERE" in Redirect action. Is there any special variable that I can use? I am using IIS7

Thanks.

Body:
Why don't you use

<match url="^webforms/visitor/popup/([a-zA-Z0-9]+).aspx\?([a-zA-Z0-9]+)=([a-zA-Z0-9]+)$" />
<action type="Rewrite" url="jwelery/{R:1}/{R:2}/{R:3}" />

?


问:
White to Transparent Layer in matplotlib figure (SVG)
I would like to add a layer with a gradient (from white to transparent) on top of my matplotlib image and be able to save the result as an SVG eventually (I have some more shapes on my actual image than sketched below).

It is unclear to me, if this is possible with matplotlib + svg. Does anybody know or has a solution for this?

Here is some example code:

```<code>plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
# TODO: Add white -> transparent layer
plt.savefig("temp.svg", bbox_inches=0)
</code>```

The result should look like this:

Before:

After:

答:
Here I present two solutions. The first one is fast solution, will bloat (just a little) the SVG size, but will yield better looking results than using a raster image. The second one produces what you'd expect for an SVG with gradients, but it is slower.

First option
As matplotlib currently does not support gradients (see here), you can mimic a gradient using a not so large number of semitransparent rectangles. You can choose how many rectangles to use, where the transparency ends, and the color of the transparency:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import  Rectangle

def add_veil(ax, top, n_steps=20, color='white'):
    starts, height = np.linspace(0, top, n_steps, endpoint=False, retstep=True)
    rects = [Rectangle((0, s), 1, height, facecolor=color, zorder=2.01,
                        alpha=(1-(n_a/n_steps)), transform=ax.transAxes)
             for n_a, s in enumerate(starts)]
    for r in rects:
        ax.add_patch(r)

plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.plot(x, y)
plt.axis('off')
ax = plt.gca()
ax.set_position([0, 0, 1, 1])
# DONE: Add white -> transparent layer
add_veil(ax, 1, 100)
plt.savefig("temp.svg", bbox_inches=0)
```
<p>Result:</p>
<p><img src="https://i.stack.imgur.com/eXQi1.png" alt="Final result" /></p>
<p>I had very good results with 20 rectangles or less.
I guess you can adapt it yo use a non linear gradient, which usually looks better.</p>
<p><strong>Second option</strong>
The second option saves the SVG to memory, parses the XML, edits it and saves it. It is much slower since it has to parse the data. I made a class, so the data used for defining the gradient is generated only once.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import  Rectangle
import xml.etree.ElementTree as ET
import matplotlib
from io import BytesIO

class GradientAdder():
    def __init__(self):
        # First, define a linear gradient.
        lingrad = ET.Element('linearGradient')
        lingrad.set('id', "grad1")
        lingrad.set('x1', "0%")
        lingrad.set('y1', "100%")
        lingrad.set('x2', "0%")
        lingrad.set('y2', "0%")
        stop1 = ET.Element('stop')
        stop1.set('offset',"0%")
        stop1.set('style', "stop-color:rgb(255,255,255);stop-opacity:1")
        stop2 = ET.Element('stop')
        stop2.set('offset',"100%")
        stop2.set('style', "stop-color:rgb(255,255,255);stop-opacity:0")
        lingrad.append(stop1)
        lingrad.append(stop2)
        self._defs = ET.Element('defs')
        self._defs.append(lingrad)
        self._defs.set('id', 'veilid')
    def __call__(self, ax: matplotlib.axes.Axes, out_file: str):
        rect = Rectangle((0, 0), 1, 1, zorder=2.01, color=(1,1,1,0),
                         transform=ax.transAxes)
        ax.add_patch(rect)
        rect.set_gid("whiteVeil")  # We create a named patch
        # Save SVG in a fake file object.
        f = BytesIO()
        ax.figure.savefig(f, format="svg", bbox_inches=0)

        # This next line will break someday
        ET.register_namespace('', "http://www.w3.org/2000/svg")
        root, xmlid = ET.XMLID(f.getvalue())
        root.append(self._defs)
        rect = xmlid['whiteVeil'][0]
        rect.set('style', "fill:url(#grad1);fill-opacity:1")  #
        ET.ElementTree(root).write(out_file)

g = GradientAdder()

x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.figure(figsize=[6, 6])
plt.plot(x, y)
plt.axis('off')
ax = plt.gca()
ax.set_position([0, 0, 1, 1])

g(ax, "/tmp/test.svg")
</code>```

With this option, ypou have to stick to SVG's linear gradients. Note that it adds a transparent Rectangle over your figure

Other option

To obtain best results you can add a Rectangle patch over the Axes, and then fill it with a gradient using Inkscape in headless mode. See here and here. The documentation is scattered and missing.

Body:
I would like to add a layer with a gradient (from white to transparent) on top of my matplotlib image and be able to save the result as an SVG eventually (I have some more shapes on my actual image than sketched below).

It is unclear to me, if this is possible with matplotlib + svg. Does anybody know or has a solution for this?

Here is some example code:

plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
# TODO: Add white -> transparent layer
plt.savefig("temp.svg", bbox_inches=0)

The result should look like this:

Before:

After:

Body:
Here I present two solutions. The first one is fast solution, will bloat (just a little) the SVG size, but will yield better looking results than using a raster image. The second one produces what you'd expect for an SVG with gradients, but it is slower.

First option
As matplotlib currently does not support gradients (see here), you can mimic a gradient using a not so large number of semitransparent rectangles. You can choose how many rectangles to use, where the transparency ends, and the color of the transparency:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import  Rectangle

def add_veil(ax, top, n_steps=20, color='white'):
    starts, height = np.linspace(0, top, n_steps, endpoint=False, retstep=True)
    rects = [Rectangle((0, s), 1, height, facecolor=color, zorder=2.01,
                        alpha=(1-(n_a/n_steps)), transform=ax.transAxes)
             for n_a, s in enumerate(starts)]
    for r in rects:
        ax.add_patch(r)

plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.plot(x, y)
plt.axis('off')
ax = plt.gca()
ax.set_position([0, 0, 1, 1])
# DONE: Add white -> transparent layer
add_veil(ax, 1, 100)
plt.savefig("temp.svg", bbox_inches=0)

Result:

I had very good results with 20 rectangles or less.
I guess you can adapt it yo use a non linear gradient, which usually looks better.

Second option
The second option saves the SVG to memory, parses the XML, edits it and saves it. It is much slower since it has to parse the data. I made a class, so the data used for defining the gradient is generated only once.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import  Rectangle
import xml.etree.ElementTree as ET
import matplotlib
from io import BytesIO

class GradientAdder():
    def __init__(self):
        # First, define a linear gradient.
        lingrad = ET.Element('linearGradient')
        lingrad.set('id', "grad1")
        lingrad.set('x1', "0%")
        lingrad.set('y1', "100%")
        lingrad.set('x2', "0%")
        lingrad.set('y2', "0%")
        stop1 = ET.Element('stop')
        stop1.set('offset',"0%")
        stop1.set('style', "stop-color:rgb(255,255,255);stop-opacity:1")
        stop2 = ET.Element('stop')
        stop2.set('offset',"100%")
        stop2.set('style', "stop-color:rgb(255,255,255);stop-opacity:0")
        lingrad.append(stop1)
        lingrad.append(stop2)
        self._defs = ET.Element('defs')
        self._defs.append(lingrad)
        self._defs.set('id', 'veilid')
    def __call__(self, ax: matplotlib.axes.Axes, out_file: str):
        rect = Rectangle((0, 0), 1, 1, zorder=2.01, color=(1,1,1,0),
                         transform=ax.transAxes)
        ax.add_patch(rect)
        rect.set_gid("whiteVeil")  # We create a named patch
        # Save SVG in a fake file object.
        f = BytesIO()
        ax.figure.savefig(f, format="svg", bbox_inches=0)

        # This next line will break someday
        ET.register_namespace('', "http://www.w3.org/2000/svg")
        root, xmlid = ET.XMLID(f.getvalue())
        root.append(self._defs)
        rect = xmlid['whiteVeil'][0]
        rect.set('style', "fill:url(#grad1);fill-opacity:1")  #
        ET.ElementTree(root).write(out_file)

g = GradientAdder()

x = np.arange(0, 100, 0.00001)
y = np.sin(0.1* np.pi * x)
plt.figure(figsize=[6, 6])
plt.plot(x, y)
plt.axis('off')
ax = plt.gca()
ax.set_position([0, 0, 1, 1])

g(ax, "/tmp/test.svg")

With this option, ypou have to stick to SVG's linear gradients. Note that it adds a transparent Rectangle over your figure

Other option

To obtain best results you can add a Rectangle patch over the Axes, and then fill it with a gradient using Inkscape in headless mode. See here and here. The documentation is scattered and missing.


问:
Error removing directory which is not empty
I'm trying to delete a directory when all the tests finish with an after, and I get the following error:

```<code>fs.rmdir is not a function
</code>```

Here is mi code:

```<code>after(() => {
        const fs = require('fs');
        const dir = '../../../../../../downloads';

        fs.rmdir(dir, { recursive: true }, (err) => {
            if (err) {
                throw err;
            }
        });
    })
</code>```

答:
Seems like the recursive option is deprecated from Node.js 14.14.0 (what version do you use?), so you can now use:

fs.rm(dir, { recursive: true, force: true }, (err) => {
  if (err) {
    throw err;
  }
});
```

Body:
I'm trying to delete a directory when all the tests finish with an after, and I get the following error:

fs.rmdir is not a function

Here is mi code:

after(() => {
        const fs = require('fs');
        const dir = '../../../../../../downloads';

        fs.rmdir(dir, { recursive: true }, (err) => {
            if (err) {
                throw err;
            }
        });
    })


问:
How to show build datetime on my react web app using create-react-app?
tl;dr version - I want to show the date of deployment of the production application on the footer of my application so that the users know exactly when the application was last updated.

I want it to be automatic, but I can't think of a way to capture the current date time during build and then parse it into html (jsx) to show them.

Update - Btw, I use CRA and have no plans of ejecting from it! At least not for this.

Context - Why do I want this?
I have a production application in React that I don't have unrestricted access to. There were some issues raised on there and I was able to replicate it on my dev and I fixed the issues and deployed it (or I thought I did). But the issue remained on production and after more time debugging, I just asked for a lot of diagnostic information from them to check if there was something wrong with the production API or database etc. But it finally turned out that my deployment to production wasn't successful. I think that if I showed the last deployement date-time somewhere on the app, I could just ask that from the users rather than get into elaborate diagnostic information.

答:
A contribution to Joe Haddat's answer; if you want to illustrate the build date by using preval.macro in the viewer timezone instead of the environment timezone which builds the app, here is how to do it;

render() {
  const buildDate = preval`module.exports = new Date();`
  return (

Build Date: {new Date(buildDate).toLocaleString()}

  )
}

```

This will save the build date, but turning it into a locale string will still happen on runtime, on the browser where the viewer timezone is used.

Body:
A contribution to Joe Haddat's answer; if you want to illustrate the build date by using preval.macro in the viewer timezone instead of the environment timezone which builds the app, here is how to do it;

render() {
  const buildDate = preval`module.exports = new Date();`
  return (
     <div>Build Date: {new Date(buildDate).toLocaleString()}</div>
  )
}

This will save the build date, but turning it into a locale string will still happen on runtime, on the browser where the viewer timezone is used.


问:
How do i allow 'Access-Control-Allow-Origin' in Node.JS Http Server?
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem.
Here is my server:</p>
```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('@socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

app.post('/', (request, res) => {
  console.log("********************");
  console.log(" >POST RECEBIDO!!");
 console.log(res);

postData = request.body;
io.emit('message',postData);
 console.log(postData);

});

http.listen(3000, function(){

  console.log('listening on *:3000');

});
</code>```

答:
Install npm package called cors

After installing, on your file add this line app.use(cors()) will solve your issue of cors error I hope.

Body:
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem.
Here is my server:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('@socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

app.post('/', (request, res) => {
  console.log("********************");
  console.log(" >POST RECEBIDO!!");
 console.log(res);

postData = request.body;
io.emit('message',postData);
 console.log(postData);

});

http.listen(3000, function(){

  console.log('listening on *:3000');

});


问:
WSO2 IS - SCIM2 Invalid Token after PATCH
I am trying to figure out if the following behavior is the expected.
In my case, I am logged in as a user with username: testuser

I make a PATCH request from my Blazor SPA to the following URL https://myidentityserver/scim2/Me. This is the location the WSO2 IS is located.

The PATCH request,containing a password change and some other patched info,completes successfully and Status Code:200 OK is returned.

Immediately after the aforementioned PATCH request, a call to https://myidentityserver/oauth2/token is made and Status Code: 400 is returned containing the grant_type: refresh_token, client_id: myid, refresh_token:xxxxxx, meaning that the token is invalid.

In my understanding this is the expected behavior as the information that were present in the token have now been altered due to the PATCH and token should be invalidated.

WSO IS version: 5.11.0

答:
Answering my own question that I made in the comments

The answer was provived from the relevant WSO2 IS slack chat

'As per the question, the PATCH request contains a password change also. So in that case the exiating sessions will be invalidated as you mentioned. But for other claim updates which will be done from SCIM2 will not invalidate the existing sessions'


问:
Why my panel is hiding the body of my views?
i want to build a built a navigation with BottomTabNavigator but i dont know what happen i never see the body of my screens, something is hidding the body, i created a demo to demostrate you the wrong, but its too simple.

this is the file App.js

```<code>import React from 'react'
//import { Provider } from 'react-native-paper'
import { Provider, useSelector } from 'react-redux'
import { createStore } from 'redux'
import { NavigationContainer } from '@react-navigation/native'
import { View, Text } from 'react-native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'

const Stack = createStackNavigator()

function HomeScreen() {
  return (
    <View
      style={{
        flexDirection: 'row',
        height: 100,
        padding: 20,
      }}
    >
      <View style={{ backgroundColor: 'blue', flex: 0.3 }} />
      <View style={{ backgroundColor: 'red', flex: 0.5 }} />
      <Text>Hello World!</Text>
    </View>
  )
}

function SettingsScreen() {
  return (
    <View
      style={{
        backgroundColor: 'red',
        flex: 1,
        color: 'green',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Text>Settings!</Text>
    </View>
  )
}

const Tab = createBottomTabNavigator()

function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="main">
        <Stack.Screen name="loginScreen" component={SettingsScreen} />
        <Stack.Screen name="main" component={MyTabs} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}
</code>```

i am trying to do, before to user is logged i would like to hidde the tabs

something is hidding

edit 1: why i have 2 headers?

答:
Moving between screens

You can create a state for handling user logged in status or you can also use redux for it so It will automatically navigate to the main screen after user logged in

```<code>export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        {state.userToken == null ? (
          // No token found, user isn't signed in
          <Stack.Screen name="loginScreen" component={LoginScreen} />
        ) : (
          // User is signed in
          <Stack.Screen name="main" component={MyTabs} />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}
</code>```

More details Here

Body:
i want to build a built a navigation with BottomTabNavigator but i dont know what happen i never see the body of my screens, something is hidding the body, i created a demo to demostrate you the wrong, but its too simple.

this is the file App.js

import React from 'react'
//import { Provider } from 'react-native-paper'
import { Provider, useSelector } from 'react-redux'
import { createStore } from 'redux'
import { NavigationContainer } from '@react-navigation/native'
import { View, Text } from 'react-native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'

const Stack = createStackNavigator()

function HomeScreen() {
  return (
    <View
      style={{
        flexDirection: 'row',
        height: 100,
        padding: 20,
      }}
    >
      <View style={{ backgroundColor: 'blue', flex: 0.3 }} />
      <View style={{ backgroundColor: 'red', flex: 0.5 }} />
      <Text>Hello World!</Text>
    </View>
  )
}

function SettingsScreen() {
  return (
    <View
      style={{
        backgroundColor: 'red',
        flex: 1,
        color: 'green',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Text>Settings!</Text>
    </View>
  )
}

const Tab = createBottomTabNavigator()

function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="main">
        <Stack.Screen name="loginScreen" component={SettingsScreen} />
        <Stack.Screen name="main" component={MyTabs} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

i am trying to do, before to user is logged i would like to hidde the tabs

something is hidding

edit 1: why i have 2 headers?

Body:
Moving between screens

You can create a state for handling user logged in status or you can also use redux for it so It will automatically navigate to the main screen after user logged in

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        {state.userToken == null ? (
          // No token found, user isn't signed in
          <Stack.Screen name="loginScreen" component={LoginScreen} />
        ) : (
          // User is signed in
          <Stack.Screen name="main" component={MyTabs} />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

More details Here


问:
Replace the first 2 lines containing a string with a specific line with a bash script
I need to replace the first 2 occurrences of:

```<code>"<version>*"
</code>```

with

```<code>"<version>$NEW_VERSION</version>"
</code>```

within an already existing xml file.

Original:

```<code><groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.0-SNAPSHOT</version>
<version>1.3.0-SNAPSHOT</version>
</code>```

Desired result:

```<code><groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>
<version>1.3.1-SNAPSHOT</version>
</code>```

I've tried for a while now and this:

```<code>sed -i -e '0,/<version>*/s/<version>*/<version>1.3.1-SNAPSHOT<\/version>/' pom.xml
</code>```

gets close, but the resulting string is:

```<code><groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>1.3.0-SNAPSHOT</version>
</code>```

答:
This might work for you (GNU sed):

```<code>sed -E '/<version>/{x;s/^/x/;/xx{2}/!{x;s/(<version>)[^<]*/\1NEW VERSION/;x};x}' file
</code>```

Match <version> on any line,swap to the hold space, increment a counter and if that counter exceeds the required number of overall substitutions, continue with no further processing.

Otherwise, swap back to the pattern space and substitute the new version.

Body:
I need to replace the first 2 occurrences of:

"<version>*"

with

"<version>$NEW_VERSION</version>"

within an already existing xml file.

Original:

<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.0-SNAPSHOT</version>
<version>1.3.0-SNAPSHOT</version>

Desired result:

<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>
<version>1.3.1-SNAPSHOT</version>

I've tried for a while now and this:

sed -i -e '0,/<version>*/s/<version>*/<version>1.3.1-SNAPSHOT<\/version>/' pom.xml

gets close, but the resulting string is:

<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>1.3.0-SNAPSHOT</version>

Body:
This might work for you (GNU sed):

sed -E '/<version>/{x;s/^/x/;/xx{2}/!{x;s/(<version>)[^<]*/\1NEW VERSION/;x};x}' file

Match <version> on any line,swap to the hold space, increment a counter and if that counter exceeds the required number of overall substitutions, continue with no further processing.

Otherwise, swap back to the pattern space and substitute the new version.


问:
python minidom does not close <xml tag>
I'm experiencing a strange behaviour using minidom. I run the following code:

```<code>import os
import sys
from xml.dom import minidom
def generateReleaseXMLFile():
    modelPath = "%./model/"
    # Create the parser
    xsydoc  = minidom.Document()
    # Create the element ScriptModelVersion
    scriptModelVersion  = xsydoc.createElement('ScriptModelVersion')
    # Assign all the attributes
    scriptModelVersion.setAttribute("Major", "1")
    scriptModelVersion.setAttribute("Minor", "2")
    scriptModelVersion.setAttribute("Patch", "3")
    scriptModelVersion.setAttribute("ReseaseDate", "2011-05-20")
    # Append the root to the document
    xsydoc.appendChild(scriptModelVersion)
    # Create the file descriptor
    fdesc = open(modelPath+"Release.xml", "w")
    # Write the file
    fdesc.write(xsydoc.toprettyxml())
    # Close the file
    fdesc.close()
    print xsydoc.toprettyxml()

generateReleaseXMLFile()
</code>```

It generates the following output:

```<code><?xml version="1.0" ?>
<ScriptModelVersion Major="9" Minor="0" Patch="1" ReleaseDate="2011-05-20"/>
</code>```

whithout the xml tag closure.
I really have no idea about why it's keeping the document open. Did anyone experienced the same problem? Or am i simply forgetting somethink really obvious and i simply canot see the problem?

答:
Your XML is valid :
Have a look at : http://en.wikipedia.org/wiki/XML_Schema_%28W3C%29

You do not need to close declaration.

Title: python minidom does not close <xml tag>

Body:
I'm experiencing a strange behaviour using minidom. I run the following code:

import os
import sys
from xml.dom import minidom
def generateReleaseXMLFile():
    modelPath = "%./model/"
    # Create the parser
    xsydoc  = minidom.Document()
    # Create the element ScriptModelVersion
    scriptModelVersion  = xsydoc.createElement('ScriptModelVersion')
    # Assign all the attributes
    scriptModelVersion.setAttribute("Major", "1")
    scriptModelVersion.setAttribute("Minor", "2")
    scriptModelVersion.setAttribute("Patch", "3")
    scriptModelVersion.setAttribute("ReseaseDate", "2011-05-20")
    # Append the root to the document
    xsydoc.appendChild(scriptModelVersion)
    # Create the file descriptor
    fdesc = open(modelPath+"Release.xml", "w")
    # Write the file
    fdesc.write(xsydoc.toprettyxml())
    # Close the file
    fdesc.close()
    print xsydoc.toprettyxml()

generateReleaseXMLFile()

It generates the following output:

<?xml version="1.0" ?>


问:
How to disable or readonly select input angular
If the cardSelect variable is true, just let [readonly]="cardSelect"

```<code><select name="card-exp-month" #validateMonth formControlName="digiMes" class="form-
 control" name="validade" id="validade"   >
<option value="">Mês</option>
<option value="01">01 Jan</option>
<option value="02">02 Fev</option>
<option value="03">03 Mar</option>
<option value="04">04 Abr</option>
<option value="05">05 Mai</option>
<option value="06">06 Jun</option>
<option value="07">07 Jul</option>
<option value="08">08 Ago</option>
<option value="09">09 Set</option>
<option value="10">10 Out</option>
<option value="11">11 Nov</option>
<option value="12">12 Dez</option>
</select>
</code>```

When is input text its works

```<code><label for="nomeimpresso">Nome <b>impresso</b> no cartão<span class="text-danger"> *
</span></label>
<input #nomeImpresso formControlName="digiNome"  name="holder-name" id="nomeimpresso"
class="form-control col-lg-6" type="text"  [readonly]="cardSelect" >
</code>```

答:
As stated by @rmjoia, my previous answer is dangerous and should be avoided (see below).

Updated answer

For disabling the whole "select" element you can use a boolean variable declared in your controller (isDisabled in my following example)

In the HTML:

```<code><select [disabled]="isDisabled">
  <option>a</option>
</select>
</code>```

In the controller:

```<code>export class AppComponent {
  …

  // the variable declaration (at start the select is enabled)
  isDisabled = false;

  // later you may change the state of the select element.
  onClick() {
    this.isDisabled = true;
  }
}
</code>```

Some code implementing different solutions :
https://stackblitz.com/edit/angular-ivy-qkwier?file=src/app/app.component.html

Previous answer

For disabling the whole "select" element you can :

```<code>  <select … [disabled]="isSelectDisabled()">
  …
  </select>
</code>```

and decide in your controller the logic behind the isSelectDisabled method.

Body:
If the cardSelect variable is true, just let [readonly]="cardSelect"

<select name="card-exp-month" #validateMonth formControlName="digiMes" class="form-
 control" name="validade" id="validade"   >
<option value="">Mês</option>
<option value="01">01 Jan</option>
<option value="02">02 Fev</option>
<option value="03">03 Mar</option>
<option value="04">04 Abr</option>
<option value="05">05 Mai</option>
<option value="06">06 Jun</option>
<option value="07">07 Jul</option>
<option value="08">08 Ago</option>
<option value="09">09 Set</option>
<option value="10">10 Out</option>
<option value="11">11 Nov</option>
<option value="12">12 Dez</option>
</select>

When is input text its works

Nome impresso no cartão *

<input #nomeImpresso formControlName="digiNome"  name="holder-name" id="nomeimpresso"
class="form-control col-lg-6" type="text"  [readonly]="cardSelect" >

Body:
As stated by @rmjoia, my previous answer is dangerous and should be avoided (see below).

Updated answer

For disabling the whole "select" element you can use a boolean variable declared in your controller (isDisabled in my following example)

In the HTML:

<select [disabled]="isDisabled">
  <option>a</option>
</select>

In the controller:

export class AppComponent {
  …

  // the variable declaration (at start the select is enabled)
  isDisabled = false;

  // later you may change the state of the select element.
  onClick() {
    this.isDisabled = true;
  }
}

Some code implementing different solutions :
https://stackblitz.com/edit/angular-ivy-qkwier?file=src/app/app.component.html

Previous answer

For disabling the whole "select" element you can :

  <select … [disabled]="isSelectDisabled()">
  …
  </select>

and decide in your controller the logic behind the isSelectDisabled method.


问:
How to map multiple subdomains to single instance of MERN Multi tenant app?
I am building a multi tenant app using MERN stack. While learning about best practices to identify tenant, i fixed on subdomain approach. For example, on browsing URL like

tenant1.mydomain.com,

tenant2.mydomain.com

etc., the tenant1/tenant2 part of the URL is extracted as tenant identity to further authenticate users and start the app. As mentioned on https://github.com/facebook/create-react-app/issues/2292#issuecomment-302894212, i set up .env so CRA (npm run start) development server can serve on mapped domain instead of default localhost:3000 on development machine.

I suppose the approach works only for single tenant due to single subdomain mapping in .env, but don't know if and how multiple tenants can be taken care of. This whole stuff is new to me and i appreciate all possible help i can get to achieve multi tenancy goal.

答:
There are a few ways to do this, I particularly create a redirection of the subdomains to my main application domain. And this works for both development and production.

Initially I left it in fixed development like you did, but now I do it
as if it were in production, it makes the development more dynamic and
real.

On any system you have the HOST file.

Their path is usually in:

Windows 10: “C:\Windows\System32\drivers\etc\hosts”

Linux: “/etc/hosts”

Mac OS X: “/private/etc/hosts”

In the HOST file I point the subdomains to my local ip or application ip. Something like:

127.0.0.1 client1.myapp.com

127.0.0.1 client2.myapp.com

127.0.0.1 client3.myapp.com

In this case it's local but it works for production, so when I run my app I don't need to use 127.0.0.1 or localhost, I can use one of those domains, and even if they point to the same IP, that way I can get the domain from the client inside application, such as:

const domainName = window.location.hostname;
```

And now just use the domain to make the multitenancy logic work.

Body:
There are a few ways to do this, I particularly create a redirection of the subdomains to my main application domain. And this works for both development and production.

Initially I left it in fixed development like you did, but now I do it
as if it were in production, it makes the development more dynamic and
real.

On any system you have the HOST file.

Their path is usually in:

Windows 10: “C:\Windows\System32\drivers\etc\hosts”

Linux: “/etc/hosts”

Mac OS X: “/private/etc/hosts”

In the HOST file I point the subdomains to my local ip or application ip. Something like:

127.0.0.1 client1.myapp.com

127.0.0.1 client2.myapp.com

127.0.0.1 client3.myapp.com

In this case it's local but it works for production, so when I run my app I don't need to use 127.0.0.1 or localhost, I can use one of those domains, and even if they point to the same IP, that way I can get the domain from the client inside application, such as:

const domainName = window.location.hostname;

And now just use the domain to make the multitenancy logic work.


问:
How to add a property to a control's DataBindings
I want to write a control derived from CheckedListBoxControl (DevExpress), and I need to add a property to the (DataBindings)

These are the standard Properties shown in the PropertyGrid:

So I can only choose between Tag and Text.

What I want is to add a third option called gttMasterField (which will be of type int, don't know if this matters)

I have been experimenting with the documentation but with no results.

These don't seem to cover exact what I am looking for, I don't know the correct search terms to find this, which makes it difficult to google for it. It will probably be somewhere in the documentation but also there I don't know on what terms to look for.

Create a Windows Forms user control that supports simple data binding

Create a Windows Forms user control that supports lookup data binding

Create a Windows Forms user control that supports complex data binding

Here is some code with comments that will also help to explain what I am searching for

```<code>public partial class gttDXManyToManyCheckedListBox : CheckedListBoxControl
{
    private int _gttMasterField;

    // This I want populated by setting the binding property MasterField
    public int gttMasterField
    {
        get { return _gttMasterField; }
        set { _gttMasterField = value; }
    }
}
</code>```

The project is a dotnet framework 4.7.2

答:
To make a custom Property appear in the PropertyGrid's (DataBindings), decorate the Property with the BindableAttribute set to true:

```<code>[Bindable(true)]
public int gttMasterField
{
    get { return _gttMasterField; }
    set { _gttMasterField = value; }
}
</code>```

Optionally also decorate with the desired DesignerSerializationVisibilityAttribute attribute

```<code>[Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public int gttMasterField
{
    get { return _gttMasterField; }
    set { _gttMasterField = value; }
}
</code>```

The class can also specify the default bindable Property, settings a DefaultBindingPropertyAttribute:

```<code>[DefaultBindingProperty("gttMasterField")]
public partial class gttDXManyToManyCheckedListBox : CheckedListBoxControl
{
    private int _gttMasterField;

    [Bindable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public int gttMasterField
    {
        get { return _gttMasterField; }
        set { _gttMasterField = value; }
    }
}
</code>```

Important note:

the class should implement INotifyPropertyChanged -> a bindable Property is supposed to raise notification events. When the binding is set in the Designer, a BindingSource is generated to mediate the binding, but it requires that the objects involved send change notifications (mostrly to determine when the Property value is updated, usually as DataSourceUpdateMode.OnPropertyChanged).

For example:

```<code>using System.Runtime.CompilerServices;

[DefaultBindingProperty("gttMasterField")]
public partial class gttDXManyToManyCheckedListBox : CheckedListBoxControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int _gttMasterField;

    [Bindable(true)]
    public int gttMasterField
    {
        get { return _gttMasterField; }
        set { _gttMasterField = value; NotifyPropertyChanged(); }
    }

    private void NotifyPropertyChanged([CallerMemberName] string PropertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }
}
</code>```

Setting DesignerSerializationVisibility.Content implies initialization. If a BindingSource is used, this object supports initialization on itself, the Attribute is not strictly required.

It could be set to DesignerSerializationVisibility.Hidden, though, depending on the use case.

Body:
I want to write a control derived from CheckedListBoxControl (DevExpress), and I need to add a property to the (DataBindings)

These are the standard Properties shown in the PropertyGrid:

So I can only choose between Tag and Text.

What I want is to add a third option called gttMasterField (which will be of type int, don't know if this matters)

I have been experimenting with the documentation but with no results.

These don't seem to cover exact what I am looking for, I don't know the correct search terms to find this, which makes it difficult to google for it. It will probably be somewhere in the documentation but also there I don't know on what terms to look for.

Create a Windows Forms user control that supports simple data binding

Create a Windows Forms user control that supports lookup data binding

Create a Windows Forms user control that supports complex data binding

Here is some code with comments that will also help to explain what I am searching for

public partial class gttDXManyToManyCheckedListBox : CheckedListBoxControl
{
    private int _gttMasterField;

    // This I want populated by setting the binding property MasterField
    public int gttMasterField
    {
        get { return _gttMasterField; }
        set { _gttMasterField = value; }
    }
}

The project is a dotnet framework 4.7.2

Body:
To make a custom Property appear in the PropertyGrid's (DataBindings), decorate the Property with the BindableAttribute set to true:

[Bindable(true)]
public int gttMasterField
{
    get { return _gttMasterField; }
    set { _gttMasterField = value; }
}

Optionally also decorate with the desired DesignerSerializationVisibilityAttribute attribute

[Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public int gttMasterField
{
    get { return _gttMasterField; }
    set { _gttMasterField = value; }
}

The class can also specify the default bindable Property, settings a DefaultBindingPropertyAttribute:

[DefaultBindingProperty("gttMasterField")]
public partial class gttDXManyToManyCheckedListBox : CheckedListBoxControl
{
    private int _gttMasterField;

    [Bindable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public int gttMasterField
    {
        get { return _gttMasterField; }
        set { _gttMasterField = value; }
    }
}

Important note:

the class should implement INotifyPropertyChanged -> a bindable Property is supposed to raise notification events. When the binding is set in the Designer, a BindingSource is generated to mediate the binding, but it requires that the objects involved send change notifications (mostrly to determine when the Property value is updated, usually as DataSourceUpdateMode.OnPropertyChanged).

For example:

using System.Runtime.CompilerServices;

[DefaultBindingProperty("gttMasterField")]
public partial class gttDXManyToManyCheckedListBox : CheckedListBoxControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int _gttMasterField;

    [Bindable(true)]
    public int gttMasterField
    {
        get { return _gttMasterField; }
        set { _gttMasterField = value; NotifyPropertyChanged(); }
    }

    private void NotifyPropertyChanged([CallerMemberName] string PropertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }
}

Setting DesignerSerializationVisibility.Content implies initialization. If a BindingSource is used, this object supports initialization on itself, the Attribute is not strictly required.

It could be set to DesignerSerializationVisibility.Hidden, though, depending on the use case.


问:
Atom installation error on Windows 10
I was getting this error when trying to install Atom using the installer.

I tried to run as Administrator but ever having the same error.
So I opened the Setup Log and found this line in many places of the log:

```<code>Failed to load local releases, starting from scratch: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\david\AppData\Local\slack\packages\RELEASES'.
</code>```

答: What worked for me was closing Slack and terminating any of it's processes in Task Manager.</p>

Title: Atom installation error on Windows 10

Body:
I was getting this error when trying to install Atom using the installer.

I tried to run as Administrator but ever having the same error.
So I opened the Setup Log and found this line in many places of the log:

Failed to load local releases, starting from scratch: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\david\AppData\Local\slack\packages\RELEASES'.


问:
Feature selection not working in SVR with rbf kernel for n_features_to_select = 0.25 (anything below 1)
I have a dataset with the following dimension (x_train, y_train) :-

type : numpy.ndarray
dimension: x_train: (3618, 1425) and y_train : (3618,)
** sklearn version** : 0.24.1

I am trying to fit a Support Vector regression.
The code is as follows :

```<code>folds = KFold(n_splits = 5, shuffle = True, random_state = 100)

# specify range of hyperparameters
hyper_params = [{
                "n_features_to_select": [0.25, 0.5, 0.75, 1.0],
                "estimator__C" : [1000, 100 ],
                "estimator__epsilon" : [0.1, 0.001, 0]}]

# specify model
lm = SVR(kernel="rbf", max_iter=10000)
#lm.fit(x_train,y_train)
rfe = RFE(lm)

# set up GridSearchCV()
model_cv = GridSearchCV(estimator = rfe,
                        param_grid = hyper_params,
                        scoring= 'r2',
                        cv = folds,
                        verbose = 3,
                        return_train_score=True,
                        refit = True)

# fit the model
model_cv.fit(x_train, y_train)
</code>```

However, during fit I am getting Nan for both train and test score for n_features_to_select 0.25, 0.5 and 0.75 i.e everything that is not 1.0

```<code>[CV 1/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.2s
[CV 2/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.0s
[CV 3/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.0s
[CV 4/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.1s
[CV 5/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.0s
[CV 1/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.665) total time=  11.0s
[CV 2/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.666) total time=  11.1s
[CV 3/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.679) total time=  11.1s
[CV 4/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.663) total time=  11.1s
[CV 5/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.632) total time=  11.0s
</code>```

Why is this happening? And how to solve it ?

I tried another regression technique to check namely LinearRegression with

```<code>hyper_params = [{'n_features_to_select': [0.25, 0.5, 0.75, 1.0]}]
</code>```

It is working perfectly fine.

Minimal Replicable Toy Dataset

```<code>from sklearn.datasets import make_friedman1
from sklearn.feature_selection import RFE
from sklearn.svm import SVR
from sklearn.model_selection import KFold
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.model_selection import TimeSeriesSplit, GridSearchCV
from sklearn.preprocessing import StandardScaler
import numpy as np

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
estimator = SVR(kernel="rbf", max_iter=10000)
selector = RFE(estimator)

# set up GridSearchCV()
folds = KFold(n_splits = 5, shuffle = True, random_state = 100)

param = [{
    "estimator__C" : [1000, 100 ],
    "estimator__epsilon" : [0.1, 0.001, 0],
    "n_features_to_select": [0.25,0.5,0.75,1.0]
}]

gridsearch = GridSearchCV(estimator = selector,
                        param_grid = param,
                        scoring= 'r2',
                        cv = folds,
                        verbose = 3,
                        return_train_score=True,
                        refit = True)

selector = gridsearch.fit(X, y)

</code>```

I realised I was suppressing the warning, so adding the warning:

```<code>ValueError: when `importance_getter=='auto'`, the underlying estimator SVR should have `coef_` or `feature_importances_` attribute. Either pass a fitted estimator to feature selector or call fit before calling transform.

  warnings.warn(some_fits_failed_message, FitFailedWarning)
/home/subora/anaconda3/envs/thesis/lib/python3.9/site-packages/sklearn/model_selection/_search.py:969: UserWarning: One or more of the test scores are non-finite: [       nan        nan        nan 0.42252336        nan        nan
        nan 0.42192834        nan        nan        nan 0.42191628
        nan        nan        nan 0.42252336        nan        nan
        nan 0.42192834        nan        nan        nan 0.42191628]
  warnings.warn(
/home/subora/anaconda3/envs/thesis/lib/python3.9/site-packages/sklearn/model_selection/_search.py:969: UserWarning: One or more of the train scores are non-finite: [       nan        nan        nan 0.99969375        nan        nan
        nan 0.99999996        nan        nan        nan 1.
        nan        nan        nan 0.99969375        nan        nan
        nan 0.99999996        nan        nan        nan 1.        ]
  warnings.warn(
</code>```

Edit 2

Tried changing the kernel to linear and it is working fine as the estimator has coef_. so what I understood is feature selection only works with linear kernel.

答:
Check the documentation for importance_getterstr argument

importance_getterstr or callable, default=’auto’ If ‘auto’, uses the
feature importance either through a coef_ or feature_importances_
attributes of estimator.

So the feature selector needs the underlining estimator to expose either coef_ or feature_importances_ so that the features can be selected.

```<code>X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

svr = SVR(kernel="rbf")
lr = LinearRegression()
#selector = RFE(estimator, n_features_to_select=5, step=1)
svr = svr.fit(X, y)
lr = lr.fit(X,y)
print (hasattr(svr, "coef_"), hasattr(svr, "feature_importances_"))
print (hasattr(lr, "coef_"), hasattr(lr, "feature_importances_"))
</code>```

Output:

```<code>False False
True False
</code>```

you can see that the LinearRegression exposed coef_ however SVR does not implement either of them. So the feature selector with SVR as estimator will fail during feature selection. Note that this errors happens only when feature selection is done i.e when n_features_to_select != 1.0. When n_features_to_select==1.0 all the features will be used and so no feature selection will come into the picture.

```<code> RFE(estimator, n_features_to_select=1.0)
</code>```

will not fail but

```<code> RFE(estimator, n_features_to_select=0.9)
</code>```

will fail with SVR as estimator. For all the cases where it failed, the result is set to nan which is clear from the error messages

90 fits failed out of a total of 120. The score on these train-test
partitions for these parameters will be set to nan.

Fixed code:

```<code>X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
estimator = SVR(kernel="rbf", max_iter=10000)
selector = RFE(estimator)
# set up GridSearchCV()
folds = KFold(n_splits = 5, shuffle = True, random_state = 100)

param = [{
    "estimator__C" : [1000, 100 ],
    "estimator__epsilon" : [0.1, 0.001, 0],
    "n_features_to_select": [1.0]
}]

gridsearch = GridSearchCV(estimator = selector,
                        param_grid = param,
                        scoring= 'r2',
                        cv = folds,
                        verbose = 3,
                        return_train_score=True,
                        refit = True)

selector = gridsearch.fit(X, y)
</code>```

If you want to grid search on n_features_to_select then you will have to implement a function that returns the feature importance and give that function to the importance_getter argument of  RFE

Body:
I have a dataset with the following dimension (x_train, y_train) :-

type : numpy.ndarray
dimension: x_train: (3618, 1425) and y_train : (3618,)
** sklearn version** : 0.24.1

I am trying to fit a Support Vector regression.
The code is as follows :

folds = KFold(n_splits = 5, shuffle = True, random_state = 100)

# specify range of hyperparameters
hyper_params = [{
                "n_features_to_select": [0.25, 0.5, 0.75, 1.0],
                "estimator__C" : [1000, 100 ],
                "estimator__epsilon" : [0.1, 0.001, 0]}]

# specify model
lm = SVR(kernel="rbf", max_iter=10000)
#lm.fit(x_train,y_train)
rfe = RFE(lm)

# set up GridSearchCV()
model_cv = GridSearchCV(estimator = rfe,
                        param_grid = hyper_params,
                        scoring= 'r2',
                        cv = folds,
                        verbose = 3,
                        return_train_score=True,
                        refit = True)

# fit the model
model_cv.fit(x_train, y_train)

However, during fit I am getting Nan for both train and test score for n_features_to_select 0.25, 0.5 and 0.75 i.e everything that is not 1.0

[CV 1/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.2s
[CV 2/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.0s
[CV 3/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.0s
[CV 4/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.1s
[CV 5/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=0.75;, score=(train=nan, test=nan) total time=   8.0s
[CV 1/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.665) total time=  11.0s
[CV 2/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.666) total time=  11.1s
[CV 3/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.679) total time=  11.1s
[CV 4/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.663) total time=  11.1s
[CV 5/5] END estimator__C=1000, estimator__epsilon=0.1, n_features_to_select=1.0;, score=(train=1.000, test=0.632) total time=  11.0s

Why is this happening? And how to solve it ?

I tried another regression technique to check namely LinearRegression with

hyper_params = [{'n_features_to_select': [0.25, 0.5, 0.75, 1.0]}]

It is working perfectly fine.

Minimal Replicable Toy Dataset

from sklearn.datasets import make_friedman1
from sklearn.feature_selection import RFE
from sklearn.svm import SVR
from sklearn.model_selection import KFold
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.model_selection import TimeSeriesSplit, GridSearchCV
from sklearn.preprocessing import StandardScaler
import numpy as np

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
estimator = SVR(kernel="rbf", max_iter=10000)
selector = RFE(estimator)

# set up GridSearchCV()
folds = KFold(n_splits = 5, shuffle = True, random_state = 100)

param = [{
    "estimator__C" : [1000, 100 ],
    "estimator__epsilon" : [0.1, 0.001, 0],
    "n_features_to_select": [0.25,0.5,0.75,1.0]
}]

gridsearch = GridSearchCV(estimator = selector,
                        param_grid = param,
                        scoring= 'r2',
                        cv = folds,
                        verbose = 3,
                        return_train_score=True,
                        refit = True)

selector = gridsearch.fit(X, y)

I realised I was suppressing the warning, so adding the warning:

ValueError: when `importance_getter=='auto'`, the underlying estimator SVR should have `coef_` or `feature_importances_` attribute. Either pass a fitted estimator to feature selector or call fit before calling transform.

  warnings.warn(some_fits_failed_message, FitFailedWarning)
/home/subora/anaconda3/envs/thesis/lib/python3.9/site-packages/sklearn/model_selection/_search.py:969: UserWarning: One or more of the test scores are non-finite: [       nan        nan        nan 0.42252336        nan        nan
        nan 0.42192834        nan        nan        nan 0.42191628
        nan        nan        nan 0.42252336        nan        nan
        nan 0.42192834        nan        nan        nan 0.42191628]
  warnings.warn(
/home/subora/anaconda3/envs/thesis/lib/python3.9/site-packages/sklearn/model_selection/_search.py:969: UserWarning: One or more of the train scores are non-finite: [       nan        nan        nan 0.99969375        nan        nan
        nan 0.99999996        nan        nan        nan 1.
        nan        nan        nan 0.99969375        nan        nan
        nan 0.99999996        nan        nan        nan 1.        ]
  warnings.warn(

Edit 2

Tried changing the kernel to linear and it is working fine as the estimator has coef_. so what I understood is feature selection only works with linear kernel.

Body:
Check the documentation for importance_getterstr argument

importance_getterstr or callable, default=’auto’ If ‘auto’, uses the
feature importance either through a coef_ or feature_importances_
attributes of estimator.

So the feature selector needs the underlining estimator to expose either coef_ or feature_importances_ so that the features can be selected.

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

svr = SVR(kernel="rbf")
lr = LinearRegression()
#selector = RFE(estimator, n_features_to_select=5, step=1)
svr = svr.fit(X, y)
lr = lr.fit(X,y)
print (hasattr(svr, "coef_"), hasattr(svr, "feature_importances_"))
print (hasattr(lr, "coef_"), hasattr(lr, "feature_importances_"))

Output:

False False
True False

you can see that the LinearRegression exposed coef_ however SVR does not implement either of them. So the feature selector with SVR as estimator will fail during feature selection. Note that this errors happens only when feature selection is done i.e when n_features_to_select != 1.0. When n_features_to_select==1.0 all the features will be used and so no feature selection will come into the picture.

 RFE(estimator, n_features_to_select=1.0)

will not fail but

 RFE(estimator, n_features_to_select=0.9)

will fail with SVR as estimator. For all the cases where it failed, the result is set to nan which is clear from the error messages

90 fits failed out of a total of 120. The score on these train-test
partitions for these parameters will be set to nan.

Fixed code:

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
estimator = SVR(kernel="rbf", max_iter=10000)
selector = RFE(estimator)
# set up GridSearchCV()
folds = KFold(n_splits = 5, shuffle = True, random_state = 100)

param = [{
    "estimator__C" : [1000, 100 ],
    "estimator__epsilon" : [0.1, 0.001, 0],
    "n_features_to_select": [1.0]
}]

gridsearch = GridSearchCV(estimator = selector,
                        param_grid = param,
                        scoring= 'r2',
                        cv = folds,
                        verbose = 3,
                        return_train_score=True,
                        refit = True)

selector = gridsearch.fit(X, y)

If you want to grid search on n_features_to_select then you will have to implement a function that returns the feature importance and give that function to the importance_getter argument of  RFE


问:
How to return values from C/++ functions correctly?
I have made some app and the method im using is this:

```<code>INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}
</code>```

and I call it like:

```<code>char returned[255];
name(first,second,returned);
printf/cout;
</code>```

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

答:
Your function is a disaster, since one can easily execute a buffer overflow attack on it.

If you use C++, you could do the following:

```<code>void name(std::string one, std::string& two, std::string& buffer) {
    buffer = "omg";
....}
</code>```

Then you can just call it like:

```<code>std::string one, two, buffer;
name(one, two, buffer);
</code>```

Body:
I have made some app and the method im using is this:

INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}

and I call it like:

char returned[255];
name(first,second,returned);
printf/cout;

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

Body:
Your function is a disaster, since one can easily execute a buffer overflow attack on it.

If you use C++, you could do the following:

void name(std::string one, std::string& two, std::string& buffer) {
    buffer = "omg";
....}

Then you can just call it like:

std::string one, two, buffer;
name(one, two, buffer);


问:
Input groups bigger than input in Bootstrap 3 using Jumbotron container
I'm experimenting a strange behavior with Bootstrap 3 input groups. When I add an input-group-addon (text or icon) to a form inside a jumbotron, the input-group height is bigger than its input height.

Here you can find a JsFiddle and an screenshot with the problem:

```<code><div class="jumbotron">
    <h1>Jumbotron with form</h1>
        <form>
           <div class="input-group">
               <input type="text" class="form-control" placeholder="Username">
                  <span class="input-group-addon">@</span>
           </div>
        </form>
  </div>
</code>```

Live example at http://jsfiddle.net/DTcHh/

Screenshot:

How can I fix this problem? I'm looking for a Bootstrap solution but if that's not possible would be nice if you could help me to fix it with CSS rules.

答:
Simply add this css style on your header style tag.</p>
```<code>.input-group {  font-size:0px !important  }
</code>```

Body:
I'm experimenting a strange behavior with Bootstrap 3 input groups. When I add an input-group-addon (text or icon) to a form inside a jumbotron, the input-group height is bigger than its input height.

Here you can find a JsFiddle and an screenshot with the problem:

Jumbotron with form

        <form>

               <input type="text" class="form-control" placeholder="Username">
                  @

        </form>

Live example at http://jsfiddle.net/DTcHh/

Screenshot:

How can I fix this problem? I'm looking for a Bootstrap solution but if that's not possible would be nice if you could help me to fix it with CSS rules.

Body:
Simply add this css style on your header style tag.

.input-group {  font-size:0px !important  }


问:
Difference between: new ExampleConstructor and Object.create(ExampleConstructor)
Code as attached

```<code>function Bird() {
  let weight = 15;
  this.getWeight = () => weight
}

// let birb = new Bird
let birb = Object.create(Bird.prototype);

console.log(birb.getWeight())
</code>```

When I use new Bird it returns a function fine. However, when I use Object.create(Bird.prototype), I get a TypeError telling me birb.getWeight is not a function.

Why does creation from the prototype interfere with the function?

答: getWeight doesn't exist on the prototype. It is created on the object itself when the constructor function is run (which isn't happening when you use Object.create instead of calling the function).

Body:
Code as attached

function Bird() {
  let weight = 15;
  this.getWeight = () => weight
}

// let birb = new Bird
let birb = Object.create(Bird.prototype);

console.log(birb.getWeight())

When I use new Bird it returns a function fine. However, when I use Object.create(Bird.prototype), I get a TypeError telling me birb.getWeight is not a function.

Why does creation from the prototype interfere with the function?