问:
I am trying to calculate the sum of distances between every uninfected point and an infected point
I have a random plot of individuals with infection status using this data.frame:

```<code>structure(list(xcoord = c(22L, 38L, 46L, 86L, 66L, 97L, 51L,
87L, 24L, 45L, 61L, 96L, 91L, 90L, 49L, 17L, 25L, 7L, 6L, 74L,
76L, 94L, 27L, 99L, 39L, 83L, 40L, 41L, 9L, 84L, 88L, 63L, 43L,
12L, 93L, 1L, 54L, 13L, 33L, 68L, 20L, 64L, 85L, 3L, 28L, 19L,
23L, 81L, 79L, 5L, 78L, 56L, 8L, 26L, 73L, 37L, 71L, 14L, 11L,
55L), ycoord = c(8L, 35L, 77L, 5L, 68L, 22L, 62L, 86L, 85L, 91L,
74L, 71L, 11L, 1L, 34L, 76L, 13L, 57L, 10L, 29L, 14L, 47L, 80L,
45L, 83L, 56L, 17L, 70L, 55L, 51L, 6L, 46L, 16L, 58L, 18L, 72L,
54L, 38L, 41L, 73L, 69L, 33L, 100L, 50L, 37L, 65L, 25L, 90L,
20L, 95L, 88L, 19L, 67L, 42L, 78L, 53L, 15L, 96L, 66L, 84L),
infectionstatus = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, -60L), class = "data.frame")
</code>```

What I would like to do is calculate the distance between every uninfected individual with the infected individual. This is so that once I have the distance between every uninfected and the infected point, I can use this information to develop a likelihood of becoming infected function which is based on this information. How do I calculate the distance between each uninfected point and the one infected point?

答:
```<code># Calculate the pairwase distance matrix for every individual to the rest.
if (!require("rdist")) { install.packages("rdist"); require("rdist") }
distances <- pdist(data[,1:2], metric ="euclidean")

# dataframe position of the infected individual.
position_infected_individual <- which(data[,3]==1)

# distances from this infected individual to the rest (we eliminate the distance from itself that is 0)
dist_from_infected <- distances[-(position_infected_individual),position_infected_individual]
</code>```

Body:
I have a random plot of individuals with infection status using this data.frame:

structure(list(xcoord = c(22L, 38L, 46L, 86L, 66L, 97L, 51L,
87L, 24L, 45L, 61L, 96L, 91L, 90L, 49L, 17L, 25L, 7L, 6L, 74L,
76L, 94L, 27L, 99L, 39L, 83L, 40L, 41L, 9L, 84L, 88L, 63L, 43L,
12L, 93L, 1L, 54L, 13L, 33L, 68L, 20L, 64L, 85L, 3L, 28L, 19L,
23L, 81L, 79L, 5L, 78L, 56L, 8L, 26L, 73L, 37L, 71L, 14L, 11L,
55L), ycoord = c(8L, 35L, 77L, 5L, 68L, 22L, 62L, 86L, 85L, 91L,
74L, 71L, 11L, 1L, 34L, 76L, 13L, 57L, 10L, 29L, 14L, 47L, 80L,
45L, 83L, 56L, 17L, 70L, 55L, 51L, 6L, 46L, 16L, 58L, 18L, 72L,
54L, 38L, 41L, 73L, 69L, 33L, 100L, 50L, 37L, 65L, 25L, 90L,
20L, 95L, 88L, 19L, 67L, 42L, 78L, 53L, 15L, 96L, 66L, 84L),
infectionstatus = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, -60L), class = "data.frame")

What I would like to do is calculate the distance between every uninfected individual with the infected individual. This is so that once I have the distance between every uninfected and the infected point, I can use this information to develop a likelihood of becoming infected function which is based on this information. How do I calculate the distance between each uninfected point and the one infected point?


来源: stackexchange

问:
Mysql workbench timestamp change format
I have a table with a column in which are inserted timestamps.

exactTime : ' 2017-12-17 05:00:12 ' and i want to change this format into '2017-12-17 05:00'

i would need some help with this .

ContentLicense: CC BY-SA 4.0

Title: Mysql workbench timestamp change format

Body: SELECT date_format('2017-12-17 05:00:12','%Y-%m-%d %h:%i')


问:
Equal Height constraints between different UIStackView's subviews
I have a constraint scenario which works perfectly when built through interface builder but I cannot make it through code. The screen layout is the following:

A Horizontal UIStackView with multiple vertical UIStackView inline. Each one of these vertical UIStackView's has multiple UIView's inside it. What I'm trying to achieve is the following: inline UIView with equal height

When creating such constraints through interface builder, it works perfectly:

But when creating this constraints through code I face the following error:

'Unable to activate constraint with anchors <NSLayoutDimension:0x600002b9a6c0 "UIView:0x7f9e6f075c30.height"> and <NSLayoutDimension:0x600002b9a700 "UIView:0x7f9e6c423d50.height"> because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

I've tried creating these constraints using the following ways:

1.

```<code>let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
NSLayoutConstraint.activate([heightConstraint])
</code>```

2.

```<code>let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
horizontalStackView.addConstraint(heightConstraint)
</code>```

where horizontalStackView is the horizontal stackview that holds all vertical stackviews.

I cannot figure out where this constraints were added to work through interface builder to create them through code.

答:
You should focus on the "because they have no common ancestor" part. The problem is probably related to your views not being added to a same container view.

I don't know how you created your views, but at a certain point you need to do something like self.addSubview(yourView), which would solve your problem.

Body:
I have a constraint scenario which works perfectly when built through interface builder but I cannot make it through code. The screen layout is the following:

A Horizontal UIStackView with multiple vertical UIStackView inline. Each one of these vertical UIStackView's has multiple UIView's inside it. What I'm trying to achieve is the following: inline UIView with equal height

When creating such constraints through interface builder, it works perfectly:

But when creating this constraints through code I face the following error:

'Unable to activate constraint with anchors <NSLayoutDimension:0x600002b9a6c0 "UIView:0x7f9e6f075c30.height"> and <NSLayoutDimension:0x600002b9a700 "UIView:0x7f9e6c423d50.height"> because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

I've tried creating these constraints using the following ways:

1.

let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
NSLayoutConstraint.activate([heightConstraint])

2.

let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
horizontalStackView.addConstraint(heightConstraint)

where horizontalStackView is the horizontal stackview that holds all vertical stackviews.

I cannot figure out where this constraints were added to work through interface builder to create them through code.


问:
Access key, value in a JSON object within an array with SQL
I'm a bit stuck with accessing a value in an object contained in a JSON array. I've tried UNNEST() to no avail. Adding OFFSET or ORDINAL did not work. It threw Array index 0 is out of bounds (overflow)

Here is the query:

```<code>SELECT d.dealid, associations.associatedvids FROM hs.deals as d
WHERE associations.associatedvids is not null
</code>```

Thank you

答:
The issue was that some rows included an empty array []. I've added WHERE condition to remove such rows:</p>

```<code>WHERE ARRAY_LENGTH(d.associations.associatedvids) >= 1
</code>```

Body:
I'm a bit stuck with accessing a value in an object contained in a JSON array. I've tried UNNEST() to no avail. Adding OFFSET or ORDINAL did not work. It threw Array index 0 is out of bounds (overflow)

Here is the query:

SELECT d.dealid, associations.associatedvids FROM hs.deals as d
WHERE associations.associatedvids is not null

Thank you

Body:
The issue was that some rows included an empty array []. I've added WHERE condition to remove such rows:

WHERE ARRAY_LENGTH(d.associations.associatedvids) >= 1


问:
Couldn't start client Rust Language Server
I'm trying to figure out how to use rustc & cargo from my WSL. I use VS Code and Rust (rls) plugin and can compile my code but there is a problem with RLS:

Couldn't start client Rust Language Server

Rustup not available. Install from https://www.rustup.rs/

How i can solve this problem?

答:
I had this problem as well with WSL and Visual Studio Code.  The problem seems to stem from the fact that the Rust Language Server needs to find rustup in your path.  We both probably followed the same path of using a package manager to install cargo, and therefore, the rust compiler tools.  This does not include rustup which you can actually use to keep the rust toolchain up-to-date.  rustup also appears to be the preferred method of installing the rust toolchain on your system.

After installing rustup with the default setup, you should see a .rustup directory in your home directory.  This is where the toolchain lives.  The install text all stated that it would add the toolchain to your environment path after logging out and back in, but I didn't have luck with this.  I'm currently using fish instead of bash and had to update the configuration to include the toolchain at startup.  Once I did that, I was able to have VSCode properly install and run the RLS.


Title: I am trying to calculate the sum of distances between every uninfected point and an infected point

Body:
You can use outer to calcualte the distances if the dataset is small.

i <- x$infectionstatus == 1
tt <- outer(x$xcoord[i], x$xcoord[!i], "-")^2 + outer(x$ycoord[i], x$ycoord[!i], "-")^2
sqrt(apply(tt, 2, min))
# [1]  81.884064  57.271284  56.603887  42.755117  35.000000  25.179357
# [7]  45.541190  39.623226  79.649231  65.855903  42.638011  24.083189
#[13]  36.124784  46.173586  46.840154  82.280010  76.922038  87.572827
#[19]  95.462034  26.907248  37.589892  74.686009   5.385165  65.734314
#[25]  14.212670  61.773781  57.775427  85.375641  10.770330  41.436699
#[31]  31.016125  59.682493  82.734515  29.017236  96.301610  40.607881
#[37]  81.498466  61.294372  36.769553  77.201036  33.105891  53.758720
#[43]  91.049437  66.753277  77.129761  74.330344  44.922155  30.886890
#[49] 101.118742  44.011362  47.201695  88.294960  68.183576  37.443290
#[55]  57.314920  39.408121  93.813645  85.146932  53.758720


问:
Is it safe to convert String to String[] by split(\0)?
For giving a string (which does not contain "\0") of type String to function as parameter, which must be of type String[], I convert String to String[] in such way:

```<code>string.split("\0")
</code>```

What do you think, is it safe enough?

Will it always work as expected (for any String without "\0")?

答:
is there a reason against doing

new String[]{string}?

because that would be more efficient than that method and more readable.

edit: I'd also like to add that split can have a second parameter on max size for the array, so if you put some regex in there you can just put 1 as the second param and guarantee that it will not actually do any splitting, but there is no reason to do that over the above method.

Body:
For giving a string (which does not contain "\0") of type String to function as parameter, which must be of type String[], I convert String to String[] in such way:

string.split("\0")

What do you think, is it safe enough?

Will it always work as expected (for any String without "\0")?


问:
Key Évents on textbox ,button and progressbar?
I have a textbox, a button, and a progressbar. I would like the keydown event of the textbox therefore the entry, is found using a button in the progressbar, in fact I would like the number entered in the textbox to become the value of the progressbar and that in this case the progressbar value increases. If you could put me a sample code, that would be nice, thank you.

    public void button1_Click(object
    sender,EventArgs e)
    {
    //I don't know.
    }

    public void textbox2_KeyDown(object
    sender,KeyEventArgs e)
    {
    if(e.KeyCode <= Keys.NumPad0 ||
    e.KeyCode >= Keys.NumPad9)
    {
     // I don't know !
    }
```

答:
As I understood, you want to change the progress bar value based on the textBox input and detect that change.
Well, to get the input from the textBox on change, there is an event for that which called:
TextChanged

so with every change in the input, you'll be able to capture the input.
For the progressbar, you can change the value by the property: Value.
Read more:
ProgressBar.Value
so if your progressBar control named: progressBar1, change it by:

```<code>progressBar1.Value = 5; // here the value is 5.
</code>```

Now, you can use textChanged event to set the progress bar value like:

```<code>public void textbox2_TextChanged(object sender,KeyEventArgs e)
{
   progressBar1.Value = int.Parse(textBox2.Text); // parse the input to int value. Consider using int.TryParse
}
</code>```

Body:
As I understood, you want to change the progress bar value based on the textBox input and detect that change.
Well, to get the input from the textBox on change, there is an event for that which called:
TextChanged

so with every change in the input, you'll be able to capture the input.
For the progressbar, you can change the value by the property: Value.
Read more:
ProgressBar.Value
so if your progressBar control named: progressBar1, change it by:

progressBar1.Value = 5; // here the value is 5.

Now, you can use textChanged event to set the progress bar value like:

public void textbox2_TextChanged(object sender,KeyEventArgs e)
{
   progressBar1.Value = int.Parse(textBox2.Text); // parse the input to int value. Consider using int.TryParse
}


问:
How to know what is the memory consumption of an single record in database table mysql
I am having a DB table with only 35000 of records on export of DB I found that the file size is more than 2 GB .

Even my table schema does not contains any BLOB type of data. Is there any way to identify Table row size in MySQL.

答:
What if we first find out the size of the consumed memory by an empty table with performing the next query:

```<code>SELECT table_name AS "Table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES
WHERE table_schema = "database_name"
AND table_name =  "your_table_name";
</code>```

Then insert in your table several rows of data, then perform the above query again and calculate the difference and the average value of memory consumption for one record.
Example:
I have a table:

```<code>create table returning_players
(
casino_id               int not null,
game_id                 int not null,
returning_players_count int null,
primary key (casino_id, game_id)
);
</code>```

so empty table consumes:

then insert into table 1000 000 records:

```<code>DROP PROCEDURE IF EXISTS query;
CREATE procedure query()
BEGIN
    declare counter int(20) default 0;
    LABEL:
    LOOP
        IF counter >= 1000000 THEN
            LEAVE LABEL;
        END IF;
        INSERT INTO returning_players VALUES(counter, 45, 5475);
        set counter = counter + 1;
    END LOOP LABEL;
END;
CALL query();
</code>```

and now we have memory consumption:

as you see that we have approximately consumed 32.56 MB per 1000_000 rows. From where we can get the consumption by one row.

ContentLicense: CC BY-SA 3.0

Body:
What if we first find out the size of the consumed memory by an empty table with performing the next query:

SELECT table_name AS "Table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES
WHERE table_schema = "database_name"
AND table_name =  "your_table_name";

Then insert in your table several rows of data, then perform the above query again and calculate the difference and the average value of memory consumption for one record.
Example:
I have a table:

create table returning_players
(
casino_id               int not null,
game_id                 int not null,
returning_players_count int null,
primary key (casino_id, game_id)
);

so empty table consumes:

then insert into table 1000 000 records:

DROP PROCEDURE IF EXISTS query;
CREATE procedure query()
BEGIN
    declare counter int(20) default 0;
    LABEL:
    LOOP
        IF counter >= 1000000 THEN
            LEAVE LABEL;
        END IF;
        INSERT INTO returning_players VALUES(counter, 45, 5475);
        set counter = counter + 1;
    END LOOP LABEL;
END;
CALL query();

and now we have memory consumption:

as you see that we have approximately consumed 32.56 MB per 1000_000 rows. From where we can get the consumption by one row.


问:
make file.exists() case insensitive
I have a line of code in my script that checks if a file exists (actually, many files, this one line gets looped for a bunch of different files):

```<code>file.exists(Sys.glob(file.path(getwd(), "files", "*name*")))
</code>```

This looks for any file in the directory /files/  that has "name" in it, e.g. "filename.csv". However, some of my files are named "fileName.csv" or "thisfileNAME.csv". They do not get recognized. How can i make file.exists treat this check in a case insensitive way?

In my other code i usually make any imported names or lists immediately lowercase with the tolower function. But I don't see any option to include that in the file.exists function.

答:
The following should return a 1 if the filename matches in any case and a 0 if it does not.</p>

```<code>max(grepl("*name*",list.files()),ignore.case=T)
</code>```

Title: make file.exists() case insensitive

Body:
I have a line of code in my script that checks if a file exists (actually, many files, this one line gets looped for a bunch of different files):

file.exists(Sys.glob(file.path(getwd(), "files", "*name*")))

This looks for any file in the directory /files/  that has "name" in it, e.g. "filename.csv". However, some of my files are named "fileName.csv" or "thisfileNAME.csv". They do not get recognized. How can i make file.exists treat this check in a case insensitive way?

In my other code i usually make any imported names or lists immediately lowercase with the tolower function. But I don't see any option to include that in the file.exists function.

Body:
The following should return a 1 if the filename matches in any case and a 0 if it does not.

max(grepl("*name*",list.files()),ignore.case=T)


问:
How to build only submodules of a gradle parent module?
I am desperately trying to build only submodules of a gradle module.
This is my current struture:

```<code>root
|_ foo
   |_egg
   |_nogg
|_ bar
   |_celona
</code>```

When I run

```<code>gradle :foo:egg:build
</code>```

It builds the submodule.
I want it to build all two submodules egg and nogg

I tried:

```<code>gradle :foo:build
</code>```

But it only build foo (which has no sources)

```<code>gradle :foo:*:build
</code>```

Is what I expected to do or

```<code>gradle :foo::build
</code>```

However no luck in getting it to work. Any ideas? The documentation is not giving out a hint for the multiproject part.

答:
You could execute all foo sub-project tasks by specifying full path to each task:

```<code>gradle :foo:egg:build :foo:nogg:build
</code>```

Gradle accepts multiple tasks in command line parameters.

Body:
I am desperately trying to build only submodules of a gradle module.
This is my current struture:

root
|_ foo
   |_egg
   |_nogg
|_ bar
   |_celona

When I run

gradle :foo:egg:build

It builds the submodule.
I want it to build all two submodules egg and nogg

I tried:

gradle :foo:build

But it only build foo (which has no sources)

gradle :foo:*:build

Is what I expected to do or

gradle :foo::build

However no luck in getting it to work. Any ideas? The documentation is not giving out a hint for the multiproject part.

Body:
You could execute all foo sub-project tasks by specifying full path to each task:

gradle :foo:egg:build :foo:nogg:build

Gradle accepts multiple tasks in command line parameters.


问:
How to prevent Travis-CI generate yarn.lock OR how to ignore Lerna publish to ignore uncommited changes in working tree
I have a monorepo project setup using Lerna and use Travis-CI to automatically publish canary version after after all tests passed.

The problem is, in some case Yarn generates the yarn.lock file during install which make Lerna complaints about uncommitted file and refuse to publish.

I search through the Lerna docs but I couldn't found a way to skip uncommitted working tree and proceed the publish.

I neither found how to setup Travis to not generate the yarn.lock file.

Any help will be appreciated

My Travis config file is below:

```<code>language: node_js
node_js:
  - 10
before_deploy:
  - printf "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" >> ~/.npmrc
deploy:
  skip_cleanup: true
  provider: script
  script: yarn publish_canary
  on:
    node: stable
    branch: master
</code>```

答: I was having the same issues and I figured out yarn comes with --frozen-lockfile which prevents lock file being generated and fails if update is needed (I've read that it's better alternative to <code>--pure-lockfile</code> since this one won't fail if config drifts....reference). </p>

Body:
I have a monorepo project setup using Lerna and use Travis-CI to automatically publish canary version after after all tests passed.

The problem is, in some case Yarn generates the yarn.lock file during install which make Lerna complaints about uncommitted file and refuse to publish.

I search through the Lerna docs but I couldn't found a way to skip uncommitted working tree and proceed the publish.

I neither found how to setup Travis to not generate the yarn.lock file.

Any help will be appreciated

My Travis config file is below:

language: node_js
node_js:
  - 10
before_deploy:
  - printf "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" >> ~/.npmrc
deploy:
  skip_cleanup: true
  provider: script
  script: yarn publish_canary
  on:
    node: stable
    branch: master

Body: I was having the same issues and I figured out yarn comes with --frozen-lockfile which prevents lock file being generated and fails if update is needed (I've read that it's better alternative to --pure-lockfile since this one won't fail if config drifts....reference).


问:
delete-access-config failed because of "unrecognized arguments: NAT"
```<code>gcloud compute instances delete-access-config gcc1 --access-config-name "External NAT"
</code>```

ERROR: (gcloud.compute.instances.delete-access-config) unrecognized
  arguments: NAT

It's just like the whitespace who cause the error.

Thanks.

答: You cannot use a whitespace in the name. In the example given here, they use external-nat as the name. (Note the dash)

Body:
gcloud compute instances delete-access-config gcc1 --access-config-name "External NAT"

ERROR: (gcloud.compute.instances.delete-access-config) unrecognized
  arguments: NAT

It's just like the whitespace who cause the error.

Thanks.


问:
Replace ctest command with "ctest --output-on-failure" permanently for a specific project in CMakeLists.txt
I have found that generic ctest command doesn't give much information about the tests, so I would like to add ctest --output-on-failure but not have the users to worry about the flag. I want them just to cmake, make the project and run ctest and it should run ctest with the --output-on-failure flag. Is it possible to do that in CMakeLists.txt?

EDIT:

Output of env CTEST_OUTPUT_ON_FAILURE=1 make test

```<code> 4/13 Test  #4: TEST_SSSP ........................***Failed  Required regular expression not found.Regex=[CORRECT
]  0.00 sec
Loading Matrix-market coordinate-formatted graph ...
Input graph file /home/muhammad/gunrock/dataset/small/chesapeake.mtx does not exis
</code>```

Output of set_property(TEST TestName PROPERTY ENVIRONMENT "CTEST_OUTPUT_ON_FAILURE=1")

```<code> 4/13 Test  #4: TEST_SSSP ........................***Failed  Required regular expression not found.Regex=[CORRECT
]  0.00 sec
</code>```

The flag in set_property is not working.

答:
In CMake 3.17 release notes, there's a new variable CMAKE_CTEST_ARGUMENTS that you can set to pass any command-line arguments to CTest, including --output-on-failure. In your specific case, you can now simply add this to your CMakeLists.txt:

```<code>list(APPEND CMAKE_CTEST_ARGUMENTS "--output-on-failure")
</code>```

Body:
I have found that generic ctest command doesn't give much information about the tests, so I would like to add ctest --output-on-failure but not have the users to worry about the flag. I want them just to cmake, make the project and run ctest and it should run ctest with the --output-on-failure flag. Is it possible to do that in CMakeLists.txt?

EDIT:

Output of env CTEST_OUTPUT_ON_FAILURE=1 make test

 4/13 Test  #4: TEST_SSSP ........................***Failed  Required regular expression not found.Regex=[CORRECT
]  0.00 sec
Loading Matrix-market coordinate-formatted graph ...
Input graph file /home/muhammad/gunrock/dataset/small/chesapeake.mtx does not exis

Output of set_property(TEST TestName PROPERTY ENVIRONMENT "CTEST_OUTPUT_ON_FAILURE=1")

 4/13 Test  #4: TEST_SSSP ........................***Failed  Required regular expression not found.Regex=[CORRECT
]  0.00 sec

The flag in set_property is not working.

Body:
In CMake 3.17 release notes, there's a new variable CMAKE_CTEST_ARGUMENTS that you can set to pass any command-line arguments to CTest, including --output-on-failure. In your specific case, you can now simply add this to your CMakeLists.txt:

list(APPEND CMAKE_CTEST_ARGUMENTS "--output-on-failure")


问:
Big React Calender year view
I need help in react-big-calendar.Some of the view already in react-big-calender like days, week & agenda etc. but how can i add custom view for year view in react-big-calender.

答:
I've been looking at the same, there is nothing out-of-the-box - I might use this as a starting point:

https://codesandbox.io/s/jjmky5047y

Title: Big React Calender year view


问:
Laravel create model outside app namespace
I want to use the command php artisan make:model User for creating an user inside the domain folder. Nevertheless it will end up in the App folder.

I've already tried this:

php artisan make:model Domain\User

php artisan make:model Domain\\User

php artisan make:model \\Domain\\User

php artisan make:model Domain/User

app folder:

```<code>app
 |
 +-- App
 |
 |
 +-- Domain
 |
 |
 +-- Http
</code>```

composer file:

```<code>"autoload": {
    "psr-4": {
      "App\\": "app/App/",
      "Domain\\": "app/Domain/",
      "Http\\": "app/Http/",
      "Support\\": "app/Support/"
    },
</code>```

UPDATE

php artisan make:model ../Domain/User solved the problem for model. I have stil the problem with a controller php artisan make:controller ../Http/UserController

答:
Not sure why you need to create a model outside the default location.

Artisan make commands will attempt to store the files in the standard location according to the command you running.

As an example, php artisan make:model User will create the model inside app directory (default directory for models). So assuming the desired destination for your model is one directory above and has the name Domain you can run the following command:

```<code>php artisan make:model ../Domain/User
</code>```

Note that ../Domain/ is relative to the default location for that command.

For a controller, knowing the default directory is app/http/Controller and you want to generate a controller in Domain/http/Controller you can do it with the following command:

php artisan make:controller ../../../Domain/Http/UserController

Please note that this isn't usual and is not following the standards.

Hape that helps you with what you are trying to achieve

Body:
I want to use the command php artisan make:model User for creating an user inside the domain folder. Nevertheless it will end up in the App folder.

I've already tried this:

php artisan make:model Domain\User

php artisan make:model Domain\\User

php artisan make:model \\Domain\\User

php artisan make:model Domain/User

app folder:

app
 |
 +-- App
 |
 |
 +-- Domain
 |
 |
 +-- Http

composer file:

"autoload": {
    "psr-4": {
      "App\\": "app/App/",
      "Domain\\": "app/Domain/",
      "Http\\": "app/Http/",
      "Support\\": "app/Support/"
    },

UPDATE

php artisan make:model ../Domain/User solved the problem for model. I have stil the problem with a controller php artisan make:controller ../Http/UserController

Body:
Not sure why you need to create a model outside the default location.

Artisan make commands will attempt to store the files in the standard location according to the command you running.

As an example, php artisan make:model User will create the model inside app directory (default directory for models). So assuming the desired destination for your model is one directory above and has the name Domain you can run the following command:

php artisan make:model ../Domain/User

Note that ../Domain/ is relative to the default location for that command.

For a controller, knowing the default directory is app/http/Controller and you want to generate a controller in Domain/http/Controller you can do it with the following command:

php artisan make:controller ../../../Domain/Http/UserController

Please note that this isn't usual and is not following the standards.

Hape that helps you with what you are trying to achieve


问:
How do I convert the VBA long &HFFFFFFF0 to a uint for use in C#?
I've seen few examples that work for me. So I wanted to ask a new question. I am specifically trying to use the AccessibleObjectFromWindow method from oleacc.dll.

I have a version of a function, written by someone else, in Access VBA that I am trying to port to C#.

the code in question is:

```<code>    public static bool GetReferenceToApplication(long hWndXL, out object oApplication)
{
    oApplication = null;
    long hWinDesk = (long)FindWindowEx(new IntPtr(hWndXL), new IntPtr(0), "XLDESK", string.Empty);
    long hWin7 = (long)FindWindowEx(new IntPtr(hWinDesk), new IntPtr(0), "EXCEL7", string.Empty);
    Guid guid = new Guid("00020400-0000-0000-C000-000000000046");
    object obj = null;

    if (AccessibleObjectFromWindow(new IntPtr(hWin7), Convert.ToUInt32("&HFFFFFFF0", 16), ref guid, ref obj) == RETURN_OK)
    {
        oApplication = obj;
        return true;
    }
    else return false;
}
</code>```

Convert.ToUInt32("&HFFFFFFF0", 16) does not work. I know I am doing something wrong here, I do not know what exactly that is. In VBA, I think the ampersand denotes a long. But, I'm not too familiar with this sort of thing yet. Any help would be appreciated. I get an exception now matter which way I try to convert this value to a uint.

答:
Just remove &H from the string.  VBA uses that to indicate "this is a hex value" but it isn't part of a valid hex string that C# can interpret.

```<code>Convert.ToUInt32("FFFFFFF0", 16)
</code>```

Body:
I've seen few examples that work for me. So I wanted to ask a new question. I am specifically trying to use the AccessibleObjectFromWindow method from oleacc.dll.

I have a version of a function, written by someone else, in Access VBA that I am trying to port to C#.

the code in question is:

    public static bool GetReferenceToApplication(long hWndXL, out object oApplication)
{
    oApplication = null;
    long hWinDesk = (long)FindWindowEx(new IntPtr(hWndXL), new IntPtr(0), "XLDESK", string.Empty);
    long hWin7 = (long)FindWindowEx(new IntPtr(hWinDesk), new IntPtr(0), "EXCEL7", string.Empty);
    Guid guid = new Guid("00020400-0000-0000-C000-000000000046");
    object obj = null;

    if (AccessibleObjectFromWindow(new IntPtr(hWin7), Convert.ToUInt32("&HFFFFFFF0", 16), ref guid, ref obj) == RETURN_OK)
    {
        oApplication = obj;
        return true;
    }
    else return false;
}

Convert.ToUInt32("&HFFFFFFF0", 16) does not work. I know I am doing something wrong here, I do not know what exactly that is. In VBA, I think the ampersand denotes a long. But, I'm not too familiar with this sort of thing yet. Any help would be appreciated. I get an exception now matter which way I try to convert this value to a uint.

Body:
Just remove &H from the string.  VBA uses that to indicate "this is a hex value" but it isn't part of a valid hex string that C# can interpret.

Convert.ToUInt32("FFFFFFF0", 16)


问:
Is there a better way in C# to reserve long variable name?
```<code>var test = Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName
</code>```

I have to use above in many places. How to avoid typing or save few key stroke? is there any shortcut in C#

答:
You can use namespace aliasing and just call it in namespaces section in your code, and you can effectively use objects and functions all over the body @canton7 has already written example for that.
or you can use code blocks statements but you have to implement IDisposable, but this can limit your object calling section but you can get benefit fit automatic dispose.  </p>

```<code> class Class1
{
   public class Subclass1
    {
      public  class Subclass2 : IDisposable
        {
            public string PropertyNameWhichIsBigName { get; set; }

            public void Dispose()
            {
                throw new NotImplementedException();
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        using (Class1.Subclass1.Subclass2 obj = new Class1.Subclass1.Subclass2())
        {
            string propertiesValue = obj.PropertyNameWhichIsBigName;
        }
    }
}
</code>```

Body:
var test = Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName

I have to use above in many places. How to avoid typing or save few key stroke? is there any shortcut in C#

Body:
You can use namespace aliasing and just call it in namespaces section in your code, and you can effectively use objects and functions all over the body @canton7 has already written example for that.
or you can use code blocks statements but you have to implement IDisposable, but this can limit your object calling section but you can get benefit fit automatic dispose.

 class Class1
{
   public class Subclass1
    {
      public  class Subclass2 : IDisposable
        {
            public string PropertyNameWhichIsBigName { get; set; }

            public void Dispose()
            {
                throw new NotImplementedException();
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        using (Class1.Subclass1.Subclass2 obj = new Class1.Subclass1.Subclass2())
        {
            string propertiesValue = obj.PropertyNameWhichIsBigName;
        }
    }
}


答:
The usual way with sed: write a regex that matches 43 | characters with anything in between and a digit. Then insert a newline after the matched string.

```<code>sed 's/[0-9]\{6\}\(|[^|]*\)\{41\}|[0-9]/&\n/g ; s/\n$//'
#                                               ^^^^^^^ - remove the leftover newline
#                                       ^ - the matched string
#                                 ^^^^^ - trailing digit
#                                ^ - 42th pipe character
#                ^^^^^^^^^^^^^^^^ - 41 fields with anything in between
#      ^^^^^^^^^^ - leading 6 digits
</code>```

tested on repl

Or maybe match 42 pipes with anything in front and a digit::

```<code>sed 's/\([^|]*|\)\{42\}[0-9]/&\n/g ; s/\n$//'
</code>```

Or match a character after 42 pipes and a digit and insert a newline in between:

```<code>sed 's/\(\([^|]*|\)\{42\}[0-9]\)\(.\)/\1\n\3/g'
</code>```

Title: Bash command/script to split line on a certain character

Body:
I would like to split the below data to the expected output:

Raw Data:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Expected Output:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0
931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Basically the \n character is getting lost sometimes in the data and the lines are getting merged. Sometimes more than 1 line gets merged as well (even the opposite happens but we can get to that later).

The data always has 43 columns | separated. The last but one column(42nd) always is a timestamp and the last column is usually 0 or 1.

Trying for the below approach:
If cols > 43
Split 44th column to add \n and print the remaining.
Repeat process until cols=43

echo "${curr}" | awk -F\| ' { if(NF > 43) {for(i=43;i<NF;i++) "sed '${NR}s/\(^0\)/\1\n/p' $i" }}' filename

Body:
The usual way with sed: write a regex that matches 43 | characters with anything in between and a digit. Then insert a newline after the matched string.

sed 's/[0-9]\{6\}\(|[^|]*\)\{41\}|[0-9]/&\n/g ; s/\n$//'
#                                               ^^^^^^^ - remove the leftover newline
#                                       ^ - the matched string
#                                 ^^^^^ - trailing digit
#                                ^ - 42th pipe character
#                ^^^^^^^^^^^^^^^^ - 41 fields with anything in between
#      ^^^^^^^^^^ - leading 6 digits

tested on repl

Or maybe match 42 pipes with anything in front and a digit::

sed 's/\([^|]*|\)\{42\}[0-9]/&\n/g ; s/\n$//'

Or match a character after 42 pipes and a digit and insert a newline in between:

sed 's/\(\([^|]*|\)\{42\}[0-9]\)\(.\)/\1\n\3/g'


问:
String values are not displaying on graph created using matplotlib-python
I have created sample graph using matplotlib-python with below code.

```<code>df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': [1000,2000,3000,400]})
print (df.head())
df.plot(kind='line',x='City', y='Staff', color= 'Blue')
plt.show()
</code>```

I am facing issue with the display of names when it is a line kind graph.
Below are the images where it shows names of the city in bar graph but not displaying in line type graph.

How do I make the city names show as labels for the X axis in the line plot?

matplotlib version used is : 3.1.3

答:
I can't reproduce your problem (matplotlib v3.1.1, but this is likely a pandas issue, not a matplotlib one)

However, the following should explicitly set the xlabels as you desire

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                    'Staff': [1000,2000,3000,400]})
ax = df.plot(kind='line',x='City', y='Staff', color= 'Blue')

# Set axis labels as desired
ax.set_xticklabels(df['City'])
ax.set_xticks(df.index)

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

Body:
I have created sample graph using matplotlib-python with below code.

df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': [1000,2000,3000,400]})
print (df.head())
df.plot(kind='line',x='City', y='Staff', color= 'Blue')
plt.show()

I am facing issue with the display of names when it is a line kind graph.
Below are the images where it shows names of the city in bar graph but not displaying in line type graph.

How do I make the city names show as labels for the X axis in the line plot?

matplotlib version used is : 3.1.3

Body:
I can't reproduce your problem (matplotlib v3.1.1, but this is likely a pandas issue, not a matplotlib one)

However, the following should explicitly set the xlabels as you desire

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                    'Staff': [1000,2000,3000,400]})
ax = df.plot(kind='line',x='City', y='Staff', color= 'Blue')

# Set axis labels as desired
ax.set_xticklabels(df['City'])
ax.set_xticks(df.index)

plt.show()


问:
Python return the first index where multiple columns contain a desired value
I have the following sample data frame:

df = pd.DataFrame({
    'seq':[0,1,2,3,4,5,6,7,8,9,10,11],
    'flag1':[np.nan,np.nan,1,1,1, 0,-1,-1,1,1,1,0],
    'flag2':[np.nan,np.nan,np.nan,0, 0,0,-1,-1,0,1, 0,1]
})
```

I am trying to get the index of the first row where both flag1 and flag2 values are 1. In the above case, it would be 9.

I tried df[df.flag1 == 1.0 & df.flag2 == 1.0].index[0] but it returns me an error. Similarly, df[df.flag1 == 1.0] & df[df.flag2 == 1.0].index[0] does not work either. I tried searching on SO but could not find a solution for my specific need.

答:
In this expression:

```<code>df.flag1 == 1.0 & df.flag2 == 1.0
</code>```

the & operator has greatest precedence, so it is actually interpreted as:

```<code>df.flag1 == (1.0 & df.flag2) == 1.0
</code>```

which is entirely not what you meant, and in this case produces an error.

Add parentheses to force the evaluation order you want:

```<code>(df.flag1 == 1.0) & (df.flag2 == 1.0)
</code>```

With this change, your initial approach should work fine.

Body:
I have the following sample data frame:

df = pd.DataFrame({
    'seq':[0,1,2,3,4,5,6,7,8,9,10,11],
    'flag1':[np.nan,np.nan,1,1,1, 0,-1,-1,1,1,1,0],
    'flag2':[np.nan,np.nan,np.nan,0, 0,0,-1,-1,0,1, 0,1]
})

I am trying to get the index of the first row where both flag1 and flag2 values are 1. In the above case, it would be 9.

I tried df[df.flag1 == 1.0 & df.flag2 == 1.0].index[0] but it returns me an error. Similarly, df[df.flag1 == 1.0] & df[df.flag2 == 1.0].index[0] does not work either. I tried searching on SO but could not find a solution for my specific need.

Body:
In this expression:

df.flag1 == 1.0 & df.flag2 == 1.0

the & operator has greatest precedence, so it is actually interpreted as:

df.flag1 == (1.0 & df.flag2) == 1.0

which is entirely not what you meant, and in this case produces an error.

Add parentheses to force the evaluation order you want:

(df.flag1 == 1.0) & (df.flag2 == 1.0)

With this change, your initial approach should work fine.


问:
How to make internal link to go to another component's ID element - Angular
Problem Statement

I cannot seem to use an internal link in the  tag to go to another component's specific section by HTML ID.

What I've tried

I went to this site: https://www.w3schools.com/html/html_links.asp and found nothing related to what I am doing.

Also, I went to this site https://www.yourhtmlsource.com/text/internallinks.html and found the thing that is related to my problem. The part is called: "Linking to parts of other documents" and this doesn't seem to work: href="http://www.yourhtmlsource.com/text/internallinks.html#section-names">. It basically links to another document and it goes to a specific section of that site, but alas, it does not work for me.

My Code

This is the page I am linking from:

```<code><a href="../products/products.component.html#backToTopBtn"><button mat-raised-button class="productsServicesBtn">Products
      <br>Services</button></a>
</code>```

This is the page I want to link to:

```<code><body>
  <button mat-raised-button id="backToTopBtn">Back to Top</button>
</body>
</code>```

Please Note: These are two different Angular components.

Explanation Of Code

As you can see, I am using what the second website has told me to do inside the href with the HTML ID at the end of the link to tell the browser which section to go to. It does not work.

FYI, the ID at the end is called a "fragment identifier".

Expected Results

The "internal" link opens up the other page and goes to the specific section which I mentioned.

Actual Results

The link does nothing and does not go anywhere.

答:
EDIT: I added the fragment

You should not link to ./products.component.html as it does not exist at runtime (in the browser).

you should link to a route using routerLink

```<code> <a routerLink="/product" fragment="backToTopBtn">services</a>
</code>```

check angular docs Routing and navigation

Body:
Problem Statement

I cannot seem to use an internal link in the  tag to go to another component's specific section by HTML ID.

What I've tried

I went to this site: https://www.w3schools.com/html/html_links.asp and found nothing related to what I am doing.

Also, I went to this site https://www.yourhtmlsource.com/text/internallinks.html and found the thing that is related to my problem. The part is called: "Linking to parts of other documents" and this doesn't seem to work: . It basically links to another document and it goes to a specific section of that site, but alas, it does not work for me.

My Code

This is the page I am linking from:

<button mat-raised-button class="productsServicesBtn">Products

Services</button>

This is the page I want to link to:

  <button mat-raised-button id="backToTopBtn">Back to Top</button>

Please Note: These are two different Angular components.

Explanation Of Code

As you can see, I am using what the second website has told me to do inside the href with the HTML ID at the end of the link to tell the browser which section to go to. It does not work.

FYI, the ID at the end is called a "fragment identifier".

Expected Results

The "internal" link opens up the other page and goes to the specific section which I mentioned.

Actual Results

The link does nothing and does not go anywhere.

Body:
EDIT: I added the fragment

You should not link to ./products.component.html as it does not exist at runtime (in the browser).

you should link to a route using routerLink

 <a routerLink="/product" fragment="backToTopBtn">services</a>

check angular docs Routing and navigation


问:
How to get subdomain inside RouteServiceProvider map() method while phpunit testing?
Is there a way to get the subdomain while running phpunit test in Laravel?

And more specific in this method:

app/Providers/RouteServiceProvider.php

```<code>/**
 * Define the routes for the application.
 *
 * @return void
 */
public function map()
{
    $this->mapApiRoutes();
    $this->mapWebRoutes();

    // inside here get subdomain while running a phpunit test??
</code>```

So if I make some dummy test like this:

```<code>/** @test */
public function user_can_see_welcome_page()
{
    $response = $this->call('GET', 'https://subdomain.domain.com');

    $response->assertStatus(200);
}
</code>```

I want to get the subdomain inside that map() method of RouteServiceProvider

答:
In order to change the domain you can add it to the phpunit.xml to set it globally:

```<code><php>
    <env name="APP_URL" value="https://subdomain.domain.com"/>
</php>
</code>```

But discussing your problem in the comments, this is the actual solution to your problem:

Multiple route files:

You could split each subdomain in its own map method and route file and register them in your RouteServiceProvider.

for each subdomain:

```<code>protected function mapSubDomainRoutes()
{
    Route::group([
        'middleware' => 'web',
        'domain' => 'subdomain.domain.com',
        'namespace' => $this->namespace,
    ], function () {
        require base_path('routes/subdomain.domain.php');
    });
}
</code>```

Single route file:

Or if you have everything inside one route file you can wrap the routes inside a group:

```<code>Route::group(['domain' => ['subdomain.domain.com']], function () {
    // domain specific routes
});
</code>```

Body:
Is there a way to get the subdomain while running phpunit test in Laravel?

And more specific in this method:

app/Providers/RouteServiceProvider.php

/**
 * Define the routes for the application.
 *
 * @return void
 */
public function map()
{
    $this->mapApiRoutes();
    $this->mapWebRoutes();

    // inside here get subdomain while running a phpunit test??

So if I make some dummy test like this:

/** @test */
public function user_can_see_welcome_page()
{
    $response = $this->call('GET', 'https://subdomain.domain.com');

    $response->assertStatus(200);
}

I want to get the subdomain inside that map() method of RouteServiceProvider

Body:
In order to change the domain you can add it to the phpunit.xml to set it globally:

<php>
    <env name="APP_URL" value="https://subdomain.domain.com"/>
</php>

But discussing your problem in the comments, this is the actual solution to your problem:

Multiple route files:

You could split each subdomain in its own map method and route file and register them in your RouteServiceProvider.

for each subdomain:

protected function mapSubDomainRoutes()
{
    Route::group([
        'middleware' => 'web',
        'domain' => 'subdomain.domain.com',
        'namespace' => $this->namespace,
    ], function () {
        require base_path('routes/subdomain.domain.php');
    });
}

Single route file:

Or if you have everything inside one route file you can wrap the routes inside a group:

Route::group(['domain' => ['subdomain.domain.com']], function () {
    // domain specific routes
});


问:
Why does a numpy array have 96 bytes of overhead?
If I take a simply and empty numpy array i can see it has 96 bytes of overhead,

```<code>>>> sys.getsizeof( np.array([]) )
96
</code>```

What is that 96 bytes storing? Where in the C source for numpy or Python 3 (cpython) is this set up?

答:
Array is present in C sources in numpy/core/include/numpy/ndarraytypes.h

See: https://github.com/numpy/numpy/blob/master/numpy/core/include/numpy/ndarraytypes.h

Looks like it has several pointers, number of dimensions and PyObject_HEAD, which all may in total count to number of bytes you see.

/*
 * The main array object structure.
 */
/* This struct will be moved to a private header in a future release */
typedef struct tagPyArrayObject_fields {
    PyObject_HEAD
    /* Pointer to the raw data buffer */
    char *data;
    /* The number of dimensions, also called 'ndim' */
    int nd;
    /* The size in each dimension, also called 'shape' */
    npy_intp *dimensions;
    /*
     * Number of bytes to jump to get to the
     * next element in each dimension
     */
    npy_intp *strides;

    PyObject *base;
    /* Pointer to type structure */
    PyArray_Descr *descr;
    /* Flags describing array -- see below */
    int flags;
    /* For weak references */
    PyObject *weakreflist;
} PyArrayObject_fields;
```

Body:
If I take a simply and empty numpy array i can see it has 96 bytes of overhead,

>>> sys.getsizeof( np.array([]) )
96

What is that 96 bytes storing? Where in the C source for numpy or Python 3 (cpython) is this set up?


问:
Codeigniter $config['uri_protocol'] problem
I need to change  $config['uri_protocol'] from AUTO to PATH_INFO (to allow url parameters)

My problem: when I set $config['uri_protocol']="PATH_INFO"; the regular urls stop functioning and I get the homepage no matter which site page URL I click.

print_r ($_SERVER) shows that url parameters I add appear only in REQUEST_URI an not in any other $_SERVER part.

my htaccess is the standard one

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    # This is different between local host and production server!!!
    RewriteBase /

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>
</code>```

UPDATE:

I changed

```<code>RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

to
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]  to allow url params to pass. Now url params appear also in

```<code> $_SERVER

 REDIRECT_QUERY_STRING, QUERY_STRING AND REQUEST_URI
</code>```

.

The problem: I tried $config[‘uri_protocol’] with all the above options but still CI gives error 404 whenever I add URL parameters.

Note: I tried the above on 2 servers. One of them is centos5/Apache2/Plesk VPS and another one is on xampp/Vista.

答: In which case you do not want to set $config['uri_protocol'] to PATH_INFO. var_dump($_SERVER) somewhere and find which variable contains your path as you want it, then set it to that, if AUTO does not work.</p>

ContentLicense: CC BY-SA 2.5

Body:
I need to change  $config['uri_protocol'] from AUTO to PATH_INFO (to allow url parameters)

My problem: when I set $config['uri_protocol']="PATH_INFO"; the regular urls stop functioning and I get the homepage no matter which site page URL I click.

print_r ($_SERVER) shows that url parameters I add appear only in REQUEST_URI an not in any other $_SERVER part.

my htaccess is the standard one

<IfModule mod_rewrite.c>
    RewriteEngine On

    # This is different between local host and production server!!!
    RewriteBase /

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

UPDATE:

I changed

RewriteRule ^(.*)$ index.php?/$1 [L]

to
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]  to allow url params to pass. Now url params appear also in

 $_SERVER

 REDIRECT_QUERY_STRING, QUERY_STRING AND REQUEST_URI

.

The problem: I tried $config[‘uri_protocol’] with all the above options but still CI gives error 404 whenever I add URL parameters.

Note: I tried the above on 2 servers. One of them is centos5/Apache2/Plesk VPS and another one is on xampp/Vista.


问:
Collecting comments from Reddit, outputting to CSV file
I'm trying to scrape comments from a certain submission on Reddit and output them to a CSV file.

```<code>import praw
import csv

reddit = praw.Reddit(client_id='ClientID', client_secret='ClientSecret', user_agent='UserAgent')

Submission = reddit.submission(id="SubmissionID")

with open('Reddit.csv', 'w') as csvfile:
    for comment in submission.comments:
        csvfile.write(comment.body)
</code>```

The problem is that for each cell the comments seem to be randomly split up. I want each comment in its own cell. Any ideas on how to achieve this?

答:
You are importing the csv library but you are not actually utilizing it. Utilize it and your problem may go away.

https://docs.python.org/3/library/csv.html#csv.DictWriter

```<code>import csv
# ...
comment = "this string was created from your code"
# ...
with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['comment']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'comment': comment})
</code>```

Body:
I'm trying to scrape comments from a certain submission on Reddit and output them to a CSV file.

import praw
import csv

reddit = praw.Reddit(client_id='ClientID', client_secret='ClientSecret', user_agent='UserAgent')

Submission = reddit.submission(id="SubmissionID")

with open('Reddit.csv', 'w') as csvfile:
    for comment in submission.comments:
        csvfile.write(comment.body)

The problem is that for each cell the comments seem to be randomly split up. I want each comment in its own cell. Any ideas on how to achieve this?

Body:
You are importing the csv library but you are not actually utilizing it. Utilize it and your problem may go away.

https://docs.python.org/3/library/csv.html#csv.DictWriter

import csv
# ...
comment = "this string was created from your code"
# ...
with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['comment']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'comment': comment})


问:
Fail to alert input text value
I have a simple <input id="editfileFormTitleinput" type="text>. I want to alert the text within the input text field but I fail. This is what I've tried:

```<code>$('#editfileFormTitleinput').on('input', function() {
    alert($(this).attr('value'));
});
</code>```

I keep typing in the input text field things, but it only alerts undefined. How do I get the value of the input text field if not in this way?

答:
Replace attr with val. attr() will return the value of the attribute but in input there is no value attribute defined. So it will alert undefined

$('#editfileFormTitleinput').on('input', function() {
  alert($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="editfileFormTitleinput" type="text"></code>```

Title: Fail to alert input text value

Body:
I have a simple <input id="editfileFormTitleinput" type="text>. I want to alert the text within the input text field but I fail. This is what I've tried:

$('#editfileFormTitleinput').on('input', function() {
    alert($(this).attr('value'));
});

I keep typing in the input text field things, but it only alerts undefined. How do I get the value of the input text field if not in this way?

Body:
Replace attr with val. attr() will return the value of the attribute but in input there is no value attribute defined. So it will alert undefined

$('#editfileFormTitleinput').on('input', function() {
  alert($(this).val());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="editfileFormTitleinput" type="text">


问:
How can I get "if true" result from two other functions and use it in a third function?
I have a simple "if true" function where I need to get the result from two other currently working functions. I have been scouring SO and the internet to find nothing that actually works. I made two initial functions. The first one checks the date and the second checks the time. I want this third script to check to see if the other two functions resulted in true and if so, do something. The script is as follows:

$(function() {
  // attempted global variables but this did not work
  //var dateA = $('#startdate').val();
  //var dateB = $('#enddate').val();
  //var timeA = $('#starttime').val();
  //var timeB = $('#endtime').val();

  //This function appears to work
  $("#startdate, #enddate").on("change.apple", function() {
    var dateA = $('#startdate').val();
    var dateB = $('#enddate').val();

    if (((dateA).length && (dateB).length) && (dateA == dateB)) {
      alert("Apple");
      return true;
    } else {
      return false;
    }
  });

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", function() {
    var timeA = $('#starttime').val();
    var timeB = $('#endtime').val();

    if (((timeA).length && (timeB).length) && (timeA >= timeB)) {
      alert("Banana");
      return true;
    } else {
      return false;
    }
  });

  //This function does NOT work
  $("#startdate, #enddate, #starttime, #endtime").change(function() {
    if (apple() && banana()) {
      // when its true
      alert("Hello");
    } else {
      // when its false
      alert("Goodbye");
    }
  });
});
```

<pre class="lang-html prettyprint-override"><code><form>
  <fieldset>
    <ul>
      <li>
        <p><input type="text" id="startdate"></p>
      </li>

      <li>
        <p><input type="text" id="starttime" </p>
      </li>

      <li>
        <p><input type="text" id="enddate" </p>
      </li>

      <li>
        <p><input type="text" id="endtime"></p>
      </li>
    </ul>
  </fieldset>
</form>
</code>```

I cleaned up the code for this question so it can be inspected easily. I have tried using global variables but for some reason I can not get the inner function to view the external variables. I have tried to check for errors in naming and and possible incorrect placement but I can not seem to locate the problem. Can anybody assist me in getting this script to work? I am lost at this point. Thanks

答:
Just for your reference i share this instead of return boolean values send it as string

and change conditions according to your need and pass those string values into the third

condition you want

//Updated the code as per change function if you want to execute the condition
  based on length then you can get the length value before the if condition no
  need to complicate it with inside the if conditon

Try the third condition like function.To avoid the unwanted confusion make sure
  every field is compulsory

var valid_apple;
    var valid_banana;
    var dateA;
    var dateB;
    var timeA;
    var timeB;
  //This function appears to work
  $("#startdate, #enddate").on("change.apple",function() {
    dateA = $('#startdate').val().length;
    dateB = $('#enddate').val().length;

    if(dateA == dateB){
      alert("Apple");
      valid_apple ="true";
    }else{
      valid_apple ="false";
    }
  });

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", function() {
    timeA = $('#starttime').val().length;
    timeB = $('#endtime').val().length;

    if(timeA!='' && timeB!=''){
    if(timeA >= timeB){
      alert("Banana");
      valid_banana = "true";
      third_fun();
    } else {
      valid_banana = "false";
      third_fun();
    }
  }
});

  function third_fun(){
    if(valid_apple == "true" && valid_banana == "true"){
      //when its true
      alert("Hello");
    }else{
      //when its false
      alert("Goodbye");
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form>
  <fieldset>
    <ul>
      <li>
        <p><input type="text" id="startdate" placeholder="startdate"></p>
      </li>

      <li>
        <p><input type="text" id="starttime" placeholder="starttime"></p>
      </li>

      <li>
        <p><input type="text" id="enddate" placeholder="enddate"> </p>
      </li>

      <li>
        <p><input type="text" id="endtime" placeholder="endtime"></p>
      </li>
    </ul>
  </fieldset>
</form></code>```

Body:
I have a simple "if true" function where I need to get the result from two other currently working functions. I have been scouring SO and the internet to find nothing that actually works. I made two initial functions. The first one checks the date and the second checks the time. I want this third script to check to see if the other two functions resulted in true and if so, do something. The script is as follows:

$(function() {
  // attempted global variables but this did not work
  //var dateA = $('#startdate').val();
  //var dateB = $('#enddate').val();
  //var timeA = $('#starttime').val();
  //var timeB = $('#endtime').val();

  //This function appears to work
  $("#startdate, #enddate").on("change.apple", function() {
    var dateA = $('#startdate').val();
    var dateB = $('#enddate').val();

    if (((dateA).length && (dateB).length) && (dateA == dateB)) {
      alert("Apple");
      return true;
    } else {
      return false;
    }
  });

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", function() {
    var timeA = $('#starttime').val();
    var timeB = $('#endtime').val();

    if (((timeA).length && (timeB).length) && (timeA >= timeB)) {
      alert("Banana");
      return true;
    } else {
      return false;
    }
  });

  //This function does NOT work
  $("#startdate, #enddate, #starttime, #endtime").change(function() {
    if (apple() && banana()) {
      // when its true
      alert("Hello");
    } else {
      // when its false
      alert("Goodbye");
    }
  });
});

<form>
  <fieldset>

<input type="text" id="startdate">

<input type="text" id="starttime"

<input type="text" id="enddate"

<input type="text" id="endtime">

  </fieldset>
</form>

I cleaned up the code for this question so it can be inspected easily. I have tried using global variables but for some reason I can not get the inner function to view the external variables. I have tried to check for errors in naming and and possible incorrect placement but I can not seem to locate the problem. Can anybody assist me in getting this script to work? I am lost at this point. Thanks

Body:
Just for your reference i share this instead of return boolean values send it as string

and change conditions according to your need and pass those string values into the third

condition you want

//Updated the code as per change function if you want to execute the condition
  based on length then you can get the length value before the if condition no
  need to complicate it with inside the if conditon

Try the third condition like function.To avoid the unwanted confusion make sure
  every field is compulsory

var valid_apple;
    var valid_banana;
    var dateA;
    var dateB;
    var timeA;
    var timeB;
  //This function appears to work
  $("#startdate, #enddate").on("change.apple",function() {
    dateA = $('#startdate').val().length;
    dateB = $('#enddate').val().length;

    if(dateA == dateB){
      alert("Apple");
      valid_apple ="true";
    }else{
      valid_apple ="false";
    }
  });

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", function() {
    timeA = $('#starttime').val().length;
    timeB = $('#endtime').val().length;

    if(timeA!='' && timeB!=''){
    if(timeA >= timeB){
      alert("Banana");
      valid_banana = "true";
      third_fun();
    } else {
      valid_banana = "false";
      third_fun();
    }
  }
});

  function third_fun(){
    if(valid_apple == "true" && valid_banana == "true"){
      //when its true
      alert("Hello");
    }else{
      //when its false
      alert("Goodbye");
    }
  }

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form>
  <fieldset>
    <ul>
      <li>
        <p><input type="text" id="startdate" placeholder="startdate"></p>
      </li>

      <li>
        <p><input type="text" id="starttime" placeholder="starttime"></p>
      </li>

      <li>
        <p><input type="text" id="enddate" placeholder="enddate"> </p>
      </li>

      <li>
        <p><input type="text" id="endtime" placeholder="endtime"></p>
      </li>
    </ul>
  </fieldset>
</form>


问:
How to compare array of objects using angular8 using reactive forms
i have used reactive forms, and the values are getting assigned to the html and the reactive forms is due to the array of object. So, what ever action i perform there must be used for comparing objects with the existing object. So i have used one array of object comparison method. But here the previous value is also getting binded to the new value which has been assigned to the form.

I want the newly edited value and the old value as seperate so that i can compare if the object proerty values are diffrent then i can enable for save.

DEMO:
DEMO

TS:

```<code>saveDetails() {
 this.objectsAreSame(this.agentDetailsList, this.detailsToggle)
      console.log(this.agentDetailsList);
      console.log(this.detailsToggle);
      console.log(this.objectsAreSame,"this.objectsAreSame")
    }

      objectsAreSame(a1, a2) {
    for (var i = 0, len = a1.length; i < len; i++) {
      for (var j = 0, len = a2.length; j < len-1; j++) {
          if (a1[i].boolValue == a2[j].boolValue) {
              return false
          } else {
            return true
          }
      }
  }
}
</code>```

FORM:

```<code>  private settingsInfoForm() {
    if (!this.agentDetailsList) {
      // Add
      this.agentSettingsInfoForm = this.FB.group({

        agentToogles: this.FB.array([this.detailsToggle]),
      });
      // this.authService.setDetailsData(this.agentSettingsInfoForm);
    } else {
      // Edit
      if (this.agentDetailsList) {
       this.detailsToggle = this.agentDetailsList
       this.agentSettingsInfoForm = this.FB.group({
          agentToogles: this.FB.array([this.detailsToggle]),
      })
      }
        let settingsInfo = this.agentSettingsInfoForm.valueChanges.subscribe(data => {
          this.formEdit = true;
          console.log('agentSettingsInfoForm', this.formEdit)
        })
}
</code>```

答:
You can use the Array.prototype.reduce function to compare the objects. It cycles through all the elements of the first array and starts with an initial value of true. If the item with the current index exist in the second array then it returns the overlap of all previous comparisons and the current elements at index. If it does not exist, then it returns false. Once one value is false the result is false.

compare(
  array1.map(item => item.boolValue),
  array2.map(item => item.boolValue)
);

function compare(arr1: Array<boolean>, arr2: Array<boolean>) {
  return arr1.reduce((acc, cur, index) => acc && cur === arr2[index], true);
}
```

Body:
i have used reactive forms, and the values are getting assigned to the html and the reactive forms is due to the array of object. So, what ever action i perform there must be used for comparing objects with the existing object. So i have used one array of object comparison method. But here the previous value is also getting binded to the new value which has been assigned to the form.

I want the newly edited value and the old value as seperate so that i can compare if the object proerty values are diffrent then i can enable for save.

DEMO:
DEMO

TS:

saveDetails() {
 this.objectsAreSame(this.agentDetailsList, this.detailsToggle)
      console.log(this.agentDetailsList);
      console.log(this.detailsToggle);
      console.log(this.objectsAreSame,"this.objectsAreSame")
    }

      objectsAreSame(a1, a2) {
    for (var i = 0, len = a1.length; i < len; i++) {
      for (var j = 0, len = a2.length; j < len-1; j++) {
          if (a1[i].boolValue == a2[j].boolValue) {
              return false
          } else {
            return true
          }
      }
  }
}

FORM:

  private settingsInfoForm() {
    if (!this.agentDetailsList) {
      // Add
      this.agentSettingsInfoForm = this.FB.group({

        agentToogles: this.FB.array([this.detailsToggle]),
      });
      // this.authService.setDetailsData(this.agentSettingsInfoForm);
    } else {
      // Edit
      if (this.agentDetailsList) {
       this.detailsToggle = this.agentDetailsList
       this.agentSettingsInfoForm = this.FB.group({
          agentToogles: this.FB.array([this.detailsToggle]),
      })
      }
        let settingsInfo = this.agentSettingsInfoForm.valueChanges.subscribe(data => {
          this.formEdit = true;
          console.log('agentSettingsInfoForm', this.formEdit)
        })
}


问:
Character encoding
For this piece of code:

```<code>String content = String.Empty;
ListenerStateObject state = (ListenerStateObject)ar.AsyncState;
Socket handler = state.workSocket;

int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
   state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

   content = state.sb.ToString();
   ...
</code>```

I'm geting 'Ol?' instead of 'Olá'

What's wrong with it?

答: Are you sure that the stream is actually utf-8 encoded? Try inspecting the raw bytes in the buffer before encoding (there should be 4) and see what the actual byte values are.</p>

Title: Character encoding

Body:
For this piece of code:

String content = String.Empty;
ListenerStateObject state = (ListenerStateObject)ar.AsyncState;
Socket handler = state.workSocket;

int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
   state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

   content = state.sb.ToString();
   ...

I'm geting 'Ol?' instead of 'Olá'

What's wrong with it?


问:
Clang doesn't compile code but gcc and msvc compiled it
I don't understand what's the problem: either in my code or in the compiler (less possible). There is a piece of code like this:

```<code>#include <iostream>
#include <type_traits>
#include <set>

template<typename T, typename = void>
struct TestA: std::false_type {};

template<typename T>
struct TestA<T, std::void_t<typename T::reverse_iterator>> : std::true_type {};

template<typename T>
struct TestA<T, std::void_t<typename T::dummy_iterator>> : std::true_type {};

int main()
{
    std::cout << TestA<std::set<int>>::value;
}
</code>```

Both GCC and MSVC compile it. I tested it on godbolt with different version of GCC and MSVC 17(local) and 19. Here is a link: https://godbolt.org/z/Enfm6L.

But Clang doesn't compile it and emits an error:

redefinition of `'TestA<T, std::void_t<typename T::dummy_iterator> >'`
```

And I'm interested - maybe there is some part of the  standard where this piece of code is incorrect or maybe something else.

答:
This is very likely related to CWG 1558.

The treatment of unused arguments in an alias template specialization
  is not specified by the current wording of 17.6.7 [temp.alias]. For
  example:

```<code>  #include <iostream>

  template <class T, class...>
    using first_of = T;

  template <class T>
    first_of<void, typename T::type> f(int)
      { std::cout << "1\n"; }

  template <class T>
    void f(...)
      { std::cout << "2\n"; }

  struct X { typedef void type; };

  int main() {
    f<X>(0);
    f<int>(0);
  }
</code>```

Is the reference to first_of with T being int
  equivalent to simply void, or is it a substitution failure?

It's a defect that was since addressed, but if the version of Clang you used  doesn't implement the fix yet, it may still consider both specializations as simply defining the second argument as void, and not doing the whole substitution failure spiel. The workaround is to not use a plain alias std::void_t, but instead a slightly more complex version

```<code>template <typename...> struct voider { using type = void; };
template <typename... T> using my_void_t = typename voider<T...>::type;
</code>```

For a class template (which is what the alias now stands for), the substitution failure is defined. Plugging that into your example appeases Clang https://godbolt.org/z/VnkwsM.

Body:
I don't understand what's the problem: either in my code or in the compiler (less possible). There is a piece of code like this:

#include <iostream>
#include <type_traits>
#include <set>

template<typename T, typename = void>
struct TestA: std::false_type {};

template<typename T>
struct TestA<T, std::void_t<typename T::reverse_iterator>> : std::true_type {};

template<typename T>
struct TestA<T, std::void_t<typename T::dummy_iterator>> : std::true_type {};

int main()
{
    std::cout << TestA<std::set<int>>::value;
}

Both GCC and MSVC compile it. I tested it on godbolt with different version of GCC and MSVC 17(local) and 19. Here is a link: https://godbolt.org/z/Enfm6L.

But Clang doesn't compile it and emits an error:

redefinition of `'TestA<T, std::void_t<typename T::dummy_iterator> >'`

And I'm interested - maybe there is some part of the  standard where this piece of code is incorrect or maybe something else.

Body:
This is very likely related to CWG 1558.

The treatment of unused arguments in an alias template specialization
  is not specified by the current wording of 17.6.7 [temp.alias]. For
  example:

  #include <iostream>

  template <class T, class...>
    using first_of = T;

  template <class T>
    first_of<void, typename T::type> f(int)
      { std::cout << "1\n"; }

  template <class T>
    void f(...)
      { std::cout << "2\n"; }

  struct X { typedef void type; };

  int main() {
    f<X>(0);
    f<int>(0);
  }

Is the reference to first_of with T being int
  equivalent to simply void, or is it a substitution failure?

It's a defect that was since addressed, but if the version of Clang you used  doesn't implement the fix yet, it may still consider both specializations as simply defining the second argument as void, and not doing the whole substitution failure spiel. The workaround is to not use a plain alias std::void_t, but instead a slightly more complex version

template <typename...> struct voider { using type = void; };
template <typename... T> using my_void_t = typename voider<T...>::type;

For a class template (which is what the alias now stands for), the substitution failure is defined. Plugging that into your example appeases Clang https://godbolt.org/z/VnkwsM.


问:
unbounded field in crystal report by pass parameter at runtime
I have a report in crystal report.
In that report, I need to set the field to 'Go' if the value is 0, and set the field to 'NoGo' if the value is 1.

I have created an unbound field string and write formula as below:

```<code>if {?idline}=1 and tonumber({bevarage;1.torque})=0 then {@UnboundString2}='Go'
else if {?idline}=1 and tonumber({bevarage;1.torque})=1 then {@UnboundString2}='NoGo'
</code>```

but this is not working and always returns an empty string from unbounded field.
Please help me to fix it.

答:
Assignment operator in Crystal is := rather than =

Why not simply create a formula that depends on the parameter?

Body:
I have a report in crystal report.
In that report, I need to set the field to 'Go' if the value is 0, and set the field to 'NoGo' if the value is 1.

I have created an unbound field string and write formula as below:

if {?idline}=1 and tonumber({bevarage;1.torque})=0 then {@UnboundString2}='Go'
else if {?idline}=1 and tonumber({bevarage;1.torque})=1 then {@UnboundString2}='NoGo'

but this is not working and always returns an empty string from unbounded field.
Please help me to fix it.


问:
How to output the result of a chain of commands for a given input with bash
In reference to this question I still struggle the following single-liner to work

```<code>kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done
</code>```

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

```<code>bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

</code>```

Same results with a slightly different approach:

```<code>kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done
</code>```

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

```<code>do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;
</code>```

or

```<code>$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh
</code>```

答:
With your suggestion I actually could achieve what I intended to do</p>

```<code>kubectl get ns | awk '/Term/ { print $1 }' | while IFS= read -r line; do
   ~/bin/kill-kube-ns.sh $line
done
Killed namespace: configmap-4500
Killed namespace: configmap-5062
Killed namespace: configmap-5526
Killed namespace: configmap-5817
Killed namespace: configmap-6143
</code>```

Body:
In reference to this question I still struggle the following single-liner to work

kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

Same results with a slightly different approach:

kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;

or

$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh

Body:
With your suggestion I actually could achieve what I intended to do

kubectl get ns | awk '/Term/ { print $1 }' | while IFS= read -r line; do
   ~/bin/kill-kube-ns.sh $line
done
Killed namespace: configmap-4500
Killed namespace: configmap-5062
Killed namespace: configmap-5526
Killed namespace: configmap-5817
Killed namespace: configmap-6143


问:
Data not available error in vlookup: don't know what to do
=VLOOKUP("MA",$M$3:$U$9,3)

The M3:U9 refers to the table here:

It keeps saying data not available, but I can't figure out why??

答:
Does your "MA" under "region" have a space after it? If you're getting an error it seems it's not actually "MA" in that box.

Also add a 0 to the end condition to make it an exact match;

=VLOOKUP("MA",$M$3:$U$9,3,0)


问:
How to redirect to a new page from a function in React?
Right now I have this function in react and I am using it to go back to login and also to check reset the localStorage value for which I am using the function and not  since using that I cannot reset local storage value. The function is below:-

```<code>logout(){
    localStorage.clear();
    console.log("cliasdk");
    return(
        <Redirect to="/login"/>
    )
  }
</code>```

This gets executed on clicking a div but I am not able to go to the /login page.How to do it?

答:
Try this </p>

```<code>
import React from "react";
const createHistory = require("history").createBrowserHistory;

class Logout extends React.Component {
    constructor(props) {
        super(props);
        let history = createHistory();
        history.push("/login");
        let pathUrl = window.location.href;
        window.location.href = pathUrl;

    }

    render() {

        return (
            <div>
            </div>
        );
    }
}

export default Logout;
</code>```

Body:
Right now I have this function in react and I am using it to go back to login and also to check reset the localStorage value for which I am using the function and not  since using that I cannot reset local storage value. The function is below:-

logout(){
    localStorage.clear();
    console.log("cliasdk");
    return(
        <Redirect to="/login"/>
    )
  }

This gets executed on clicking a div but I am not able to go to the /login page.How to do it?

Body:
Try this

import React from "react";
const createHistory = require("history").createBrowserHistory;

class Logout extends React.Component {
    constructor(props) {
        super(props);
        let history = createHistory();
        history.push("/login");
        let pathUrl = window.location.href;
        window.location.href = pathUrl;

    }

    render() {

        return (
            <div>
            </div>
        );
    }
}

export default Logout;


问:
Metrics for spring boot rest api
I have a spring boot app with some REST APIs. I would like to collect usage metrics on these APIs. Metrics would be like how many times did a user hit the service in a time period. The user id is available in request header. Is there any framework that will help me with this reducing the boiler plate? Will splunk help?</p>

答:
In our e-commerce project we use the DropWizard metrics:

```<code>https://github.com/dropwizard/metrics
https://mvnrepository.com/artifact/io.dropwizard.metrics/metrics-core
https://mvnrepository.com/artifact/io.dropwizard.metrics/metrics-healthchecks
</code>```

With dropwizard you have timers, counters, meters, gauges, histograms, etc...

Getting started:
    https://metrics.dropwizard.io/3.1.0/getting-started/

Title: Metrics for spring boot rest api

Body:
In our e-commerce project we use the DropWizard metrics:

https://github.com/dropwizard/metrics
https://mvnrepository.com/artifact/io.dropwizard.metrics/metrics-core
https://mvnrepository.com/artifact/io.dropwizard.metrics/metrics-healthchecks

With dropwizard you have timers, counters, meters, gauges, histograms, etc...

Getting started:
    https://metrics.dropwizard.io/3.1.0/getting-started/


问:
Mysql sync on Work and Home computers
I have two Windows 7 systems located in two different locations - work and home, with XAMPP running on both of them. I would like to be able to sync the mysql databases located on the machines. The problem is that both the machines do not stay connnected to the internet continously and do not have dedicated IPs.

I thought of using some cloud hosting service to share the "data" folder in mysql. But for some reason, the tables for the db are not showing up in System #2, thought it said DB(3) - 3 being the number of tables in the database. In this case, i didn't sync the whole of data folder, but the folder of a particular database. Not sure if this is a way of doing it.

Is there a better method of syncing both the databases. Please note that I only work on both the machines and update the database only in one location at a time. So the issue of conflicting records won't occur. I just would like both the systems updated with the same data at the end of the day.

答: I don't know how big your DB is but you could just use an external hard drive as your MySQL path.</p>

Title: Mysql sync on Work and Home computers


问:
Building GCC-Ada, Syntax error compiling s-excmac.adb with very old gnatmake
I'm trying to update our 20-year old Ada compiler, however you need an Ada-compiler to build some parts of GCC+Ada (9.2.0).

The gnatmake is circa 2000, and it's possibly sub-calling GCC 2.8.1.  Sigh.

I have already successfully built several Ada parts of GCC, but this libgnat/ file eludes me:

Compiling libgnat/s-excmac.adb:

```<code>$ gnatmake s-excmac.adb
gcc -c -gnatpg s-excmac.adb
s-excmac.ads:134:44: identifier expected
gnatmake: "s-excmac.adb" compilation error
</code>```

So the problematic line in s-excmac.ads is:

```<code>   type GCC_Exception_Access is access all Unwind_Exception;
   --  Pointer to a GCC exception

   procedure Unwind_DeleteException (Excp : not null GCC_Exception_Access );  -- <-- THIS ONE!

   pragma Import (C, Unwind_DeleteException, "_Unwind_DeleteException");

   --  Procedure to free any GCC exception
</code>```

I don't understand what is wrong with this code.  Is there some turn-of-the-century Ada syntax replacement I can use to get this part of GCC-Ada compiled?

I'm a bit of an Ada NOOB, so please be gentle.

EDIT: Seems like trying to "repair" the s-excmac.adb / s-excmac.ads is a fool's errand.  The path of lesser resistance is to download a pre-built compiler, and start building the later GCC from that.

答: I guess, building libgnat is the latest step. I mean you need to build "new-gcc" using old one, and then with "new-gcc" you will build libgnat. In this case you won't get this error.

Body:
I'm trying to update our 20-year old Ada compiler, however you need an Ada-compiler to build some parts of GCC+Ada (9.2.0).

The gnatmake is circa 2000, and it's possibly sub-calling GCC 2.8.1.  Sigh.

I have already successfully built several Ada parts of GCC, but this libgnat/ file eludes me:

Compiling libgnat/s-excmac.adb:

$ gnatmake s-excmac.adb
gcc -c -gnatpg s-excmac.adb
s-excmac.ads:134:44: identifier expected
gnatmake: "s-excmac.adb" compilation error

So the problematic line in s-excmac.ads is:

   type GCC_Exception_Access is access all Unwind_Exception;
   --  Pointer to a GCC exception

   procedure Unwind_DeleteException (Excp : not null GCC_Exception_Access );  -- <-- THIS ONE!

   pragma Import (C, Unwind_DeleteException, "_Unwind_DeleteException");

   --  Procedure to free any GCC exception

I don't understand what is wrong with this code.  Is there some turn-of-the-century Ada syntax replacement I can use to get this part of GCC-Ada compiled?

I'm a bit of an Ada NOOB, so please be gentle.

EDIT: Seems like trying to "repair" the s-excmac.adb / s-excmac.ads is a fool's errand.  The path of lesser resistance is to download a pre-built compiler, and start building the later GCC from that.