问:
First, second and third element individually with only CSS
I'm looking for a way to target only 1, only 2 and only 3 of a given element - I know there are better ways, but this is more of a challenge to see if it's possible to easily target selectors at such a vague accuracy with only CSS.

```<code><div class="members-of">
    <h4 class="widget-title">Members of</h4>
    <ul>
        <li>
            <img src="image0.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image1.png" alt="">
        </li>
    </ul>
    <ul>
        <li>
            <img src="image3.png" alt="">
        </li>
    </ul>
    <div class="clear"></div>
</div>
</code>```

How would you tackle it with highest efficiency if all you could use was CSS?

```<code>/* Member 1 */
.members-of ul img:first-child {}
/* Member 2 */
.members-of ul img:nth-of-type... {}
/* Member 3 */
.members-of ul img:eq(@_o) {}
</code>```

答:
You can use nth-of-type, nth-child, :first-of-type, :last-of-type css selector.

**.members-of ul img:eq(@_o) {} **
// eq is not valid selector here,

eq for jQuery selector.

see below

```<code>
img{
  width: 50px;
  height: 50px;
  display: block;
}
.members-of ul:first-of-type li img{
  border: solid red;
}
.members-of ul:nth-of-type(2) li img{
  border: solid green;
}
.members-of ul:last-of-type li img{
  border: solid orange;
}

</code>```

or you can use with nth-child but you have to count also h4 tag for this.

```<code>img{
  width: 50px;
  height: 50px;
  display: block;
}
.members-of ul:nth-child(2) li img{
  border: solid red;
}
.members-of ul:nth-child(3) li img{
  border: solid green;
}
.members-of ul:nth-child(4) li img{
  border: solid orange;
}
</code>```

see here complete idea about css selectors

w3schools.com CSS Selectors

Body:
I'm looking for a way to target only 1, only 2 and only 3 of a given element - I know there are better ways, but this is more of a challenge to see if it's possible to easily target selectors at such a vague accuracy with only CSS.

Members of

How would you tackle it with highest efficiency if all you could use was CSS?

/* Member 1 */
.members-of ul img:first-child {}
/* Member 2 */
.members-of ul img:nth-of-type... {}
/* Member 3 */
.members-of ul img:eq(@_o) {}

Body:
You can use nth-of-type, nth-child, :first-of-type, :last-of-type css selector.

**.members-of ul img:eq(@_o) {} **
// eq is not valid selector here,

eq for jQuery selector.

see below

img{
  width: 50px;
  height: 50px;
  display: block;
}
.members-of ul:first-of-type li img{
  border: solid red;
}
.members-of ul:nth-of-type(2) li img{
  border: solid green;
}
.members-of ul:last-of-type li img{
  border: solid orange;
}

or you can use with nth-child but you have to count also h4 tag for this.

img{
  width: 50px;
  height: 50px;
  display: block;
}
.members-of ul:nth-child(2) li img{
  border: solid red;
}
.members-of ul:nth-child(3) li img{
  border: solid green;
}
.members-of ul:nth-child(4) li img{
  border: solid orange;
}

see here complete idea about css selectors

w3schools.com CSS Selectors


来源: stackexchange

问:
Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "character"
This is the code:

```<code>PRICE <- as.vector(my.data[,"PRICE"])
ADDRESS_CITY_NAME <- as.vector(my.data[,"ADDRESS_CITY_NAME"])

my.data <- data.frame(ADDRESS_CITY_NAME,log(UNITS), log(PRICE))

my.data %>%
  +group_by(ADDRESS_CITY_NAME)%>%
  +do(tidy(lm(UNITS~PRICE, data=my.data))
</code>```

The data I used (part of it):

```<code>287      INDEPENDENCE  4.1108739  0.42526774
288      INDEPENDENCE  4.1431347  0.47000363
289      INDEPENDENCE  4.2766661  0.17395331
290      INDEPENDENCE  4.0604430  0.46373402
291          LOVELAND  4.3820266  0.38526240
292          LOVELAND  4.2626799  0.42526774
293          LOVELAND  4.1271344  0.51282363
294          LOVELAND  4.8040210  0.43178242
295          LOVELAND  4.1896547  0.37843644
296          LOVELAND  4.2766661  0.32930375
297          LOVELAND  4.4543473  0.39204209
298          LOVELAND  4.3820266  0.39877612
299          LOVELAND  3.7841896  0.43178242
</code>```

I keep getting the error:
Error in UseMethod("group_by_") :    no applicable method for 'group_by_' applied to an object of class "character"

答:
It is in the data.frame creation step where the column names got changed

```<code>my.data <- data.frame(ADDRESS_CITY_NAME,log(UNITS), log(PRICE))
</code>```

Instead, it would be

```<code>my.data <- data.frame(ADDRESS_CITY_NAME,UNITS = log(UNITS), PRICE = log(PRICE))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is the code:

PRICE <- as.vector(my.data[,"PRICE"])
ADDRESS_CITY_NAME <- as.vector(my.data[,"ADDRESS_CITY_NAME"])

my.data <- data.frame(ADDRESS_CITY_NAME,log(UNITS), log(PRICE))

my.data %>%
  +group_by(ADDRESS_CITY_NAME)%>%
  +do(tidy(lm(UNITS~PRICE, data=my.data))

The data I used (part of it):

287      INDEPENDENCE  4.1108739  0.42526774
288      INDEPENDENCE  4.1431347  0.47000363
289      INDEPENDENCE  4.2766661  0.17395331
290      INDEPENDENCE  4.0604430  0.46373402
291          LOVELAND  4.3820266  0.38526240
292          LOVELAND  4.2626799  0.42526774
293          LOVELAND  4.1271344  0.51282363
294          LOVELAND  4.8040210  0.43178242
295          LOVELAND  4.1896547  0.37843644
296          LOVELAND  4.2766661  0.32930375
297          LOVELAND  4.4543473  0.39204209
298          LOVELAND  4.3820266  0.39877612
299          LOVELAND  3.7841896  0.43178242

I keep getting the error:
Error in UseMethod("group_by_") :    no applicable method for 'group_by_' applied to an object of class "character"

Body:
It is in the data.frame creation step where the column names got changed

my.data <- data.frame(ADDRESS_CITY_NAME,log(UNITS), log(PRICE))

Instead, it would be

my.data <- data.frame(ADDRESS_CITY_NAME,UNITS = log(UNITS), PRICE = log(PRICE))


问:
Checking some columns for specific values before insert/update using a trigger
I have a database FOO with several columns, among those I have one column "Url". I need to write a trigger before insert/update that will check the Url columns whether the newer value matches any existing values, i.e. "hello" except some predefined value. That means if "hello" is inserted or updated multiple times no error will happen otherwise it will check for duplicity. And if it finds some aborts the insertion update. This will also return some code so that my script calling for the insertion/update will know a failure has occurred. I know there might be other workarounds but I will need to have it this way. I am pretty new to SQL.

```<code>Foo {
    Url
}
</code>```

Here is the algorithm

```<code>Before update insert
if new value of Url is not "hello1" o "hello 2"
    check if new value of Url already exists in Foo.Url if so abort otherwise allow update/insert
     return something if aborted/success
</code>```

答:
try something like this.. you'll need to index your table.. </p>

```<code>    IF EXISTS(SELECT URL FROM  Foo.Url)
      BEGIN
       SELECT 'URL Exists Already'
      END
   ELSE
     BEGIN

      INSERT/UPDATE

     END
</code>```

Body:
I have a database FOO with several columns, among those I have one column "Url". I need to write a trigger before insert/update that will check the Url columns whether the newer value matches any existing values, i.e. "hello" except some predefined value. That means if "hello" is inserted or updated multiple times no error will happen otherwise it will check for duplicity. And if it finds some aborts the insertion update. This will also return some code so that my script calling for the insertion/update will know a failure has occurred. I know there might be other workarounds but I will need to have it this way. I am pretty new to SQL.

Foo {
    Url
}

Here is the algorithm

Before update insert
if new value of Url is not "hello1" o "hello 2"
    check if new value of Url already exists in Foo.Url if so abort otherwise allow update/insert
     return something if aborted/success

Body:
try something like this.. you'll need to index your table..

    IF EXISTS(SELECT URL FROM  Foo.Url)
      BEGIN
       SELECT 'URL Exists Already'
      END
   ELSE
     BEGIN

      INSERT/UPDATE

     END


问:
Removing elements from an array such that the sum becomes less than or equal to a particular value. (Not subarray)
I came across a practice problem wherein I am given with an array and I want to remove certain elements from it so that the sum becomes less than a given value but also the sum should be near to the given value.

Let the value be 17 and the array given be [2, 5, 6 , 8] then I can remove element 2nd such that the new array becomes [2, 6, 8] and the obtained sum is 16. Assume array to be in increasing order.

My attempt:

```<code>#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int main(){
    ll a,b;
    cin>>a>>b;
    vector<ll> v;
    map<ll,vector<ll>> mp;
    ll sum=0;
    for(ll i=0;i<b;i++){
        ll x;
        cin>>x;
        v.push_back(x);
        mp[x].push_back(i);
        sum+=x;
    }
    for(auto x:v) cout << x << " ";
    cout << endl;
  //  cout << sum << endl;
    if(sum<=a){
        cout << b << endl;
        for(ll i=0;i<b;i++){
            cout << i << " ";
        }
        cout << endl;
    }
   else{
       // sort(v.begin(),v.end());
        vector<ll> ind;

            cout << "sum:" << sum<< endl;
            for(auto i=v.begin();i!=v.end();++i){
               cout << "i val:" << (*i) << endl;
                sum = sum - (*i);
                ind.push_back(*mp[*i].begin());
                mp[*i].erase(mp[*i].begin());
                v.erase(i-1,i);
                for(auto x:v) cout << x << " ";
                cout << endl;
                if(sum>a) continue;
                else break;
            }
        cout << sum << endl;

    }
}
</code>```

答: First make sure it's ordered. In a loop, starting with the largest number in the array, subtract it from the sum. Compare to the target value, if sum still greater then remove and go back to start of loop, if not then store the absolute value (DIF) in a variable and restart the loop. Now your loop should look at the next largest number in the array and subtract from sum. Assuming we have a value for DIF, compare the absolute value of the current comparison to DIF. If DIF is closer then remove the previous number, exit the loop, and you are done. Otherwise you'll continue until you find the best result.</p>

Body:
I came across a practice problem wherein I am given with an array and I want to remove certain elements from it so that the sum becomes less than a given value but also the sum should be near to the given value.

Let the value be 17 and the array given be [2, 5, 6 , 8] then I can remove element 2nd such that the new array becomes [2, 6, 8] and the obtained sum is 16. Assume array to be in increasing order.

My attempt:

#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int main(){
    ll a,b;
    cin>>a>>b;
    vector<ll> v;
    map<ll,vector<ll>> mp;
    ll sum=0;
    for(ll i=0;i>x;
        v.push_back(x);
        mp[x].push_back(i);
        sum+=x;
    }
    for(auto x:v) cout << x << " ";
    cout << endl;
  //  cout << sum << endl;
    if(sum<=a){
        cout << b << endl;
        for(ll i=0;i<b;i++){
            cout << i << " ";
        }
        cout << endl;
    }
   else{
       // sort(v.begin(),v.end());
        vector<ll> ind;

            cout << "sum:" << sum<< endl;
            for(auto i=v.begin();i!=v.end();++i){
               cout << "i val:" << (*i) << endl;
                sum = sum - (*i);
                ind.push_back(*mp[*i].begin());
                mp[*i].erase(mp[*i].begin());
                v.erase(i-1,i);
                for(auto x:v) cout << x << " ";
                cout << endl;
                if(sum>a) continue;
                else break;
            }
        cout << sum << endl;

    }
}


问:
Multiple Project in Same Solution with inter-project depedencies - Deploy using Azure DevOps - CICD Pipeline
I have a Github repo that contains Visual Studio solution having multiple projects and want to setup Azure DevOps pipelines separately for the projects which will trigger according to the commit.

Solution

1) DataFactory

2) BusinessLogic

3) DataAcessLayer

4) WebAPI

5) UI

Also, One project have inter-project dependencies for other projects like

1 WebAPI => DataFactory & BusinessLogic

2 BusinessLogic => DataFactory & DataAcessLayer

So, This can be managed?
- I already tried paths

I'm not able to see any path filter here:

Please let me know how it can be done.

答:
Even though you don't get to see in the UI, you should be able to configure it using the YAML file for Github Repositories, Here is a guidance.</p>

```<code># specific path build
trigger:
  branches:
    include:
    - master
    - releases/*
  paths:
    include:
    - docs/*
    exclude:
    - docs/README.md
</code>```

Body:
Even though you don't get to see in the UI, you should be able to configure it using the YAML file for Github Repositories, Here is a guidance.

# specific path build
trigger:
  branches:
    include:
    - master
    - releases/*
  paths:
    include:
    - docs/*
    exclude:
    - docs/README.md


问:
Floating on both sides separately without interfering
I would like to decorate and shape the left and right borders of my text using float and clear properties. To start I have this markup which looks like the left and right stair steps should both start at the top of the page. However, the stairs aren't vertically aligned; the second stairs seem to always start drawing at the second-to-last step on the other side.

Left

Left Two

Left Number Three

Right

Right Two

Right Number Three

... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... .```

The result (same in Chrome + Firefox):

I'd like the stairs to both start at the beginning, as they seem like they should, since I'm only clearing floats on the side they're on. Note that I'm not just shaping the borders, I'm also showing important things on the shaped sides.

答:
The easyest way to solve the problem,
just to change places the rows like this:
green, red, green, red, green, red.
This code works properly:</p>

```<code><div style="float: left; clear: left; background: green;">Left</div>
<div style="float: right; clear: right; background: red;">Right</div>
<div style="float: left; clear: left; background: green;">Left Two</div>
<div style="float: right; clear: right; background: red;">Right Two</div>
<div style="float: left; clear: left; background: green;">Left Number Three</div>
<div style="float: right; clear: right; background: red;">Right Number Three</div>
</code>```

Body:
I would like to decorate and shape the left and right borders of my text using float and clear properties. To start I have this markup which looks like the left and right stair steps should both start at the top of the page. However, the stairs aren't vertically aligned; the second stairs seem to always start drawing at the second-to-last step on the other side.

Left

Left Two

Left Number Three

Right

Right Two

Right Number Three

... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... .

The result (same in Chrome + Firefox):

I'd like the stairs to both start at the beginning, as they seem like they should, since I'm only clearing floats on the side they're on. Note that I'm not just shaping the borders, I'm also showing important things on the shaped sides.

Body:
The easyest way to solve the problem,
just to change places the rows like this:
green, red, green, red, green, red.
This code works properly:

<div style="float: left; clear: left; background: green;">Left</div>
<div style="float: right; clear: right; background: red;">Right</div>
<div style="float: left; clear: left; background: green;">Left Two</div>
<div style="float: right; clear: right; background: red;">Right Two</div>
<div style="float: left; clear: left; background: green;">Left Number Three</div>
<div style="float: right; clear: right; background: red;">Right Number Three</div>


问:
Is it possible to make multiple ANDs into only one in SQL?
Is it possible to make multiple ANDs into only one? For example, something like this:

```<code>AND b.estado IS NULL AND c.estado IS NULL AND l.estado IS NULL
</code>```

to be specified like this:

```<code>AND b.estado IS NULL, c.estado IS NULL, l.estado IS NULL
</code>```

答:
In a nutshell: no, the second syntax in your question is not supported in any database that I know.

You could, however, use coalesce() to shorten the expression:

```<code>and coalesce(b.estado, c.estado, l.estado) is null
</code>```

coalesce() returns the first non-null value from its argument list. So if it returns null, it means that all of its arguments are null.

Body:
Is it possible to make multiple ANDs into only one? For example, something like this:

AND b.estado IS NULL AND c.estado IS NULL AND l.estado IS NULL

to be specified like this:

AND b.estado IS NULL, c.estado IS NULL, l.estado IS NULL

Body:
In a nutshell: no, the second syntax in your question is not supported in any database that I know.

You could, however, use coalesce() to shorten the expression:

and coalesce(b.estado, c.estado, l.estado) is null

coalesce() returns the first non-null value from its argument list. So if it returns null, it means that all of its arguments are null.


问:
Why does my execve() only works when arguments include /bin/?
execve() only works when /bin/ is a prefix to the first argument

e.g. ./test.out ls finds nothing while ./test.out /bin/ls works

execve(argv[1], args, getenv("PATH"))

答: execve() doesn't search PATH for the executable. You have to use execvp() for that. The p in the name stands for PATH.


问:
Unknow column in a MySQLTrigger execution
I have this trigger with no syntax errors working on my DB:

```<code>DROP TRIGGER IF EXISTS image_demand;
DELIMITER //
CREATE TRIGGER image_demand BEFORE INSERT ON demand_img
FOR EACH ROW
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE val DATE DEFAULT NULL;
    DECLARE minValue CURSOR FOR SELECT min(date_demand) AS RES FROM demand_img;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN minValue;
    read_loop : LOOP
        FETCH minValue INTO val;
        IF done THEN
            LEAVE read_loop;
        END IF;
    END LOOP;
    CLOSE minValue;
    IF minValue IS NOT NULL THEN
        SET NEW.date_demand = val + INTERVAL 1 HOUR;
    END IF;
END //
</code>```

It tries to add 1 hour from the minimum value already setted in the database, to the new register about to insert. But when I try to insert a new image_demand component with an INSERT command, it fails with this error:

```<code>18:16:40    INSERT INTO `database`.`demand_img` (USER_ID_FK, IMG_ID) VALUES (2, 'asdfasdfasdfa')
Error Code: 1054. Unknown column 'minValue' in 'field list' 0.000 sec
</code>```

As you can see, minValue is a variable that comes from the Trigger, so I think the error is from it, but I can't see where is it. Maybe am I setting minValue incorrectly?

Thank you for your help

J.

答:
Ok, I see my mistake. Sorry for bugging you. IF minValue should be IF val

MySQL compiles it without showing any error.

Sorry and thank you.

Body:
I have this trigger with no syntax errors working on my DB:

DROP TRIGGER IF EXISTS image_demand;
DELIMITER //
CREATE TRIGGER image_demand BEFORE INSERT ON demand_img
FOR EACH ROW
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE val DATE DEFAULT NULL;
    DECLARE minValue CURSOR FOR SELECT min(date_demand) AS RES FROM demand_img;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN minValue;
    read_loop : LOOP
        FETCH minValue INTO val;
        IF done THEN
            LEAVE read_loop;
        END IF;
    END LOOP;
    CLOSE minValue;
    IF minValue IS NOT NULL THEN
        SET NEW.date_demand = val + INTERVAL 1 HOUR;
    END IF;
END //

It tries to add 1 hour from the minimum value already setted in the database, to the new register about to insert. But when I try to insert a new image_demand component with an INSERT command, it fails with this error:

18:16:40    INSERT INTO `database`.`demand_img` (USER_ID_FK, IMG_ID) VALUES (2, 'asdfasdfasdfa')
Error Code: 1054. Unknown column 'minValue' in 'field list' 0.000 sec

As you can see, minValue is a variable that comes from the Trigger, so I think the error is from it, but I can't see where is it. Maybe am I setting minValue incorrectly?

Thank you for your help

J.


问:
True but False in recursion
I want to count if there is k-same consecutive number in my array
For example if we want to check if there is is (k=)3 consecutive number the function will return :

```<code>[0,0,1,1,1,3,4,5,4,3] = true
[0,0,1,2,1,3,4,5,4,3] = false
</code>```

I write

def seq(a, n, k):
    if n == 1:
        return 0
    if k <= 1:
        return 1
    return (a[0] == a[1] and seq(a[1:], n-1, k - 1)) or seq(a[1:], n - 1, k)`
```

But when i call (seq(array, len(array), 3)) for [2, 0, 0, 2, -4, -4, 0, 5, 0, 65, 66, 67]
its returning 1 instead of 0

答:
It seems like you are messing up what you have to have as your accumulator. What you should be accumulating is the last thing you saw and how many times you saw it. Where a is equal to the list we are checking, n is the number of times we have seen the element e and k is the number of consecutive elements we have to reach.

```<code>def seq(a, k):
    def seq_acc(a, n, e, k):
        if not a:
            return n == k
        if n == k:
            return True
        if e == a[0]:
            return seq_acc(a[1:], n+1, e, k)
        else:
            return seq_acc(a[1:], 1, a[0], k)
    if not a:
        return False
    else:
        return seq_acc(a[1:], 1, a[0], k)
</code>```

Title: True but False in recursion

Body:
I want to count if there is k-same consecutive number in my array
For example if we want to check if there is is (k=)3 consecutive number the function will return :

[0,0,1,1,1,3,4,5,4,3] = true
[0,0,1,2,1,3,4,5,4,3] = false

I write

def seq(a, n, k):
    if n == 1:
        return 0
    if k <= 1:
        return 1
    return (a[0] == a[1] and seq(a[1:], n-1, k - 1)) or seq(a[1:], n - 1, k)`

But when i call (seq(array, len(array), 3)) for [2, 0, 0, 2, -4, -4, 0, 5, 0, 65, 66, 67]
its returning 1 instead of 0

Body:
It seems like you are messing up what you have to have as your accumulator. What you should be accumulating is the last thing you saw and how many times you saw it. Where a is equal to the list we are checking, n is the number of times we have seen the element e and k is the number of consecutive elements we have to reach.

def seq(a, k):
    def seq_acc(a, n, e, k):
        if not a:
            return n == k
        if n == k:
            return True
        if e == a[0]:
            return seq_acc(a[1:], n+1, e, k)
        else:
            return seq_acc(a[1:], 1, a[0], k)
    if not a:
        return False
    else:
        return seq_acc(a[1:], 1, a[0], k)


问:
How to get the most recent shared AWS RDS snapshot by id?
I have 2 databases on AWS RDS, one for stage and one for production across 2 accounts. I am trying to copy the data in production to stage every x days. My plan was to make a copy of the most recent automatic backup snapshot in production and share it to the stage account before creating the database in stage using the shared snapshot from production. Everything was going right until I ran into what I believe is a bug but it could easily be that I made a mistake.

When I tried to get the most recent, shared, snapshot with an id of abcd in Terraform with data "aws_db_snapshot", I got no results.

```<code>data "aws_db_snapshot" "latest_prod_snapshot" {
  db_instance_identifier = "abcd"
  snapshot_type          = "shared"
  include_shared         = "true"
  most_recent            = "true"
}
</code>```

Then I decided to try out AWS CLI. When I run this...

aws rds describe-db-snapshots --snapshot-type shared --include-shared

... I get this...

```<code>{
    "DBSnapshots": [
        {
            "MasterUsername": "root",
            "LicenseModel": "general-public-license",
            "InstanceCreateTime": "2018-01-13T00:00:00.000Z",
            "Engine": "mysql",
            "VpcId": "vpc-0000000000000000",
            "SourceRegion": "us-east-1",
            "AllocatedStorage": 20,
            "Status": "available",
            "PercentProgress": 100,
            "SourceDBSnapshotIdentifier": "arn:aws:rds:us-east-1:000000000000:snapshot:rds:abcd-2020-01-13-00-00",
            "DBSnapshotIdentifier": "arn:aws:rds:us-east-1:000000000000:snapshot:rds:abcd-2020-01-13-00-00",
            "DBSnapshotArn": "arn:aws:rds:us-east-1:000000000000:snapshot:rds:abcd-2020-01-13-00-00",
            "EngineVersion": "5.6.41",
            "ProcessorFeatures": [],
            "OptionGroupName": "default:mysql-5-6",
            "SnapshotCreateTime": "2020-01-13T00:00:00.000Z",
            "AvailabilityZone": "us-east-1b",
            "StorageType": "gp2",
            "Encrypted": false,
            "IAMDatabaseAuthenticationEnabled": false,
            "DbiResourceId": "db-AAAAAAAAAAAAAAAAAAAAAAAAA",
            "SnapshotType": "shared",
            "Port": 3306,
            "DBInstanceIdentifier": "abcd"
        }
    ]
}
</code>```

... which is what I expected. Looking at the response, I would expect the db instance id to be abcd but when I run this...

aws rds describe-db-snapshots --snapshot-type shared --include-shared --db-instance-identifier abcd

... or this...

aws rds describe-db-snapshots --snapshot-type shared --include-shared --filters Name=db-instance-id,Values=abcd

... I get this...

```<code>{
    "DBSnapshots": []
}
</code>```

... which is not what I would have expected. Is this a bug or am I doing something wrong? I looked through their documentation but I may have missed something.

答:
While we wait for AWS to fix this. Here are some things you can do as workaround:

In the stage account copy the shared snapshot and use the copy instead of the shared.

In Terraform, rollback to an older provider version.

2.27 works for me

```<code>provider "aws" {
  version                 = "2.27.0"
}
</code>```

Body:
I have 2 databases on AWS RDS, one for stage and one for production across 2 accounts. I am trying to copy the data in production to stage every x days. My plan was to make a copy of the most recent automatic backup snapshot in production and share it to the stage account before creating the database in stage using the shared snapshot from production. Everything was going right until I ran into what I believe is a bug but it could easily be that I made a mistake.

When I tried to get the most recent, shared, snapshot with an id of abcd in Terraform with data "aws_db_snapshot", I got no results.

data "aws_db_snapshot" "latest_prod_snapshot" {
  db_instance_identifier = "abcd"
  snapshot_type          = "shared"
  include_shared         = "true"
  most_recent            = "true"
}

Then I decided to try out AWS CLI. When I run this...

aws rds describe-db-snapshots --snapshot-type shared --include-shared

... I get this...

{
    "DBSnapshots": [
        {
            "MasterUsername": "root",
            "LicenseModel": "general-public-license",
            "InstanceCreateTime": "2018-01-13T00:00:00.000Z",
            "Engine": "mysql",
            "VpcId": "vpc-0000000000000000",
            "SourceRegion": "us-east-1",
            "AllocatedStorage": 20,
            "Status": "available",
            "PercentProgress": 100,
            "SourceDBSnapshotIdentifier": "arn:aws:rds:us-east-1:000000000000:snapshot:rds:abcd-2020-01-13-00-00",
            "DBSnapshotIdentifier": "arn:aws:rds:us-east-1:000000000000:snapshot:rds:abcd-2020-01-13-00-00",
            "DBSnapshotArn": "arn:aws:rds:us-east-1:000000000000:snapshot:rds:abcd-2020-01-13-00-00",
            "EngineVersion": "5.6.41",
            "ProcessorFeatures": [],
            "OptionGroupName": "default:mysql-5-6",
            "SnapshotCreateTime": "2020-01-13T00:00:00.000Z",
            "AvailabilityZone": "us-east-1b",
            "StorageType": "gp2",
            "Encrypted": false,
            "IAMDatabaseAuthenticationEnabled": false,
            "DbiResourceId": "db-AAAAAAAAAAAAAAAAAAAAAAAAA",
            "SnapshotType": "shared",
            "Port": 3306,
            "DBInstanceIdentifier": "abcd"
        }
    ]
}

... which is what I expected. Looking at the response, I would expect the db instance id to be abcd but when I run this...

aws rds describe-db-snapshots --snapshot-type shared --include-shared --db-instance-identifier abcd

... or this...

aws rds describe-db-snapshots --snapshot-type shared --include-shared --filters Name=db-instance-id,Values=abcd

... I get this...

{
    "DBSnapshots": []
}

... which is not what I would have expected. Is this a bug or am I doing something wrong? I looked through their documentation but I may have missed something.

Body:
While we wait for AWS to fix this. Here are some things you can do as workaround:

In the stage account copy the shared snapshot and use the copy instead of the shared.

In Terraform, rollback to an older provider version.

2.27 works for me

provider "aws" {
  version                 = "2.27.0"
}


问:
Kivy - Trying to Understand Clock.schedule_interval
I'm new to Kivy, I was doing pong tutorial and everything was going great, I adapted it to 4 players, each paddle has its own color and if the ball hits a paddle it gets the color of it, this way if the ball gets off the screen the last-hitter gets a score point.

I'm running in Ubuntu 14,04, with a virtualenv.

For easier download and checking, all code can be found here: Pong_kivy

What's the problem?

After a game is over once it restarts the ball seems like it's increasing speed everytime, until it crashes, which is not caused by velocity vector, I checked it, hence I think that I'm handling wrong the Clock.Schedule function. I can't seem to find whats wrong with so any help is appreciated.

pong.py file

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
    ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.graphics import *
from kivy.uix.button import Button, Label
from random import randint

class PongPaddle(Widget):
    score = NumericProperty(0)
    orientation = ObjectProperty([0, 0])
    color = ObjectProperty([0,0,0,1])

def bounce_ball(self, ball):
    if self.collide_widget(ball):
        vx, vy = ball.velocity
        ball.color = self.color
        ball.last_hit = int(self.custom_id)
        if self.orientation[0] == 25:
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset
        else:
            offset = (ball.center_x - self.center_x) / (self.width / 2)
            bounced = Vector(vx, -1 * vy)
            vel = bounced * 1.1
            ball.velocity = vel.x + offset, vel.y

class PongBall(Widget):
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    last_hit = 0
    color = ObjectProperty([0,0,0,1])
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)
    player3 = ObjectProperty(None)
    player4 = ObjectProperty(None)
    l = Label()
    btn1 = Button(text='Restart')
    win_game = 1

    def start(self):
        Clock.schedule_interval(self.update, 1.0 / 60.0)

    def stop(self):
        # Stop updating
        Clock.unschedule(self.update)

    def init(self):
        ## Setup players
        self.player1.orientation = [25, 200]
        self.player1.color = [1,0,0,1]
        self.player1.score = 0
        # Player 2
        self.player2.orientation = [25, 200]
        self.player2.color = [0,1,0,1]
        self.player2.score = 0
        # Player 3
        self.player3.orientation = [200, 25]
        self.player3.color = [0,0,1,1]
        self.player3.score = 0
        # Player 4
        self.player4.orientation = [200, 25]
        self.player4.color = [1,1,0,1]
        self.player4.score = 0

    def serve_ball(self):
        # Ball velocity - Add 2 to avoid 0
        vel = (randint(-8,6)+2, randint(-8,6)+2)

        # Setup ball
        self.ball.center = self.center
        self.ball.velocity = vel
        self.ball.last_hit = 0
        self.ball.color = [1,1,1,1]

    def update(self, dt):
        self.ball.move()

        #Bounce out the of paddles - Why do all check? Only can bounce on one any given time
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)
        self.player3.bounce_ball(self.ball)
        self.player4.bounce_ball(self.ball)

        #bounce ball off bottom or top - This is for 2 players game
        # if (self.ball.y < self.y) or (self.ball.top > self.top):
        #     self.ball.velocity_y *= -1

        # Went of any side? - Last hitter gets a goal
        if self.ball.x < self.x or self.ball.x > self.width or self.ball.y < self.y or self.ball.y > self.height:
            if self.ball.last_hit == 1:
                self.player1.score += 1
            elif self.ball.last_hit == 2:
                self.player2.score += 1
            elif self.ball.last_hit == 3:
                self.player3.score += 1
            elif self.ball.last_hit == 4:
                self.player4.score += 1
            self.serve_ball()

        if self.player1.score >= self.win_game:
            self.player_win(1)
        elif self.player2.score >= self.win_game:
            self.player_win(2)
        elif self.player3.score >= self.win_game:
            self.player_win(3)
        elif self.player4.score >= self.win_game:
            self.player_win(4)

    def player_win(self, player_int):
        # Remove Ball and players
        self.clear_widgets()
        # Configure Label and Btn
        self.l.text ='Player ' + str(player_int) + ' Wins!!'
        self.l.top = self.top-50
        self.l.font_size = 50
        self.l.center_x = self.width/2
        self.btn1.bind(on_press=self.restart)
        self.btn1.center_x = self.width/2
        self.btn1.top = self.top/2
        self.add_widget(self.l)
        self.add_widget(self.btn1)
        self.stop()

    def on_touch_move(self, touch):
        if touch.x < self.width / 3 and touch.y > self.height / 6 \
            and touch.y < 5 * self.height/6:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3 and touch.y > self.height / 6 \
            and touch.y < 5 * self.height / 6:
            self.player2.center_y = touch.y
        if touch.y < self.height / 3 and touch.x > self.width / 6 \
            and touch.x < 5 * self.width / 6:
            self.player4.center_x = touch.x
        if touch.y > 2* self.height / 3 and touch.x > self.width / 6 \
            and touch.x < 5 * self.width / 6:
            self.player3.center_x = touch.x

    # Method update  layout
    def update_rect(instance, value):
        instance.rect.pos = instance.pos
        instance.rect.size = instance.size

    def restart(self, instance):
        # Remove btn and labels
        self.clear_widgets()

        # Add what I want
        self.add_widget(self.ball)
        self.add_widget(self.player1)
        self.add_widget(self.player2)
        self.add_widget(self.player3)
        self.add_widget(self.player4)
        self.init()
        self.serve_ball()
        self.start()

class PongApp(App):
    def build(self):
        game = PongGame()
        game.init()
        game.serve_ball()
        game.start()
        return game

if __name__ == '__main__':
    PongApp().run()
</code>```

pong.kv file

```<code>#:kivy 1.0.9

<PongBall>:
    size: 50, 50
    canvas:
        Color:
            rgba: self.color[0], self.color[1], self.color[2], self.color[3]
        Ellipse:
            pos: self.pos
            size: self.size

<PongPaddle>:
    size: root.orientation[0], root.orientation[1]
    canvas:
        Color:
            rgba: self.color[0], self.color[1], self.color[2], self.color[3]
        Rectangle:
            pos:self.pos
            size:self.size

<PongGame>:
    ball: pong_ball
    player1: player_left
    player2: player_right
    player3: player_top
    player4: player_bottom

    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'black.jpg'

    Label:
        font_size: 15
        center_x: root.width / 8
        top: self.height*0.95
        text: "P1: " + str(root.player1.score)
    Label:
        font_size: 15
        center_x: root.width / 8
        top: self.height*0.80
        text: "P2: " + str(root.player2.score)
    Label:
        font_size: 15
        center_x: root.width / 5
        top: self.height*0.95
        text: "P3: " + str(root.player3.score)
    Label:
        font_size: 15
        center_x: root.width / 5
        top: self.height*0.80
        text: "P4: " + str(root.player4.score)

    PongBall:
        id: pong_ball
        center: self.parent.center

    PongPaddle:
        id: player_left
        custom_id: "1"
        x: root.x
        center_y: root.center_y

    PongPaddle:
        id: player_right
        custom_id: "2"
        x: root.width-self.width
        center_y: root.center_y

    PongPaddle:
        id: player_top
        custom_id: "3"
        y: root.height - self.height
        center_x: root.center_x

    PongPaddle:
        id: player_bottom
        custom_id: "4"
        y: root.y
        center_x: root.center_x
</code>```

答:
Refer to section 9.2.3 Trigger Events in Kivy Documentation

Sometimes you may want to schedule a function to be called only once for the next frame, preventing
duplicate calls. You might be tempted to achieve that like so:

EXAMPLE CODE:

```<code>//First, schedule once.

event = Clock.schedule_once(my_callback, 0)

//Then, in another place you will have to unschedule first to avoid duplicate call. Then you can schedule again.

Clock.unschedule(event)

event = Clock.schedule_once(my_callback, 0)
</code>```

This way of programming a trigger is expensive, since you’ll always call unschedule, even if the event has already completed. In addition, a new event is created every time. Use a trigger instead:

```<code>trigger = Clock.create_trigger(my_callback)
//later
trigger()
</code>```

Each time you call trigger(), it will schedule a single call of your callback. If it was already scheduled, it will not be rescheduled.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to Kivy, I was doing pong tutorial and everything was going great, I adapted it to 4 players, each paddle has its own color and if the ball hits a paddle it gets the color of it, this way if the ball gets off the screen the last-hitter gets a score point.

I'm running in Ubuntu 14,04, with a virtualenv.

For easier download and checking, all code can be found here: Pong_kivy

What's the problem?

After a game is over once it restarts the ball seems like it's increasing speed everytime, until it crashes, which is not caused by velocity vector, I checked it, hence I think that I'm handling wrong the Clock.Schedule function. I can't seem to find whats wrong with so any help is appreciated.

pong.py file

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
    ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.graphics import *
from kivy.uix.button import Button, Label
from random import randint

class PongPaddle(Widget):
    score = NumericProperty(0)
    orientation = ObjectProperty([0, 0])
    color = ObjectProperty([0,0,0,1])

def bounce_ball(self, ball):
    if self.collide_widget(ball):
        vx, vy = ball.velocity
        ball.color = self.color
        ball.last_hit = int(self.custom_id)
        if self.orientation[0] == 25:
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset
        else:
            offset = (ball.center_x - self.center_x) / (self.width / 2)
            bounced = Vector(vx, -1 * vy)
            vel = bounced * 1.1
            ball.velocity = vel.x + offset, vel.y

class PongBall(Widget):
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    last_hit = 0
    color = ObjectProperty([0,0,0,1])
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)
    player3 = ObjectProperty(None)
    player4 = ObjectProperty(None)
    l = Label()
    btn1 = Button(text='Restart')
    win_game = 1

    def start(self):
        Clock.schedule_interval(self.update, 1.0 / 60.0)

    def stop(self):
        # Stop updating
        Clock.unschedule(self.update)

    def init(self):
        ## Setup players
        self.player1.orientation = [25, 200]
        self.player1.color = [1,0,0,1]
        self.player1.score = 0
        # Player 2
        self.player2.orientation = [25, 200]
        self.player2.color = [0,1,0,1]
        self.player2.score = 0
        # Player 3
        self.player3.orientation = [200, 25]
        self.player3.color = [0,0,1,1]
        self.player3.score = 0
        # Player 4
        self.player4.orientation = [200, 25]
        self.player4.color = [1,1,0,1]
        self.player4.score = 0

    def serve_ball(self):
        # Ball velocity - Add 2 to avoid 0
        vel = (randint(-8,6)+2, randint(-8,6)+2)

        # Setup ball
        self.ball.center = self.center
        self.ball.velocity = vel
        self.ball.last_hit = 0
        self.ball.color = [1,1,1,1]

    def update(self, dt):
        self.ball.move()

        #Bounce out the of paddles - Why do all check? Only can bounce on one any given time
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)
        self.player3.bounce_ball(self.ball)
        self.player4.bounce_ball(self.ball)

        #bounce ball off bottom or top - This is for 2 players game
        # if (self.ball.y < self.y) or (self.ball.top > self.top):
        #     self.ball.velocity_y *= -1

        # Went of any side? - Last hitter gets a goal
        if self.ball.x < self.x or self.ball.x > self.width or self.ball.y < self.y or self.ball.y > self.height:
            if self.ball.last_hit == 1:
                self.player1.score += 1
            elif self.ball.last_hit == 2:
                self.player2.score += 1
            elif self.ball.last_hit == 3:
                self.player3.score += 1
            elif self.ball.last_hit == 4:
                self.player4.score += 1
            self.serve_ball()

        if self.player1.score >= self.win_game:
            self.player_win(1)
        elif self.player2.score >= self.win_game:
            self.player_win(2)
        elif self.player3.score >= self.win_game:
            self.player_win(3)
        elif self.player4.score >= self.win_game:
            self.player_win(4)

    def player_win(self, player_int):
        # Remove Ball and players
        self.clear_widgets()
        # Configure Label and Btn
        self.l.text ='Player ' + str(player_int) + ' Wins!!'
        self.l.top = self.top-50
        self.l.font_size = 50
        self.l.center_x = self.width/2
        self.btn1.bind(on_press=self.restart)
        self.btn1.center_x = self.width/2
        self.btn1.top = self.top/2
        self.add_widget(self.l)
        self.add_widget(self.btn1)
        self.stop()

    def on_touch_move(self, touch):
        if touch.x < self.width / 3 and touch.y > self.height / 6 \
            and touch.y < 5 * self.height/6:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3 and touch.y > self.height / 6 \
            and touch.y < 5 * self.height / 6:
            self.player2.center_y = touch.y
        if touch.y < self.height / 3 and touch.x > self.width / 6 \
            and touch.x < 5 * self.width / 6:
            self.player4.center_x = touch.x
        if touch.y > 2* self.height / 3 and touch.x > self.width / 6 \
            and touch.x < 5 * self.width / 6:
            self.player3.center_x = touch.x

    # Method update  layout
    def update_rect(instance, value):
        instance.rect.pos = instance.pos
        instance.rect.size = instance.size

    def restart(self, instance):
        # Remove btn and labels
        self.clear_widgets()

        # Add what I want
        self.add_widget(self.ball)
        self.add_widget(self.player1)
        self.add_widget(self.player2)
        self.add_widget(self.player3)
        self.add_widget(self.player4)
        self.init()
        self.serve_ball()
        self.start()

class PongApp(App):
    def build(self):
        game = PongGame()
        game.init()
        game.serve_ball()
        game.start()
        return game

if __name__ == '__main__':
    PongApp().run()

pong.kv file

#:kivy 1.0.9

<PongBall>:
    size: 50, 50
    canvas:
        Color:
            rgba: self.color[0], self.color[1], self.color[2], self.color[3]
        Ellipse:
            pos: self.pos
            size: self.size

<PongPaddle>:
    size: root.orientation[0], root.orientation[1]
    canvas:
        Color:
            rgba: self.color[0], self.color[1], self.color[2], self.color[3]
        Rectangle:
            pos:self.pos
            size:self.size

<PongGame>:
    ball: pong_ball
    player1: player_left
    player2: player_right
    player3: player_top
    player4: player_bottom

    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'black.jpg'

    Label:
        font_size: 15
        center_x: root.width / 8
        top: self.height*0.95
        text: "P1: " + str(root.player1.score)
    Label:
        font_size: 15
        center_x: root.width / 8
        top: self.height*0.80
        text: "P2: " + str(root.player2.score)
    Label:
        font_size: 15
        center_x: root.width / 5
        top: self.height*0.95
        text: "P3: " + str(root.player3.score)
    Label:
        font_size: 15
        center_x: root.width / 5
        top: self.height*0.80
        text: "P4: " + str(root.player4.score)

    PongBall:
        id: pong_ball
        center: self.parent.center

    PongPaddle:
        id: player_left
        custom_id: "1"
        x: root.x
        center_y: root.center_y

    PongPaddle:
        id: player_right
        custom_id: "2"
        x: root.width-self.width
        center_y: root.center_y

    PongPaddle:
        id: player_top
        custom_id: "3"
        y: root.height - self.height
        center_x: root.center_x

    PongPaddle:
        id: player_bottom
        custom_id: "4"
        y: root.y
        center_x: root.center_x

Body:
Refer to section 9.2.3 Trigger Events in Kivy Documentation

Sometimes you may want to schedule a function to be called only once for the next frame, preventing
duplicate calls. You might be tempted to achieve that like so:

EXAMPLE CODE:

//First, schedule once.

event = Clock.schedule_once(my_callback, 0)

//Then, in another place you will have to unschedule first to avoid duplicate call. Then you can schedule again.

Clock.unschedule(event)

event = Clock.schedule_once(my_callback, 0)

This way of programming a trigger is expensive, since you’ll always call unschedule, even if the event has already completed. In addition, a new event is created every time. Use a trigger instead:

trigger = Clock.create_trigger(my_callback)
//later
trigger()

Each time you call trigger(), it will schedule a single call of your callback. If it was already scheduled, it will not be rescheduled.


问:
Load Blazorise DataGrid DetailRow from server
The "Blazorise DataGrid extension" supports Master/Detail. How does one load detail data, say from a server, when a user click on its parent in master table?

In example of DataGrid extension I can use "selectedEmployee" property to find out what master row selected but the main problem is "how to reload child data from server when master row clicked?"

```<code><DataGrid TItem="Employee"
  Data="@dataModels"
  EditMode="@editMode"
  Editable="@editable"
  Sortable="@sortable"
  Filterable="@filterable"
  ShowPager="@showPager"
  RowInserted="@OnRowInserted"
  RowUpdated="@OnRowUpdated"
  RowRemoved="@OnRowRemoved"
  UseInternalEditing="true"
  @bind-SelectedRow="@selectedEmployee"
  DetailRowTrigger="@((item)=>item.Salaries?.Count > 0 && item.Id == selectedEmployee?.Id)"
  IsStriped="true"
  IsBordered="true"
  IsHoverable="true">
</code>```

答:
You need to use event ReadData along with TotalItems property on your sub-datagrid. Sample usage can be found on Blazorise documentation.

```<code><DataGrid TItem="YourSubModel"
    Data="@yourSubModelList"
    ReadData="@OnReadData"
    TotalItems="@totalSubModels">
</DataGrid>
</code>```

Body:
The "Blazorise DataGrid extension" supports Master/Detail. How does one load detail data, say from a server, when a user click on its parent in master table?

In example of DataGrid extension I can use "selectedEmployee" property to find out what master row selected but the main problem is "how to reload child data from server when master row clicked?"

<DataGrid TItem="Employee"
  Data="@dataModels"
  EditMode="@editMode"
  Editable="@editable"
  Sortable="@sortable"
  Filterable="@filterable"
  ShowPager="@showPager"
  RowInserted="@OnRowInserted"
  RowUpdated="@OnRowUpdated"
  RowRemoved="@OnRowRemoved"
  UseInternalEditing="true"
  @bind-SelectedRow="@selectedEmployee"
  DetailRowTrigger="@((item)=>item.Salaries?.Count > 0 && item.Id == selectedEmployee?.Id)"
  IsStriped="true"
  IsBordered="true"
  IsHoverable="true">

Body:
You need to use event ReadData along with TotalItems property on your sub-datagrid. Sample usage can be found on Blazorise documentation.

<DataGrid TItem="YourSubModel"
    Data="@yourSubModelList"
    ReadData="@OnReadData"
    TotalItems="@totalSubModels">
</DataGrid>


问:
FusionAuth incomplete reindex with AWS Elasticsearch
I am migrating from a self-hosted Elasticsearch FusionAuth search to an AWS Elasticsearch Service solution.

I have a new FusionAuth app EC2 instance reading from the in-use database that is configured to use the new Elasticsearch service.

On triggering a reindex from the new app instance I see that only around 60k or 62.5k documents are being written to the new index when I am expecting roughly 6mil.

I see no errors from AWS's Elasticsearch Service and in the app's logs I can see: (endpoint intentionally omitted)

```<code>Feb 13, 2020 10:18:46.116 AM INFO  io.fusionauth.api.service.search.ElasticSearchClientProvider - Connecting to FusionAuth Search Engine at [https://vpc-<<omitted>>.eu-west-1.es.amazonaws.com]
13-Feb-2020 11:19:55.176 INFO [http-nio-9011-exec-3] org.apache.coyote.http11.Http11Processor.service Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
        java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
                at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:430)
                at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:684)
                at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
                at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
                at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
"/usr/local/fusionauth/logs/fusionauth-app.log" [readonly] 43708L, 4308629C                                                                                42183,1       96%
        at io.fusionauth.api.service.search.client.domain.documents.IndexUser.<init>(IndexUser.java:79)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.lambda$index$1(ElasticsearchSearchEngine.java:140)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.index(ElasticsearchSearchEngine.java:140)
        at io.fusionauth.api.service.user.ReindexRunner$ReindexWorker.run(ReindexRunner.java:101)
        at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-14" java.lang.NullPointerException
        at io.fusionauth.api.service.search.client.domain.documents.IndexUser.<init>(IndexUser.java:79)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.lambda$index$1(ElasticsearchSearchEngine.java:140)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.index(ElasticsearchSearchEngine.java:140)
        at io.fusionauth.api.service.user.ReindexRunner$ReindexWorker.run(ReindexRunner.java:101)
        at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-13" java.lang.NullPointerException
Exception in thread "Thread-11" java.lang.NullPointerException
Exception in thread "Thread-12" java.lang.NullPointerException
Feb 18, 2020 10:23:29.064 AM INFO  io.fusionauth.api.service.user.ReindexRunner - Reindex completed in [86797] ms or [86] seconds.
</code>```

Although there are some exceptions there is also an "Reindex completed" INFO log at the end.

Not knowing the ins-and-outs of Elasticsearch I'm also not sure where to start in investigating a NullPointerException.

答:
It looks like the re-index operation is taking an exception which is likely the cause of the truncated index.

```<code>Exception in thread "Thread-14" java.lang.NullPointerException
        at io.fusionauth.api.service.search.client.domain.documents.IndexUser.<init>(IndexUser.java:79)

</code>```

This code makes an assumption that you have a username or email address. This should be enforced by the FusionAuth APIs. But in this case, for this exception to occur the email and username are both NULL.

How did you get users into the db, using the Import API, User API, or something else?

In theory you should find at least one user with a NULL value for the email and username.

This query - or similar - should find the offending user, then we need to identify how this user was added to FusionAuth.

```<code>SELECT email, username from identities WHERE email IS NULL OR username IS NULL
</code>```

Body:
I am migrating from a self-hosted Elasticsearch FusionAuth search to an AWS Elasticsearch Service solution.

I have a new FusionAuth app EC2 instance reading from the in-use database that is configured to use the new Elasticsearch service.

On triggering a reindex from the new app instance I see that only around 60k or 62.5k documents are being written to the new index when I am expecting roughly 6mil.

I see no errors from AWS's Elasticsearch Service and in the app's logs I can see: (endpoint intentionally omitted)

Feb 13, 2020 10:18:46.116 AM INFO  io.fusionauth.api.service.search.ElasticSearchClientProvider - Connecting to FusionAuth Search Engine at [https://vpc-<<omitted>>.eu-west-1.es.amazonaws.com]
13-Feb-2020 11:19:55.176 INFO [http-nio-9011-exec-3] org.apache.coyote.http11.Http11Processor.service Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
        java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
                at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:430)
                at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:684)
                at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
                at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
                at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
"/usr/local/fusionauth/logs/fusionauth-app.log" [readonly] 43708L, 4308629C                                                                                42183,1       96%
        at io.fusionauth.api.service.search.client.domain.documents.IndexUser.<init>(IndexUser.java:79)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.lambda$index$1(ElasticsearchSearchEngine.java:140)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.index(ElasticsearchSearchEngine.java:140)
        at io.fusionauth.api.service.user.ReindexRunner$ReindexWorker.run(ReindexRunner.java:101)
        at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-14" java.lang.NullPointerException
        at io.fusionauth.api.service.search.client.domain.documents.IndexUser.<init>(IndexUser.java:79)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.lambda$index$1(ElasticsearchSearchEngine.java:140)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at io.fusionauth.api.service.search.ElasticsearchSearchEngine.index(ElasticsearchSearchEngine.java:140)
        at io.fusionauth.api.service.user.ReindexRunner$ReindexWorker.run(ReindexRunner.java:101)
        at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-13" java.lang.NullPointerException
Exception in thread "Thread-11" java.lang.NullPointerException
Exception in thread "Thread-12" java.lang.NullPointerException
Feb 18, 2020 10:23:29.064 AM INFO  io.fusionauth.api.service.user.ReindexRunner - Reindex completed in [86797] ms or [86] seconds.

Although there are some exceptions there is also an "Reindex completed" INFO log at the end.

Not knowing the ins-and-outs of Elasticsearch I'm also not sure where to start in investigating a NullPointerException.

Body:
It looks like the re-index operation is taking an exception which is likely the cause of the truncated index.

Exception in thread "Thread-14" java.lang.NullPointerException
        at io.fusionauth.api.service.search.client.domain.documents.IndexUser.<init>(IndexUser.java:79)

This code makes an assumption that you have a username or email address. This should be enforced by the FusionAuth APIs. But in this case, for this exception to occur the email and username are both NULL.

How did you get users into the db, using the Import API, User API, or something else?

In theory you should find at least one user with a NULL value for the email and username.

This query - or similar - should find the offending user, then we need to identify how this user was added to FusionAuth.

SELECT email, username from identities WHERE email IS NULL OR username IS NULL


问:
Exporting Colors In React using TypeScript
Hey so I am using React with Typescript, and I have created a colors library to store all of our colors so they can be callable by importing LibraryColors and then doing LibraryColors.orange.primary for example. I want this to be easy to use for my team and so I want to give them intellisense when using it. I believe that is possible with an interface but I have no idea what that interface would look like.

```<code>interface ILibraryColors{

}
const LibraryColors: ILibraryColors = {
    black: {
        primary: "#000000",
    },
    green: {
        light: {
            60: "#40C0C0",
        },
        primary: "#00AEA9",
        dark: {
            40: "#00867C",
        }
    },
    grey: {
        light: {
            80: "#fafafa",
            70: "#dddddd",
            60: "#C4C7C5",
        },
        primary: "#707373",
        dark: {
            40: "#353735"
        }
    },
    orange: {
        light: {
            60: "#FFBB11",
        },
        primary: "#FAA21B",
        dark: {
            40: "#F58220"
        }
    },
    red: {
        light: {
            60: "F15B5D",
        },
        primary: "#E63E51",
        dark: {
            40: "#BC3A4B",
        }
    },
    white: {
        primary: "#ffffff",
    },
    pink: {
        primary: "#f434ed",
    },
    purple: {
        primary: "#1E4286",
    },
    blue: {
        light: {
            60: "#6BC3E7",
        },
        primary: "#06A7E0",
        dark: {
            40: "#005DA6",
        }
    }
}
</code>```

Any help is greatly appreciated, thank you! Also I know I could forget the primary, dark, and light and simply do 0-100 on the colors, but I think it is easier to remember which way gets lighter and darker this way.

答:
```<code>interface aColor {
  [key: number]: string;
}

interface oColorVariant {
  primary: string;
  light?: aColor;
  dark?: aColor;
}

interface ILibraryColors{
  [key: string]: oColorVariant;
}
</code>```

Body:
Hey so I am using React with Typescript, and I have created a colors library to store all of our colors so they can be callable by importing LibraryColors and then doing LibraryColors.orange.primary for example. I want this to be easy to use for my team and so I want to give them intellisense when using it. I believe that is possible with an interface but I have no idea what that interface would look like.

interface ILibraryColors{

}
const LibraryColors: ILibraryColors = {
    black: {
        primary: "#000000",
    },
    green: {
        light: {
            60: "#40C0C0",
        },
        primary: "#00AEA9",
        dark: {
            40: "#00867C",
        }
    },
    grey: {
        light: {
            80: "#fafafa",
            70: "#dddddd",
            60: "#C4C7C5",
        },
        primary: "#707373",
        dark: {
            40: "#353735"
        }
    },
    orange: {
        light: {
            60: "#FFBB11",
        },
        primary: "#FAA21B",
        dark: {
            40: "#F58220"
        }
    },
    red: {
        light: {
            60: "F15B5D",
        },
        primary: "#E63E51",
        dark: {
            40: "#BC3A4B",
        }
    },
    white: {
        primary: "#ffffff",
    },
    pink: {
        primary: "#f434ed",
    },
    purple: {
        primary: "#1E4286",
    },
    blue: {
        light: {
            60: "#6BC3E7",
        },
        primary: "#06A7E0",
        dark: {
            40: "#005DA6",
        }
    }
}

Any help is greatly appreciated, thank you! Also I know I could forget the primary, dark, and light and simply do 0-100 on the colors, but I think it is easier to remember which way gets lighter and darker this way.


问:
Is HTML5 backwards compatible with XHTML?
Short question: Can I change the DOCTYPE of my existing XHTML 1.0 website to HTML5? Will this cause any problems?

Long story:

We've got a website written in ASP.NET webforms. Since it's pretty old, the default DOCTYPE is set to XHTML (default for Visual Studio) and all the controls render XHTML as well. Not extremely valid, but we've had no problems under any browsers so far.

That is, until recently we noticed some odd behavior on different machines under IE. Turns out that IE by default renders intranet websites in "compatibility mode", which breaks things down.

Now, I've got two choices. I can either add:

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge" >
</code>```

Or I can add

```<code><!DOCTYPE html>
</code>```

I'd prefer the DOCTYPE route, since it would open the doors for a lot of neat HTML5 features. However I wonder if it won't have incompatibility problems with our existing XHTML layout.

答:
First up, IE does indeed render intranet sites in compatibility mode by default. However, it is a config setting and can be switched off: if possible, I'd suggest that your first solution would simply be to switch off this setting on all the machines on your network. (whether this is a viable solution will depend on the size of your network, your group policies, and what other intranet sites would be affected)

Now to answer your question.

The HTML5 doctype can be specified on any site that you want to render in standards mode. If you're already using XHTML, the only effect for you will be that the browser will no longer rigidly enforce strict XHTML compliance. You are perfectly entitled to continue using XHTML code, but it won't be enforced.

The HTML5 doctype was specifically chosen because it works with existing browsers, including older versions of IE. You should be able to put it onto any page, and it should just work.

What it won't do is have any effect at all on IE going into compatibility mode. Nor will any other doctype. The X-UA-Compatible solution you mentioned is the solution to this (unless you can set the config setting I mentioned earlier), and is un-related to the doctype - you'll still need it even if you use the HTML5 doctype.

Body:
Short question: Can I change the DOCTYPE of my existing XHTML 1.0 website to HTML5? Will this cause any problems?

Long story:

We've got a website written in ASP.NET webforms. Since it's pretty old, the default DOCTYPE is set to XHTML (default for Visual Studio) and all the controls render XHTML as well. Not extremely valid, but we've had no problems under any browsers so far.

That is, until recently we noticed some odd behavior on different machines under IE. Turns out that IE by default renders intranet websites in "compatibility mode", which breaks things down.

Now, I've got two choices. I can either add:

<meta http-equiv="X-UA-Compatible" content="IE=edge" >

Or I can add

<!DOCTYPE html>

I'd prefer the DOCTYPE route, since it would open the doors for a lot of neat HTML5 features. However I wonder if it won't have incompatibility problems with our existing XHTML layout.


问:
Why Angular evaluates first route only?
I have the following routes which all have the same path. The route is activated based on logic in the canLoad but Angular evaluates the first route with data A only and does not go through second if the first fails. I tested the logic in the canLoad and there is nothing wrong there. It returns true and false.

```<code>const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        data: {provider: 'A'},
        loadChildren: () => import('./xx/auth.module').then(m => m.AuthModule),
      },
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        loadChildren: () => import('./x/auth.module').then(m => m.AuthModule),
      }
    ]
  }
];
</code>```

CanLoad:

```<code>export class AuthGuardProviderService implements CanLoad {

  constructor() {
  }

  canLoad(route: Route): boolean {
    const data = route.data.provider;
    return this.getRoute(data);
  }

  private getRoute(data): boolean {
    const paths = location.href.split('/');
    if (data === 'A') {
      return true;
    } else if (!data) {
      return true;
    }
  }
}
</code>```

Updated question using UrlMatcher:

what you're trying to accomplish with this implementation

User case: I have multiple modules and load a module based on URL. For instance:
User A hits: localhost/a and the module loads.

```<code>path: '',
loadChildren: () => import('./a/auth.module').then(m => m.AuthModule)
</code>```

And if User B hits: localhost/b I want to load:

```<code>path: '',
loadChildren: () => import('./b/auth.module').then(m => m.AuthModule)
</code>```

I can use UrlMatcher but this works only for first route.

```<code>const matcher = (url: UrlSegment[], providerParam) => {
  const paths = location.href.split('/');
  if ((paths[3] === '' || paths[3] === 'auth') && providerParam === 'win') {
    return {consumed: url};
  } else if (paths[3] !== '') {
    const provider = providers.find(p => paths[3].toLowerCase() === p.shortName);
    return provider && provider.shortName === providerParam ? {consumed: url} : null;
  }
  return null;
};
</code>```

And the lazy load module has:

```<code>const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        component: NbLoginComponent,
      },
      {
        path: 'sign-in',
        component: NbLoginComponent,
      },
      {
        path: 'sign-up',
        component: NbRegisterComponent,
      }
    ],
  },
];
</code>```

Now the problem with this approach is that it always loads sign-in component. It always hits path: '' not going to other paths like auth/sign-up

It might be worth to mention that if user hits localhost/a I am setting a as baseHref, therefore, I cannot use this as a path. It would be straight forward if I don't set it as baseHref. The a or b path is not part of the route.

It would also help provide more context if we could see your guard
  implementation

I also tried using guard but that is not helpful either since all paths are same '' empty string, and Angular routes matches the first one and does not evaluate guard on the rest.

what data you want to associate with the first route and how you're
  planning to use it

The purpose of the data is just to know which route is being evaluated.

答:
With issues like this, I always find it helpful to enable route tracing so I can see what the Angular router is doing by watching browser console. More information can never hurt.

```<code>imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only!!!
    )
]
</code>```

The Angular Router iterates over the routes array comparing the window.location.href value with the path variable for each of your routes. Once it finds a match, it loads the component or module associated with that path. As you've seen, it does not continue iterating over the routes array looking for other possible matches. If it did, the Angular Router would then have to determine what route configuration wins, which would likely be too implementation-specific to handle in a generic way at the framework level.

Thankfully, the Angular team does provide an API called the UrlMatcher that allows the developer to make that decision. That's an option if you cannot change the route setup for some reason.

In my opinion, we should always avoid changing the default behavior of a framework if at all possible. At a high level, I would recommend using two different route paths and implementing logic in your guard to check for data A. If it exists and it is what your app expects, load the module in the first route; otherwise, redirect to the second route.

We could provide a more specific solution if we knew:

what data you want to associate with the first route and how you're planning to use it

what you're trying to accomplish with this implementation (Something
like: when a user navigates to my app, I want to check to see if
they're authenticated. If they are, they proceed with the first
route; otherwise, they are redirected to the second route to kick off
the authentication process)

It would also help provide more context if we could see your guard implementation

If you don't find any of this helpful so far and you're unable to provide more information, try taking a look at this post => The Three Pillars of the Angular Router — Router States and URL Matching. It goes more into depth about how the router works and how it handles things like Url segments.

Hope this helps!

Title: Why Angular evaluates first route only?

Body:
I have the following routes which all have the same path. The route is activated based on logic in the canLoad but Angular evaluates the first route with data A only and does not go through second if the first fails. I tested the logic in the canLoad and there is nothing wrong there. It returns true and false.

const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        data: {provider: 'A'},
        loadChildren: () => import('./xx/auth.module').then(m => m.AuthModule),
      },
      {
        path: '',
        canLoad: [AuthGuardProviderService],
        loadChildren: () => import('./x/auth.module').then(m => m.AuthModule),
      }
    ]
  }
];

CanLoad:

export class AuthGuardProviderService implements CanLoad {

  constructor() {
  }

  canLoad(route: Route): boolean {
    const data = route.data.provider;
    return this.getRoute(data);
  }

  private getRoute(data): boolean {
    const paths = location.href.split('/');
    if (data === 'A') {
      return true;
    } else if (!data) {
      return true;
    }
  }
}

Updated question using UrlMatcher:

what you're trying to accomplish with this implementation

User case: I have multiple modules and load a module based on URL. For instance:
User A hits: localhost/a and the module loads.

path: '',
loadChildren: () => import('./a/auth.module').then(m => m.AuthModule)

And if User B hits: localhost/b I want to load:

path: '',
loadChildren: () => import('./b/auth.module').then(m => m.AuthModule)

I can use UrlMatcher but this works only for first route.

const matcher = (url: UrlSegment[], providerParam) => {
  const paths = location.href.split('/');
  if ((paths[3] === '' || paths[3] === 'auth') && providerParam === 'win') {
    return {consumed: url};
  } else if (paths[3] !== '') {
    const provider = providers.find(p => paths[3].toLowerCase() === p.shortName);
    return provider && provider.shortName === providerParam ? {consumed: url} : null;
  }
  return null;
};

And the lazy load module has:

const routes: Routes = [
  {
    path: '',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        component: NbLoginComponent,
      },
      {
        path: 'sign-in',
        component: NbLoginComponent,
      },
      {
        path: 'sign-up',
        component: NbRegisterComponent,
      }
    ],
  },
];

Now the problem with this approach is that it always loads sign-in component. It always hits path: '' not going to other paths like auth/sign-up

It might be worth to mention that if user hits localhost/a I am setting a as baseHref, therefore, I cannot use this as a path. It would be straight forward if I don't set it as baseHref. The a or b path is not part of the route.

It would also help provide more context if we could see your guard
  implementation

I also tried using guard but that is not helpful either since all paths are same '' empty string, and Angular routes matches the first one and does not evaluate guard on the rest.

what data you want to associate with the first route and how you're
  planning to use it

The purpose of the data is just to know which route is being evaluated.

Body:
With issues like this, I always find it helpful to enable route tracing so I can see what the Angular router is doing by watching browser console. More information can never hurt.

imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only!!!
    )
]

The Angular Router iterates over the routes array comparing the window.location.href value with the path variable for each of your routes. Once it finds a match, it loads the component or module associated with that path. As you've seen, it does not continue iterating over the routes array looking for other possible matches. If it did, the Angular Router would then have to determine what route configuration wins, which would likely be too implementation-specific to handle in a generic way at the framework level.

Thankfully, the Angular team does provide an API called the UrlMatcher that allows the developer to make that decision. That's an option if you cannot change the route setup for some reason.

In my opinion, we should always avoid changing the default behavior of a framework if at all possible. At a high level, I would recommend using two different route paths and implementing logic in your guard to check for data A. If it exists and it is what your app expects, load the module in the first route; otherwise, redirect to the second route.

We could provide a more specific solution if we knew:

what data you want to associate with the first route and how you're planning to use it

what you're trying to accomplish with this implementation (Something
like: when a user navigates to my app, I want to check to see if
they're authenticated. If they are, they proceed with the first
route; otherwise, they are redirected to the second route to kick off
the authentication process)

It would also help provide more context if we could see your guard implementation

If you don't find any of this helpful so far and you're unable to provide more information, try taking a look at this post => The Three Pillars of the Angular Router — Router States and URL Matching. It goes more into depth about how the router works and how it handles things like Url segments.

Hope this helps!


问:
Rails doesn't allow to create new enum - instance method already defined by another enum
Trying to add enum to User class:

```<code>enum vehicle: { car: 1, bus: 2, other: 3 }, _prefix: true
</code>```

and rails throws an error

You tried to define an enum named "vehicle" on the model "Spree::User", but this will generate an instance method "vehicle_car?", which is already defined by another enum.

I had tried with another name, suffix and prefix options, and made ack in gems folder. I suppose that can be Zeitwerk problem but I don't have idea how to fix that.

Working on Rails version: 6

答: That could happen if you have a method or column called vehicle_car, because enum method will try to create a helper for you with that name. Is that the case?

Body:
Trying to add enum to User class:

enum vehicle: { car: 1, bus: 2, other: 3 }, _prefix: true

and rails throws an error

You tried to define an enum named "vehicle" on the model "Spree::User", but this will generate an instance method "vehicle_car?", which is already defined by another enum.

I had tried with another name, suffix and prefix options, and made ack in gems folder. I suppose that can be Zeitwerk problem but I don't have idea how to fix that.

Working on Rails version: 6


问:
taking random sample of text chunks python
I'm trying to take random samples of length k from each line in a string of text to create a list of text chunks, but I keep getting a type error even though I can print out a bunch of random numbers that appear in a list. the int() function doesn't help in this case. Am I thinking about this all wrong? Does the random package have a better implementation? I know this is a really quick fix, but I guess I just don't know enough about data types to implement the right solution:

```<code>text = '''blahblahblah
blahblahblah
blahblahblah'''

import random
def randomtext(Text,k):
    chunks = []
    textspl = text.split('\n')
    tlen = len(textspl[0])-k
    for i in range(len(text)):
        samp = random.sample(tlen,1)
        chunks.append(text[i][samp:samp+k])
    return chunks

randomtext(text,3)
TypeError: Population must be a sequence or set.  For dicts, use list(d)
</code>```

答:
```<code>def randomtext(text,k):
    chunks = []
    for line in text.splitlines():
        position = random.randint(0, len(line)-k)
        chunks.append(line[position:position+k])
    return chunks
</code>```

Body:
I'm trying to take random samples of length k from each line in a string of text to create a list of text chunks, but I keep getting a type error even though I can print out a bunch of random numbers that appear in a list. the int() function doesn't help in this case. Am I thinking about this all wrong? Does the random package have a better implementation? I know this is a really quick fix, but I guess I just don't know enough about data types to implement the right solution:

text = '''blahblahblah
blahblahblah
blahblahblah'''

import random
def randomtext(Text,k):
    chunks = []
    textspl = text.split('\n')
    tlen = len(textspl[0])-k
    for i in range(len(text)):
        samp = random.sample(tlen,1)
        chunks.append(text[i][samp:samp+k])
    return chunks

randomtext(text,3)
TypeError: Population must be a sequence or set.  For dicts, use list(d)


问:
Why is my sort algorithm changing the array values?
This is a simple bubble sort algorithm, part of my larger program, intended to sort an array of doubles. I previously tried sorting the same values with merge sort but I got the same output. I really fail to notice what I am missing.Can someone please point it out to me
Thanks in advance!</p>

```<code>#include<iostream>
#include<iomanip>

using namespace std;

int const POINTS = 5;
double dataPoints[POINTS] = { 0.1, 0.5, 0.6, 0.2, 0.8 };

void sort(double dataPoints[])
{
    int i, j, flag = 1;
    int temp;
    for (i = 1; (i <= POINTS) && flag; i++)
    {
        flag = 0;
        for (j = 0; j < (POINTS - 1); j++)
        {
            if (dataPoints[j + 1] > dataPoints[j])
            {
                temp = dataPoints[j];
                dataPoints[j] = dataPoints[j + 1];
                dataPoints[j + 1] = temp;
                flag = 1;
            }
        }
    }

}

int main()
{

    sort(dataPoints);

    for (int i = 0; i < POINTS; i++)
    {
        cout << dataPoints[i] << " ";
    }

}
</code>```

```<code>Output:

0.8 0 0 0 0
</code>```

答:
You swap double, with temporary of type int.

Use instead:

```<code>double temp;
</code>```

or better auto:

```<code>const auto temp = dataPoints[j];
dataPoints[j] = dataPoints[j + 1];
dataPoints[j + 1] = temp;
</code>```

or even better, use std::swap:

```<code>std::swap(dataPoints[j], dataPoints[j + 1]);
</code>```

If allowed, you can even use:

```<code>std::sort(std::begin(dataPoints), std::end(dataPoints), std::greater<>{});
</code>```

Body:
This is a simple bubble sort algorithm, part of my larger program, intended to sort an array of doubles. I previously tried sorting the same values with merge sort but I got the same output. I really fail to notice what I am missing.Can someone please point it out to me
Thanks in advance!

#include<iostream>
#include<iomanip>

using namespace std;

int const POINTS = 5;
double dataPoints[POINTS] = { 0.1, 0.5, 0.6, 0.2, 0.8 };

void sort(double dataPoints[])
{
    int i, j, flag = 1;
    int temp;
    for (i = 1; (i <= POINTS) && flag; i++)
    {
        flag = 0;
        for (j = 0; j < (POINTS - 1); j++)
        {
            if (dataPoints[j + 1] > dataPoints[j])
            {
                temp = dataPoints[j];
                dataPoints[j] = dataPoints[j + 1];
                dataPoints[j + 1] = temp;
                flag = 1;
            }
        }
    }

}

int main()
{

    sort(dataPoints);

    for (int i = 0; i < POINTS; i++)
    {
        cout << dataPoints[i] << " ";
    }

}

Output:

0.8 0 0 0 0

Body:
You swap double, with temporary of type int.

Use instead:

double temp;

or better auto:

const auto temp = dataPoints[j];
dataPoints[j] = dataPoints[j + 1];
dataPoints[j + 1] = temp;

or even better, use std::swap:

std::swap(dataPoints[j], dataPoints[j + 1]);

If allowed, you can even use:

std::sort(std::begin(dataPoints), std::end(dataPoints), std::greater<>{});


问:
How do I save a file in Flex with Flash 9
I am using Flex 3 under Flash Player 9.

I have a datagrid that I want to export to Excel. I construct the Excel object (ByteArray) in Actionscript, and now I want to save it using FileReference. However, under FlashPlayer 9, FileReference only has a download method. Can I somehow point this download method to the Excel object?

答:
I think you need to upload your data to your server, and then download it to your client.  Look at this example for saving images created in as3 to a client.

OR (this is hackish, but might get done what you need) you can print your data to the debug console.

OwnerDisplayName: Mike S

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jedierikb


问:
How can I pass mouse events on a translucent JWindow to the JFrame underneath?
I am creating a Firefox style drag and drop tabbed pane based on this example. To implement the scaled tab images as you drag I am using a JWindow. I want the image to be visible when you drag anywhere on the desktop so I have to use a heavyweight component instead of drawing on the glass pane like most examples I have seen.

However, when I drag the JWindow captures mouse events and interferes with drag and drop listeners that are on the JFrame below. Is there a way I can get the JWindow to resdispatch the mouse events so they activate the drag listeners on the JFrame below (like would happen if I did use the glass pane)?

答: Check out this good article "A well-behaved GlassPane" which may have some ideas for doing what you wish.</p>


问:
Using MySql.Data with C# while not making a MySqlConnection
The reccomended way to use MySql.Data is to NOT use a MySqlConnection object; as explained in the documentation.  This allows for the MySQl.Data API code to handle connection pooling correctly.
See: mySQL documentation

So, for example, this code Selects data with the connection string passed in as a parameter.

The MySqlConnection object is created in the background:

```<code>        DataSet dataset = new DataSet();
        MySqlDataAdapter adapter = new MySqlDataAdapter("select * from cfx_jobs", _mySqlConnectionString);
        adapter.Fill(dataset);
        return dataset;
</code>```

I have looked around and I cannot find an example of how to Insert into the database without explicitly creating a MySqlConnection object.

Which method should I use?

答:
This is how to do it.</p>

```<code>MySqlHelper.ExecuteNonQuery(_mySqlConnectionString, sqlStatement);
</code>```

Body:
The reccomended way to use MySql.Data is to NOT use a MySqlConnection object; as explained in the documentation.  This allows for the MySQl.Data API code to handle connection pooling correctly.
See: mySQL documentation

So, for example, this code Selects data with the connection string passed in as a parameter.

The MySqlConnection object is created in the background:

        DataSet dataset = new DataSet();
        MySqlDataAdapter adapter = new MySqlDataAdapter("select * from cfx_jobs", _mySqlConnectionString);
        adapter.Fill(dataset);
        return dataset;

I have looked around and I cannot find an example of how to Insert into the database without explicitly creating a MySqlConnection object.

Which method should I use?

Body:
This is how to do it.

MySqlHelper.ExecuteNonQuery(_mySqlConnectionString, sqlStatement);


问:
How to exchange square bracket and curly bracket (karabiner)
On Karabiner rules (https://pqrs.org/osx/karabiner/complex_modifications/), there is a rule for Exchange paren and square bracket but there is no rule for Exchange square bracket and curly braket.

[Q] How to exchange square bracket and curly bracket through Karabiner or any alternative?

Wanted exchange:

[ => { and { => [

] => } and } => ]

答:
This code works for me

```<code>{
  "description": "Swap {} and []",
  "manipulators": [
    {
      "type": "basic",
      "from": {
        "key_code": "open_bracket"
      },
      "to": [
        {
          "modifiers": ["left_shift"],
          "key_code": "open_bracket"
        }
      ]
    },
    {
      "type": "basic",
      "from": {
        "key_code": "open_bracket",
        "modifiers": {
          "mandatory": ["left_shift"]
        }
      },
      "to": [
        {
          "key_code": "open_bracket"
        }
      ]
    },
    {
      "type": "basic",
      "from": {
        "key_code": "close_bracket"
      },
      "to": [
        {
          "modifiers": ["left_shift"],
          "key_code": "close_bracket"
        }
      ]
    },
    {
      "type": "basic",
      "from": {
        "key_code": "close_bracket",
        "modifiers": {
          "mandatory": ["left_shift"]
        }
      },
      "to": [
        {
          "key_code": "close_bracket"
        }
      ]
    }
  ]
}
</code>```

edit: also now in complex mod list https://pqrs.org/osx/karabiner/complex_modifications/#exchange_square_brackets_and_curly_brackets

Body:
This code works for me

{
  "description": "Swap {} and []",
  "manipulators": [
    {
      "type": "basic",
      "from": {
        "key_code": "open_bracket"
      },
      "to": [
        {
          "modifiers": ["left_shift"],
          "key_code": "open_bracket"
        }
      ]
    },
    {
      "type": "basic",
      "from": {
        "key_code": "open_bracket",
        "modifiers": {
          "mandatory": ["left_shift"]
        }
      },
      "to": [
        {
          "key_code": "open_bracket"
        }
      ]
    },
    {
      "type": "basic",
      "from": {
        "key_code": "close_bracket"
      },
      "to": [
        {
          "modifiers": ["left_shift"],
          "key_code": "close_bracket"
        }
      ]
    },
    {
      "type": "basic",
      "from": {
        "key_code": "close_bracket",
        "modifiers": {
          "mandatory": ["left_shift"]
        }
      },
      "to": [
        {
          "key_code": "close_bracket"
        }
      ]
    }
  ]
}

edit: also now in complex mod list https://pqrs.org/osx/karabiner/complex_modifications/#exchange_square_brackets_and_curly_brackets


问:
Impossible to run the program with the "mpirun" command
I perfectly builded a program with cygwin, however when i've to run the .exe file with the command "mpirun" as the tutorial of the program says

https://github.com/jalombar/starsmasher/blob/master/documentation/walkthroughs/star_star_flyby.md

It appears the following error:

```<code>    $ mpirun -np 4 test_cpu_sph
[Francyrad:00524] PMIX ERROR: INIT in file /cygdrive/d/cyg_pub/devel/openmpi/v3.1/openmpi-3.1.5-1.x86_64/src/openmpi-3.1.5/opal/mca/pmix/pmix2x/pmix/src/mca/gds/ds21/gds_ds21_lock_pthread.c at line 188
[Francyrad:00524] PMIX ERROR: SUCCESS in file /cygdrive/d/cyg_pub/devel/openmpi/v3.1/openmpi-3.1.5-1.x86_64/src/openmpi-3.1.5/opal/mca/pmix/pmix2x/pmix/src/mca/common/dstore/dstore_base.c at line 2432
--------------------------------------------------------------------------
Open MPI tried to fork a new process via the "execve" system call but
failed.  Open MPI checks many things before attempting to launch a
child process, but nothing is perfect. This error may be indicative
of another problem on the target host, or even something as silly as
having specified a directory for your application. Your job will now
abort.

  Local host:        Francyrad
  Application name:  /cygdrive/c/Users/Francyrad/Desktop/starsmasher/GAM1.667_N1.5
  Error:             /cygdrive/c/Users/Francyrad/Desktop/starsmasher/GAM1.667_N1.5/test_cpu_sph
--------------------------------------------------------------------------
--------------------------------------------------------------------------
mpirun was unable to start the specified application as it encountered an
error:

Error name:
Node: (null)

when attempting to start process rank 34361314336.
--------------------------------------------------------------------------
4 total processes failed to start
[Francyrad:00524] 3 more processes have sent help message help-orte-odls-default.txt / execve error
[Francyrad:00524] Set MCA parameter "orte_base_help_aggregate" to 0 to see all help / error messages
</code>```

I tried everything, to change the syntaxis and other, but anything! Ive no idea how to make run this application. What the hell i've to do????

答:
Hum, the executable seem to be the problem...

Does your executable has been well built ? Do you see it with a "ls" command ?
And did you try to call the executable with mpirun using "mpirun -np 4 ./test_cpu_sph" instead of "mpirun -np 4 test_cpu_sph" ?

And could you give a bit more information please ? (if you're using cygwin, I guess that you're running on Windows ?)

Body:
I perfectly builded a program with cygwin, however when i've to run the .exe file with the command "mpirun" as the tutorial of the program says

https://github.com/jalombar/starsmasher/blob/master/documentation/walkthroughs/star_star_flyby.md

It appears the following error:

    $ mpirun -np 4 test_cpu_sph
[Francyrad:00524] PMIX ERROR: INIT in file /cygdrive/d/cyg_pub/devel/openmpi/v3.1/openmpi-3.1.5-1.x86_64/src/openmpi-3.1.5/opal/mca/pmix/pmix2x/pmix/src/mca/gds/ds21/gds_ds21_lock_pthread.c at line 188
[Francyrad:00524] PMIX ERROR: SUCCESS in file /cygdrive/d/cyg_pub/devel/openmpi/v3.1/openmpi-3.1.5-1.x86_64/src/openmpi-3.1.5/opal/mca/pmix/pmix2x/pmix/src/mca/common/dstore/dstore_base.c at line 2432
--------------------------------------------------------------------------
Open MPI tried to fork a new process via the "execve" system call but
failed.  Open MPI checks many things before attempting to launch a
child process, but nothing is perfect. This error may be indicative
of another problem on the target host, or even something as silly as
having specified a directory for your application. Your job will now
abort.

  Local host:        Francyrad
  Application name:  /cygdrive/c/Users/Francyrad/Desktop/starsmasher/GAM1.667_N1.5
  Error:             /cygdrive/c/Users/Francyrad/Desktop/starsmasher/GAM1.667_N1.5/test_cpu_sph
--------------------------------------------------------------------------
--------------------------------------------------------------------------
mpirun was unable to start the specified application as it encountered an
error:

Error name:
Node: (null)

when attempting to start process rank 34361314336.
--------------------------------------------------------------------------
4 total processes failed to start
[Francyrad:00524] 3 more processes have sent help message help-orte-odls-default.txt / execve error
[Francyrad:00524] Set MCA parameter "orte_base_help_aggregate" to 0 to see all help / error messages

I tried everything, to change the syntaxis and other, but anything! Ive no idea how to make run this application. What the hell i've to do????


答: The best practice when working on a css file is to be sure that your javafx program is using that css file.</p>

Title: How do you use an svg file to set a shape of a button in javafx?

Body:
I am attempting to create an image on a button similar to the calendar on DatePicker.

I have attempted to use -fx-shape, same as the date picker, with an svg path, but it does not seem to be working. The code I have in my css is:

 .time-picker > .toggle-button {
    -fx-shape:"M 43.73,27.84
           C 43.73,28.87 42.90,29.71 41.87,29.71
             41.87,29.71 26.13,29.71 26.13,29.71
             26.13,29.71 26.13,10.11 26.13,10.11
             26.13,9.08 26.97,8.24 28.00,8.24
             29.03,8.24 29.87,9.07 29.87,10.11
             29.87,10.11 29.87,25.97 29.87,25.97
             29.87,25.97 41.87,25.97 41.87,25.97
             42.89,25.97 43.73,26.81 43.73,27.84 Z
           M 56.00,28.00
           C 56.00,43.44 43.44,56.00 28.00,56.00
             12.56,56.00 0.00,43.44 0.00,28.00
             0.00,12.56 12.56,0.00 28.00,0.00
             43.44,0.00 56.00,12.56 56.00,28.00 Z
           M 52.27,28.00
           C 52.27,14.62 41.38,3.73 28.00,3.73
             14.62,3.73 3.73,14.62 3.73,28.00
             3.73,41.38 14.62,52.27 28.00,52.27
             41.38,52.27 52.27,41.38 52.27,28.00 Z";
 }

What am I doing wrong here?


问:
How do I make fetch requests to dynamic targets, remote non-cors enabled urls? In http-proxy-middleware, can variables be used in targets?
I use fetch('htp://list-of-servers') that returns a list of urls

test1.example.com

test3.example.com

test5.example.com

Then I need to perform a fetch() on each one of these urls: fetch('test1.example.com').then(...)

```<code>urls.map(url => fetch(url))
</code>```

but

a) url is not cors enabled (so I tried adding them in setupProxy)

b) I don't know these urls in advance (since they're result of an earlier fetch, so I'm not sure how they can be added to setupProxy.js.
I basically need some kind of equivalent to curl, that can request any non-cors remote url, but in js/react/node.

Suggestions?

答: Found a solution online. I have to run an express server/node app at the same time as the react client (different port), so client requests to url=test1.example.com, would be written as fetch(`/api/${url}`) then that would hit the express server localhost for proxying, where it would do a non-browser server-side request fetch(`http://${url}`) where cors problems wouldn't be an issue. I needed an ELI5.

Body:
I use fetch('htp://list-of-servers') that returns a list of urls

test1.example.com

test3.example.com

test5.example.com

Then I need to perform a fetch() on each one of these urls: fetch('test1.example.com').then(...)

urls.map(url => fetch(url))

but

a) url is not cors enabled (so I tried adding them in setupProxy)

b) I don't know these urls in advance (since they're result of an earlier fetch, so I'm not sure how they can be added to setupProxy.js.
I basically need some kind of equivalent to curl, that can request any non-cors remote url, but in js/react/node.

Suggestions?