问:
Get ordered kmeans cluster labels
Say I have a data set x and do the following kmeans cluster:

```<code>fit <- kmeans(x,2)
</code>```

My question is in regards to the output of fit$cluster: I know that it will give me a vector of integers (from 1:k) indicating the cluster to which each point is allocated. Instead, is there a way to have the clusters be labeled 1,2, etc... in order of decreasing numerical value of their center?

For example: If x=c(1.5,1.4,1.45,.2,.3,.3) , then fit$cluster should result in (1,1,1,2,2,2) but not result in (2,2,2,1,1,1)

Similarly, if x=c(1.5,.2,1.45,1.4,.3,.3) then fit$cluster should return (1,2,1,1,2,2), instead of (2,1,2,2,1,1)

Right now, fit$cluster seems to label the cluster numbers randomly. I've looked into documentation but haven't been able to find anything. Please let me know if you can help!

答:
I had a similar problem. I had a vector of ages that I wanted to separate into 5 factor groups based on a logical ordinal set. I did the following:

I ran the k-means function:

```<code>k5 <- kmeans(all_data$age, centers = 5, nstart = 25)
</code>```

I built a data frame of the k-means indexes and centres; then arranged it by centre value.

```<code>kmeans_index <- as.numeric(rownames(k5$centers))
k_means_centres <- as.numeric(k5$centers)
k_means_df <- data_frame(index=kmeans_index, centres=k_means_centres)
k_means_df <- k_means_df %>%
    arrange(centres)
</code>```

Now that the centres are in the df in ascending order, I created my 5 element factor list and bound it to the data frame:

```<code>factors <- c("very_young", "young", "middle_age", "old", "very_old")
k_means_df <- cbind(k_means_df, factors)
</code>```

Looks like this:

```<code>> k_means_df
  index  centres    factors
1     2 23.33770 very_young
2     5 39.15239      young
3     1 55.31727 middle_age
4     4 67.49422        old
5     3 79.38353   very_old
</code>```

I saved my cluster values in a data frame and created a dummy factor column:

```<code>cluster_vals <- data_frame(cluster=k5$cluster, factor=NA)
</code>```

Finally, I iterated through the factor options in k_means_df and replaced the cluster value with my factor/character value within the cluster_vals data frame:

```<code>for (i in 1:nrow(k_means_df))
  {
    index_val <- k_means_df$index[i]
    factor_val <- as.character(k_means_df$factors[i])

    cluster_vals <- cluster_vals %>%
      mutate(factor=replace(factor, cluster==index_val, factor_val))
  }
</code>```

Voila; I now have a vector of factors/characters that were applied based on their ordinal logic to the randomly created cluster vector.

```<code># A tibble: 3,163 x 2
   cluster factor
     <int> <chr>
 1       4 old
 2       2 very_young
 3       2 very_young
 4       2 very_young
 5       3 very_old
 6       3 very_old
 7       4 old
 8       4 old
 9       2 very_young
10       5 young
# ... with 3,153 more rows
</code>```

Hope this helps.

Title: Get ordered kmeans cluster labels

Body:
Say I have a data set x and do the following kmeans cluster:

fit <- kmeans(x,2)

My question is in regards to the output of fit$cluster: I know that it will give me a vector of integers (from 1:k) indicating the cluster to which each point is allocated. Instead, is there a way to have the clusters be labeled 1,2, etc... in order of decreasing numerical value of their center?

For example: If x=c(1.5,1.4,1.45,.2,.3,.3) , then fit$cluster should result in (1,1,1,2,2,2) but not result in (2,2,2,1,1,1)

Similarly, if x=c(1.5,.2,1.45,1.4,.3,.3) then fit$cluster should return (1,2,1,1,2,2), instead of (2,1,2,2,1,1)

Right now, fit$cluster seems to label the cluster numbers randomly. I've looked into documentation but haven't been able to find anything. Please let me know if you can help!

Body:
I had a similar problem. I had a vector of ages that I wanted to separate into 5 factor groups based on a logical ordinal set. I did the following:

I ran the k-means function:

k5 <- kmeans(all_data$age, centers = 5, nstart = 25)

I built a data frame of the k-means indexes and centres; then arranged it by centre value.

kmeans_index <- as.numeric(rownames(k5$centers))
k_means_centres <- as.numeric(k5$centers)
k_means_df <- data_frame(index=kmeans_index, centres=k_means_centres)
k_means_df <- k_means_df %>%
    arrange(centres)

Now that the centres are in the df in ascending order, I created my 5 element factor list and bound it to the data frame:

factors <- c("very_young", "young", "middle_age", "old", "very_old")
k_means_df <- cbind(k_means_df, factors)

Looks like this:

> k_means_df
  index  centres    factors
1     2 23.33770 very_young
2     5 39.15239      young
3     1 55.31727 middle_age
4     4 67.49422        old
5     3 79.38353   very_old

I saved my cluster values in a data frame and created a dummy factor column:

cluster_vals <- data_frame(cluster=k5$cluster, factor=NA)

Finally, I iterated through the factor options in k_means_df and replaced the cluster value with my factor/character value within the cluster_vals data frame:

for (i in 1:nrow(k_means_df))
  {
    index_val <- k_means_df$index[i]
    factor_val <- as.character(k_means_df$factors[i])

    cluster_vals <- cluster_vals %>%
      mutate(factor=replace(factor, cluster==index_val, factor_val))
  }

Voila; I now have a vector of factors/characters that were applied based on their ordinal logic to the randomly created cluster vector.

# A tibble: 3,163 x 2
   cluster factor
     <int> <chr>
 1       4 old
 2       2 very_young
 3       2 very_young
 4       2 very_young
 5       3 very_old
 6       3 very_old
 7       4 old
 8       4 old
 9       2 very_young
10       5 young
# ... with 3,153 more rows

Hope this helps.


来源: stackexchange

问:
WSO2 enterprise integrator - datasource
do you know where is save settings about datasource from wso2 EI?
i create datasource on GUI in wso2 but I can't find record on server.
Thanks</p>

答:
You can find the dataservice file under,

EI-Home/repository/deployment/server/dataservices

Datasources added from Management Console will be stored in registry,

/_system/config/repository/components/org.wso2.carbon.ndatasource/

ContentLicense: CC BY-SA 4.0

Title: WSO2 enterprise integrator - datasource


问:
ControlValueAccessor with multiple formControl in child component
I have multiple formcontrols in the child component, how to apply validators in the child component, So that original form will become invalid. It would be ideal to implement it with ControlValueAccessor but want to start with simple @input form group.

@Component({
  selector: 'my-child',
  template: `

Child

    <input formControlName="firstName">
    <input formControlName="lastName">

  `
})

export class Child {
  @Input()
  childForm: FormGroup;
}
```

http://plnkr.co/edit/K1xAak4tlUKtZmOV1CAQ

答:
What you want to do can be achieved more easily without implementing ControlValueAccessor.
Instead, you can simply set the viewProviders in the child component to use the existing parent NgForm as the ControlContainer.

Then, there's no need to pass the form/formGroup as an input parameter to the child component as the form controls will automatically be part of the parent's form.

child.component.ts:

@Component({
    selector: 'child',
    templateUrl: './child.component.html',
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm}]
})
export class Child {
    @Input() firstName;
    @Input() lastName;
}
```
<p>child.component.html:</p>
<pre class="lang-html prettyprint-override"><code><h1>Child</h1>
<div>
    <input [(ngModel)]="firstName" name="firstname">
    <input [(ngModel)]="lastName" name="lastname">
</div>
</code>```

parent.component.html:

<form #personalForm="ngForm" name="personalForm">
    <child [firstName]="firstName" [lastName]="lastName"></child>
</form>
```

Body:
I have multiple formcontrols in the child component, how to apply validators in the child component, So that original form will become invalid. It would be ideal to implement it with ControlValueAccessor but want to start with simple @input form group.

@Component({
  selector: 'my-child',
  template: `

Child

    <input formControlName="firstName">
    <input formControlName="lastName">

  `
})

export class Child {
  @Input()
  childForm: FormGroup;
}

http://plnkr.co/edit/K1xAak4tlUKtZmOV1CAQ

Body:
What you want to do can be achieved more easily without implementing ControlValueAccessor.
Instead, you can simply set the viewProviders in the child component to use the existing parent NgForm as the ControlContainer.

Then, there's no need to pass the form/formGroup as an input parameter to the child component as the form controls will automatically be part of the parent's form.

child.component.ts:

@Component({
    selector: 'child',
    templateUrl: './child.component.html',
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm}]
})
export class Child {
    @Input() firstName;
    @Input() lastName;
}

child.component.html:

<h1>Child</h1>
<div>
    <input [(ngModel)]="firstName" name="firstname">
    <input [(ngModel)]="lastName" name="lastname">
</div>

parent.component.html:

<form #personalForm="ngForm" name="personalForm">
    <child [firstName]="firstName" [lastName]="lastName"></child>
</form>


问:
How to replace 0 values in a numpy array to other values based on column range?
I have a dataset in the following format:

[[ 226      600   3.33    915.     92.6    98.6 ]
  [ 217      700   3.34    640.    93.7    98.5 ]
  [ 213      900   3.35    662.    88.8    96.  ]
  ...
  [ 108      600    2.31   291.     64.     70.4 ]
  [ 125      800    3.36   1094.    65.5    84.1 ]
  [ 109      400    2.44   941.     52.3    68.7 ]]

Each column is a separate criteria that has its own value range. How can I impute values that are 0 to a value that is more than zero based on its column range? In other words the worst minimal value other than 0.

I have written the following code but it can only either change the 0 to the minimal value in the column (which is of course 0) or max. The max varies by column. Thanks for your help!

```<code># Impute 0 values -- give them the worst value for that column

I, J = np.nonzero(scores == 0)
scores[I,J] = scores.min(axis=0)[J] # can only do min or max
</code>```

答:
One way would be to use a masked array to find the minimum value along the columns masking those that are <=0. And replace the 0s in the array with the corresponding minimum using np.where:

```<code>min_gt0 = np.ma.array(r, mask=r<=0).min(0)
np.where(r == 0, min_gt0, r)
</code>```

Here's an example:

```<code>r = np.random.randint(0,5,(5,5))

print(r)
array([[2, 1, 3, 0, 4],
       [0, 4, 4, 2, 2],
       [4, 0, 0, 0, 1],
       [1, 2, 2, 2, 2],
       [2, 0, 4, 4, 2]])

min_gt0 = np.ma.array(r, mask=r<=0).min(0)
np.where(r == 0, min_gt0, r)

array([[2, 1, 3, 2, 4],
       [1, 4, 4, 2, 2],
       [4, 1, 2, 2, 1],
       [1, 2, 2, 2, 2],
       [2, 1, 4, 4, 2]])
</code>```

Body:
I have a dataset in the following format:

[[ 226      600   3.33    915.     92.6    98.6 ]
  [ 217      700   3.34    640.    93.7    98.5 ]
  [ 213      900   3.35    662.    88.8    96.  ]
  ...
  [ 108      600    2.31   291.     64.     70.4 ]
  [ 125      800    3.36   1094.    65.5    84.1 ]
  [ 109      400    2.44   941.     52.3    68.7 ]]

Each column is a separate criteria that has its own value range. How can I impute values that are 0 to a value that is more than zero based on its column range? In other words the worst minimal value other than 0.

I have written the following code but it can only either change the 0 to the minimal value in the column (which is of course 0) or max. The max varies by column. Thanks for your help!

# Impute 0 values -- give them the worst value for that column

I, J = np.nonzero(scores == 0)
scores[I,J] = scores.min(axis=0)[J] # can only do min or max

Body:
One way would be to use a masked array to find the minimum value along the columns masking those that are <=0. And replace the 0s in the array with the corresponding minimum using np.where:

min_gt0 = np.ma.array(r, mask=r<=0).min(0)
np.where(r == 0, min_gt0, r)

Here's an example:

r = np.random.randint(0,5,(5,5))

print(r)
array([[2, 1, 3, 0, 4],
       [0, 4, 4, 2, 2],
       [4, 0, 0, 0, 1],
       [1, 2, 2, 2, 2],
       [2, 0, 4, 4, 2]])

min_gt0 = np.ma.array(r, mask=r<=0).min(0)
np.where(r == 0, min_gt0, r)

array([[2, 1, 3, 2, 4],
       [1, 4, 4, 2, 2],
       [4, 1, 2, 2, 1],
       [1, 2, 2, 2, 2],
       [2, 1, 4, 4, 2]])


问:
How do I import CSV file into a MySQL table?
I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format. I created a table called 'CSVImport' that has one field for every column of the CSV file. The CSV contains 99 columns , so this was a hard enough task in itself:

```<code>CREATE TABLE 'CSVImport' (id INT);
ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);
...
ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);
ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);
</code>```

No constraints are on the table, and all the fields hold VARCHAR(256) values, except the columns which contain counts (represented by INT), yes/no (represented by BIT), prices (represented by DECIMAL), and text blurbs (represented by TEXT).

I tried to load data into the file:

```<code>LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;
Query OK, 2023 rows affected, 65535 warnings (0.08 sec)
Records: 2023  Deleted: 0  Skipped: 0  Warnings: 198256
SELECT * FROM CSVImport;
| NULL             | NULL        | NULL           | NULL | NULL               |
...
</code>```

The whole table is filled with NULL.

I think the problem is that the text blurbs contain more than one line, and MySQL is parsing the file as if each new line would correspond to one databazse row. I can load the file into OpenOffice without a problem.

The clientdata.csv file contains 2593 lines, and 570 records. The first line contains column names. I think it is comma delimited, and text is apparently delimited with doublequote.

UPDATE:

When in doubt, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

I added some information to the LOAD DATA statement that OpenOffice was smart enough to infer, and now it loads the correct number of records:

```<code>LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
</code>```

But still there are lots of completely NULL records, and none of the data that got loaded seems to be in the right place.

答:
How to import csv files to sql tables

Example file: Overseas_trade_index data CSV File

Steps:

Need to create table for overseas_trade_index.

Need to create columns related to csv file.

SQL Query:

```<code>( id int not null primary key auto_increment,
series_reference varchar (60),
period varchar (60),
data_value decimal(60,0),
status varchar (60),
units varchar (60),
magnitude int(60),
subject text(60),
group text(60),
series_title_1 varchar (60),
series_title_2 varchar (60),
series_title_3 varchar (60),
series_title_4 varchar (60),
series_title_5 varchar (60),
 );
</code>```

Need to connect mysql database in terminal.

```<code>=>show databases;
=>use database;
=>show tables;
</code>```

Please enter this command to import the csv data to mysql tables.

```<code>load data infile '/home/desktop/Documents/overseas.csv' into table trade_index fields terminated by ',' lines terminated by '\n' (series_reference,period,data_value,status,units,magnitude,subject,series_title1,series_title_2,series_title_3,series_title_4,series_title_5);
</code>```

Find this overseas trade index data on sqldatabase:

```<code>select * from trade_index;
</code>```

Body:
I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format. I created a table called 'CSVImport' that has one field for every column of the CSV file. The CSV contains 99 columns , so this was a hard enough task in itself:

CREATE TABLE 'CSVImport' (id INT);
ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);
...
ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);
ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);

No constraints are on the table, and all the fields hold VARCHAR(256) values, except the columns which contain counts (represented by INT), yes/no (represented by BIT), prices (represented by DECIMAL), and text blurbs (represented by TEXT).

I tried to load data into the file:

LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;
Query OK, 2023 rows affected, 65535 warnings (0.08 sec)
Records: 2023  Deleted: 0  Skipped: 0  Warnings: 198256
SELECT * FROM CSVImport;
| NULL             | NULL        | NULL           | NULL | NULL               |
...

The whole table is filled with NULL.

I think the problem is that the text blurbs contain more than one line, and MySQL is parsing the file as if each new line would correspond to one databazse row. I can load the file into OpenOffice without a problem.

The clientdata.csv file contains 2593 lines, and 570 records. The first line contains column names. I think it is comma delimited, and text is apparently delimited with doublequote.

UPDATE:

When in doubt, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

I added some information to the LOAD DATA statement that OpenOffice was smart enough to infer, and now it loads the correct number of records:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

But still there are lots of completely NULL records, and none of the data that got loaded seems to be in the right place.

Body:
How to import csv files to sql tables

Example file: Overseas_trade_index data CSV File

Steps:

Need to create table for overseas_trade_index.

Need to create columns related to csv file.

SQL Query:

( id int not null primary key auto_increment,
series_reference varchar (60),
period varchar (60),
data_value decimal(60,0),
status varchar (60),
units varchar (60),
magnitude int(60),
subject text(60),
group text(60),
series_title_1 varchar (60),
series_title_2 varchar (60),
series_title_3 varchar (60),
series_title_4 varchar (60),
series_title_5 varchar (60),
 );

Need to connect mysql database in terminal.

=>show databases;
=>use database;
=>show tables;

Please enter this command to import the csv data to mysql tables.

load data infile '/home/desktop/Documents/overseas.csv' into table trade_index fields terminated by ',' lines terminated by '\n' (series_reference,period,data_value,status,units,magnitude,subject,series_title1,series_title_2,series_title_3,series_title_4,series_title_5);

Find this overseas trade index data on sqldatabase:

select * from trade_index;


问:
Writing a generic clone method in TypeScript
In TypeScript, is there a way for a class to refer to its constructor in a way that works when it is subclassed?

```<code>abstract class Base<T> {
  constructor(readonly value: T) {}

  abstract getName(): string;

  clone() {
    const Cls = this.constructor;
    return new Cls(this.value);
  }
}
</code>```

In this snippet, Cls is given the type Function and so the compiler complains that: "Cannot use 'new' with an expression whose type lacks a call or construct signature."

答:
Typescript does not use a strict type for the constructor (it just uses Function) and since this is not a constructor, it is not callable with new.

The simple solution is to use a type assertion:

```<code>abstract class Base<T> {
    constructor(readonly value: T) { }

    abstract getName(): string;

    clone() {
        // Using polymorphic this ensures the return type is correct in derived  types
        const Cls = this.constructor as new (value: T) => this;
        return new Cls(this.value);
    }
}
</code>```

Body:
In TypeScript, is there a way for a class to refer to its constructor in a way that works when it is subclassed?

abstract class Base<T> {
  constructor(readonly value: T) {}

  abstract getName(): string;

  clone() {
    const Cls = this.constructor;
    return new Cls(this.value);
  }
}

In this snippet, Cls is given the type Function and so the compiler complains that: "Cannot use 'new' with an expression whose type lacks a call or construct signature."

Body:
Typescript does not use a strict type for the constructor (it just uses Function) and since this is not a constructor, it is not callable with new.

The simple solution is to use a type assertion:

abstract class Base<T> {
    constructor(readonly value: T) { }

    abstract getName(): string;

    clone() {
        // Using polymorphic this ensures the return type is correct in derived  types
        const Cls = this.constructor as new (value: T) => this;
        return new Cls(this.value);
    }
}


问:
Id is not getting on url of ajax
I am working on categories and its subcategories when in my code I am getting id from category but it is not able to pass into Ajax and its URL.
My code is</p>

```<code><script type="text/javascript">

    $(document).ready(function() {
        $('select[name="category"]').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                    url: "<?php echo base_url("myformAjax");?>/"+stateID,
//                    alert(url);
                    type: "GET",
                    dataType: "json",
                    success:function(data) {
                        $('select[name="subcategory"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="subcategory"]').append('<option value="'+ value.id +'">'+ value.subcategory +'</option>');
                        });
                    }
                });
            }else{
                $('select[name="subcategory"]').empty();
            }
        });
    });
</script>
</code>```

答:
you have a mistake in your code.

you are using double-quotes inside double-quotes

change this line

```<code> url: "<?php echo base_url("myformAjax");?>/"+stateID,
</code>```

to

```<code> url: "<?php echo base_url('myformAjax');?>/"+stateID,
</code>```

updated answer:

assign the php value to js variable and concat both.

```<code>var phpVal = <?php echo base_url('myformAjax');?>;
</code>```

and then

```<code>url: phpVal + "/" + stateID,
</code>```

Title: Id is not getting on url of ajax

Body:
you have a mistake in your code.

you are using double-quotes inside double-quotes

change this line

 url: "<?php echo base_url("myformAjax");?>/"+stateID,

to

 url: "<?php echo base_url('myformAjax');?>/"+stateID,

updated answer:

assign the php value to js variable and concat both.

var phpVal = <?php echo base_url('myformAjax');?>;

and then

url: phpVal + "/" + stateID,


问:
Write a function ASTERISK in C++ Programming
I did a coding that accepts an integer from the user, and output the corresponding number of asterisks. For example:

```<code>Please enter a number: 10
* * * * * * * * * *
</code>```

I must use function concept to complete the coding only. I managed to get the correct number of asterisks but the '0' at the back just won't disappear.

```<code>#include<iostream>
using namespace std;

int NUMBER, i;
int ASTERISK (int NUMBER);
int main ()

{
    cout << "Enter a number: " ;
    cin >> i ;
    cout << ASTERISK (i);
    return 0;
}

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}
</code>```

答:
This line is the cause of the problematic zero:

```<code>cout << ASTERISK (i);
</code>```

This asks to print the value returned by ASTERISK (i).

```<code>int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}
</code>```

In the definition of ASTERISK, you print a NUMBER of asterisks and return the value ANSWER which is an uninitialized integer, which happens to be zero in your case.

This is bad for two reasons:

Manipulating uninitalized values is in general undefined behavior which can have a lot of bad consequences. Really bad.

Returning a value when you don't need it makes the code harder to maintain.

As a solution, make ASTERISK return nothing:

```<code>ASTERISK (i);
// ...
void ASTERISK (int NUMBER) {
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        std::cout << "* " ;
    }
}
</code>```

Finally, you completly missed the point of scoped variable. Try and get that important concept as soon as possible by not using global variables. With a few improvements, your function would become:

```<code>void print_asteriks(int count) {
    for (int n=0 ; n<count ; ++n) {
        std::cout << "* ";
    }
}
</code>```

Body:
I did a coding that accepts an integer from the user, and output the corresponding number of asterisks. For example:

Please enter a number: 10
* * * * * * * * * *

I must use function concept to complete the coding only. I managed to get the correct number of asterisks but the '0' at the back just won't disappear.

#include<iostream>
using namespace std;

int NUMBER, i;
int ASTERISK (int NUMBER);
int main ()

{
    cout << "Enter a number: " ;
    cin >> i ;
    cout << ASTERISK (i);
    return 0;
}

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}

Body:
This line is the cause of the problematic zero:

cout << ASTERISK (i);

This asks to print the value returned by ASTERISK (i).

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}

In the definition of ASTERISK, you print a NUMBER of asterisks and return the value ANSWER which is an uninitialized integer, which happens to be zero in your case.

This is bad for two reasons:

Manipulating uninitalized values is in general undefined behavior which can have a lot of bad consequences. Really bad.

Returning a value when you don't need it makes the code harder to maintain.

As a solution, make ASTERISK return nothing:

ASTERISK (i);
// ...
void ASTERISK (int NUMBER) {
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        std::cout << "* " ;
    }
}

Finally, you completly missed the point of scoped variable. Try and get that important concept as soon as possible by not using global variables. With a few improvements, your function would become:

void print_asteriks(int count) {
    for (int n=0 ; n<count ; ++n) {
        std::cout << "* ";
    }
}


问:
Getting return values from a MySQL stored procedure in Python, using MySQLdb
I've got a stored procedure in a MySQL database that simply updates a date column and returns the previous date.  If I call this stored procedure from the MySQL client, it works fine, but when I try to call the stored procedure from Python using MySQLdb I can't seem to get it to give me the return value.

Here's the code to the stored procedure:

```<code>CREATE PROCEDURE test_stuff.get_lastpoll()
BEGIN
    DECLARE POLLTIME TIMESTAMP DEFAULT NULL;
    START TRANSACTION;

    SELECT poll_date_time
      FROM test_stuff.poll_table
      LIMIT 1
      INTO POLLTIME
    FOR UPDATE;

    IF POLLTIME IS NULL THEN
        INSERT INTO
               test_stuff.poll_table
               (poll_date_time)
        VALUES
               ( UTC_TIMESTAMP() );

        COMMIT;
        SELECT NULL as POLL_DATE_TIME;
    ELSE
        UPDATE test_stuff.poll_table SET poll_date_time = UTC_TIMESTAMP();
        COMMIT;
        SELECT DATE_FORMAT(POLLTIME, '%Y-%m-%d %H:%i:%s') as POLL_DATE_TIME;
    END IF;
END
</code>```

The code I'm using to try to call the stored procedure is similar to this:

```<code>#!/usr/bin/python

import sys
import MySQLdb

try:
    mysql = MySQLdb.connect(user=User,passwd=Passwd,db="test_stuff")
    mysql_cursor = mysql.cursor()

    results=mysql_cursor.callproc( "get_lastpoll", () )
    print results

    mysql_cursor.close()
    mysql.close()

except MySQLdb.Error, e:
    print "MySQL Error %d:  %s" % ( e.args[0], e.args[1] )
    sys.exit(1)
</code>```

I know that you can do IN and OUT parameters, but from what I can determine from the MySQLdb documentation, this isn't possible with MySQLdb.  Does anyone have any clue how I could get the results of the stored procedure?

If I run it from a SQL tool, here's the output:

```<code>POLL_DATE_TIME
-------------------
2009-02-18 22:27:07
</code>```

If I run the Python script, it returns back an empty set, like this:

```<code>()
</code>```

答:
You still have to fetch the results.

```<code>results = cursor.fetchone()
</code>```

or

```<code>results = cursor.fetchall()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've got a stored procedure in a MySQL database that simply updates a date column and returns the previous date.  If I call this stored procedure from the MySQL client, it works fine, but when I try to call the stored procedure from Python using MySQLdb I can't seem to get it to give me the return value.

Here's the code to the stored procedure:

CREATE PROCEDURE test_stuff.get_lastpoll()
BEGIN
    DECLARE POLLTIME TIMESTAMP DEFAULT NULL;
    START TRANSACTION;

    SELECT poll_date_time
      FROM test_stuff.poll_table
      LIMIT 1
      INTO POLLTIME
    FOR UPDATE;

    IF POLLTIME IS NULL THEN
        INSERT INTO
               test_stuff.poll_table
               (poll_date_time)
        VALUES
               ( UTC_TIMESTAMP() );

        COMMIT;
        SELECT NULL as POLL_DATE_TIME;
    ELSE
        UPDATE test_stuff.poll_table SET poll_date_time = UTC_TIMESTAMP();
        COMMIT;
        SELECT DATE_FORMAT(POLLTIME, '%Y-%m-%d %H:%i:%s') as POLL_DATE_TIME;
    END IF;
END

The code I'm using to try to call the stored procedure is similar to this:

#!/usr/bin/python

import sys
import MySQLdb

try:
    mysql = MySQLdb.connect(user=User,passwd=Passwd,db="test_stuff")
    mysql_cursor = mysql.cursor()

    results=mysql_cursor.callproc( "get_lastpoll", () )
    print results

    mysql_cursor.close()
    mysql.close()

except MySQLdb.Error, e:
    print "MySQL Error %d:  %s" % ( e.args[0], e.args[1] )
    sys.exit(1)

I know that you can do IN and OUT parameters, but from what I can determine from the MySQLdb documentation, this isn't possible with MySQLdb.  Does anyone have any clue how I could get the results of the stored procedure?

If I run it from a SQL tool, here's the output:

POLL_DATE_TIME
-------------------
2009-02-18 22:27:07

If I run the Python script, it returns back an empty set, like this:

()

Body:
You still have to fetch the results.

results = cursor.fetchone()

or

results = cursor.fetchall()

OwnerDisplayName: mluebke


问:
Android: Null Pointer Exception at Text View
Here is a code for which I face the Exception

```<code>public class SHOSuper extends Activity{

String officerName;
String arr[];
String[] offN;
public void onCreate(Bundle savedInstanceState) {
    try{
        super.onCreate(savedInstanceState);
        final TextView tv;
        tv=(TextView)findViewById(R.id.txt1);
        System.out.println("I AM NEW ACTIVITY");
        arr=Receiver.split(Receiver.orignal, ",");
        String value1= arr[1];
        System.out.println("Array index " + value1);
        String value2=arr[2];
        System.out.println("Array 2nd index " + value2);
        tv.setText(value1 + " At " + value2);
        officerName= arr[5];
        offN =new String[officerName.length()];
        offN=Receiver.split(officerName, "_");
    }
    catch(Exception e){
        e.printStackTrace();
    }

setContentView(R.layout.main);
  }
}
</code>```

On line tv.setText(value1 + " At " + value2); I face Null pointer Exception like this

```<code>**04-12 13:25:18.105: WARN/System.err(527): java.lang.NullPointerException
04-12 13:25:18.265: WARN/System.err(527):     at com.sho.SHOSuper.onCreate(SHOSuper.java:24)**
</code>```

Can you help me?

答:
It would appear that

```<code>tv=(TextView)findViewById(R.id.txt1);
</code>```

returns null

ContentLicense: CC BY-SA 3.0

Body:
Here is a code for which I face the Exception

public class SHOSuper extends Activity{

String officerName;
String arr[];
String[] offN;
public void onCreate(Bundle savedInstanceState) {
    try{
        super.onCreate(savedInstanceState);
        final TextView tv;
        tv=(TextView)findViewById(R.id.txt1);
        System.out.println("I AM NEW ACTIVITY");
        arr=Receiver.split(Receiver.orignal, ",");
        String value1= arr[1];
        System.out.println("Array index " + value1);
        String value2=arr[2];
        System.out.println("Array 2nd index " + value2);
        tv.setText(value1 + " At " + value2);
        officerName= arr[5];
        offN =new String[officerName.length()];
        offN=Receiver.split(officerName, "_");
    }
    catch(Exception e){
        e.printStackTrace();
    }

setContentView(R.layout.main);
  }
}

On line tv.setText(value1 + " At " + value2); I face Null pointer Exception like this

**04-12 13:25:18.105: WARN/System.err(527): java.lang.NullPointerException
04-12 13:25:18.265: WARN/System.err(527):     at com.sho.SHOSuper.onCreate(SHOSuper.java:24)**

Can you help me?

Body:
It would appear that

tv=(TextView)findViewById(R.id.txt1);

returns null


问:
Detect browser refresh in an Angular project
I want to detect when a page is refreshed using a router  in my single-page application (Angular project).

Is there an alternate way?

答:
Try this:

```<code>  this.router.events
    .pipe(filter((rs): rs is NavigationEnd => rs instanceof NavigationEnd))
    .subscribe(event => {
      if (
        event.id === 1 &&
        event.url === event.urlAfterRedirects
      ) {
          // Your code here for when the page is refreshd
      }
    })
</code>```

You will need to import

```<code>import { filter } from 'rxjs/operators'
import { Router  } from '@angular/router';
</code>```

Body:
Try this:

  this.router.events
    .pipe(filter((rs): rs is NavigationEnd => rs instanceof NavigationEnd))
    .subscribe(event => {
      if (
        event.id === 1 &&
        event.url === event.urlAfterRedirects
      ) {
          // Your code here for when the page is refreshd
      }
    })

You will need to import

import { filter } from 'rxjs/operators'
import { Router  } from '@angular/router';


问:
Error - input that isn't a symbolic tensor - Boolean
I am trying to adjust the weights of a Dense layer thanks to a binary crossentropy loss. A have created a shared layer that output for two vectors two values (encoded_value_1 and encoded_value_2). I want to create a boolean equal to 1 if the value of encoded_value_1 is superior to the value of encoded_value_2.
In order to do that I use greater via a Lambda layer. Yet, it produces an error (see below).

```<code>import keras
from keras.backend import greater
from keras.layers import Input, LSTM, Dense, Lambda, concatenate
from keras.models import Model

value_1 = Input(shape=(4,))
value_2 = Input(shape=(4,))

shared_layer = Dense(1)
encoded_value_1 = shared_layer(value_1)
encoded_value_2 = shared_layer(value_2)

x = Lambda(greater,output_shape=(1,))((encoded_value_1,encoded_value_2))
model = Model(inputs=[value_1, value_2], outputs=x)
model.compile(optimizer='adam',loss='binary_crossentropy', metrics='accuracy'])
</code>```

NB: I also tried to concatenate the two layers, I had the same error.

```<code>merged_vector = concatenate([encoded_value_1, encoded_value_2], axis=-1)
x = Lambda(greater,output_shape=(1,))((merged_vector[0],merged_vector[1]))
</code>```

ValueError: Layer lambda_4 was called with an input that isn't a symbolic tensor. Received type: . Full input: [(, )]. All inputs to the layer should be tensors.

答:
There are three points:

When the Lambda layer has more than one input, then the inputs must be passed as a list of tensors, not a tuple.

The output of greater is a bool Tensor which you need to cast to float for doing computations on it.

greater takes two inputs, so you need to wrap it inside a python lambda function to be able to use it in a Lambda layer in Keras.

Therefore, we would have:

```<code>from keras import backend as K

# ...
x = Lambda(lambda z: K.cast(K.greater(z[0], z[1]), K.floatx()),output_shape=(1,))([encoded_value_1,encoded_value_2])
</code>```

And also don't forget the missing opening bracket for metrics argument:

```<code>..., metrics=['accuracy'])
             ^
             |
             |
          missing!
</code>```

Body:
I am trying to adjust the weights of a Dense layer thanks to a binary crossentropy loss. A have created a shared layer that output for two vectors two values (encoded_value_1 and encoded_value_2). I want to create a boolean equal to 1 if the value of encoded_value_1 is superior to the value of encoded_value_2.
In order to do that I use greater via a Lambda layer. Yet, it produces an error (see below).

import keras
from keras.backend import greater
from keras.layers import Input, LSTM, Dense, Lambda, concatenate
from keras.models import Model

value_1 = Input(shape=(4,))
value_2 = Input(shape=(4,))

shared_layer = Dense(1)
encoded_value_1 = shared_layer(value_1)
encoded_value_2 = shared_layer(value_2)

x = Lambda(greater,output_shape=(1,))((encoded_value_1,encoded_value_2))
model = Model(inputs=[value_1, value_2], outputs=x)
model.compile(optimizer='adam',loss='binary_crossentropy', metrics='accuracy'])

NB: I also tried to concatenate the two layers, I had the same error.

merged_vector = concatenate([encoded_value_1, encoded_value_2], axis=-1)
x = Lambda(greater,output_shape=(1,))((merged_vector[0],merged_vector[1]))

ValueError: Layer lambda_4 was called with an input that isn't a symbolic tensor. Received type: . Full input: [(, )]. All inputs to the layer should be tensors.

Body:
There are three points:

When the Lambda layer has more than one input, then the inputs must be passed as a list of tensors, not a tuple.

The output of greater is a bool Tensor which you need to cast to float for doing computations on it.

greater takes two inputs, so you need to wrap it inside a python lambda function to be able to use it in a Lambda layer in Keras.

Therefore, we would have:

from keras import backend as K

# ...
x = Lambda(lambda z: K.cast(K.greater(z[0], z[1]), K.floatx()),output_shape=(1,))([encoded_value_1,encoded_value_2])

And also don't forget the missing opening bracket for metrics argument:

..., metrics=['accuracy'])
             ^
             |
             |
          missing!


问:
Powershell: CheckBox.Add_CheckStateChanged
I've started with powershell forms and this is my first attempt.

I'd like to add more checkboxes and I've no problem with "CheckStateChanged".
I'm looking for an alternative code with foreach declaration.
How can I shorten the code with my checkboxes using foreach x in y?

My first attempt works well:

```<code>$CheckBox1.Add_CheckStateChanged({
if ($CheckBox1.Checked){$CheckBox2.Enabled = $false} else {$CheckBox2.Enabled = $true}
if ($CheckBox1.Checked){$CheckBox3.Enabled = $false} else {$CheckBox3.Enabled = $true}
if ($CheckBox1.Checked){$CheckBox4.Enabled = $false} else {$CheckBox4.Enabled = $true}
})

$CheckBox2.Add_CheckStateChanged({
if ($CheckBox2.Checked){$CheckBox1.Enabled = $false} else {$CheckBox1.Enabled = $true}
if ($CheckBox2.Checked){$CheckBox3.Enabled = $false} else {$CheckBox3.Enabled = $true}
if ($CheckBox2.Checked){$CheckBox4.Enabled = $false} else {$CheckBox4.Enabled = $true}
})

$CheckBox3.Add_CheckStateChanged({
if ($CheckBox3.Checked){$CheckBox1.Enabled = $false} else {$CheckBox1.Enabled = $true}
if ($CheckBox3.Checked){$CheckBox2.Enabled = $false} else {$CheckBox2.Enabled = $true}
if ($CheckBox3.Checked){$CheckBox4.Enabled = $false} else {$CheckBox4.Enabled = $true}
})

$CheckBox4.Add_CheckStateChanged({
if ($CheckBox4.Checked){$CheckBox1.Enabled = $false} else {$CheckBox1.Enabled = $true}
if ($CheckBox4.Checked){$CheckBox2.Enabled = $false} else {$CheckBox2.Enabled = $true}
if ($CheckBox4.Checked){$CheckBox3.Enabled = $false} else {$CheckBox3.Enabled = $true}
})
</code>```

An alternative I'm looking for might look like:

CheckBox1.Add_CheckStateChanged({
if (CheckBox1.Checked){foreach CheckBox in $_.Enabled = $false} else {$CheckBox2.Enabled = true}

Unfortunately I can't figure it out how to use a foreach function with checkboxes. I'd like to add more than ten checkboxes to my form.

答:
I agree with Mathias R. Jessen that I too think you are better off using a radio button group.

However, if you want to have mutually exclusive checkboxes and shorten your code, you could do this:

```<code># create a scriptblock to be used in every checkboxes CheckStateChanged event
$checkChange = {
    # loop through all the forms checkbox controls.
    # the sender object is captured in the automatic variable '$this'
    $form.Controls | Where-Object {$_ -is [System.Windows.Forms.Checkbox]} | ForEach-Object {
        # if this checkbox is checked, disable all others, otherwise
        # set all checkbox controls to Enabled
        $_.Enabled = if ($this.Checked) { ($_ -eq $this) } else { $true }
    }
}

# add the scriptblock to the individual checkbox objects
$CheckBox1.Add_CheckStateChanged($checkChange)
$CheckBox2.Add_CheckStateChanged($checkChange)
$CheckBox3.Add_CheckStateChanged($checkChange)
$CheckBox4.Add_CheckStateChanged($checkChange)
</code>```

As per your comment, yes, it is possible to collect all checkbox controls in an array and use that to build the form. It may shorten your code, but makes it less readable at the same time. Here's an example:

```<code>$chkBoxes = @()
for ($i = 0; $i -lt 4; $i++) {
    $dummy = New-Object System.Windows.Forms.Checkbox
    $dummy.Location = New-Object System.Drawing.Size(10,(20 + $i * 20))
    # add more COMMON properties if need be.
    # individual properties need to be set on each box by index.
    # e.g. $chkBoxes[0].Cursor = [System.Windows.Forms.Cursors]::Hand

    # set the CheckStateChanged handler on the control
    $dummy.Add_CheckStateChanged($checkChange)
    # add the new control to the $chkBoxes array
    $chkBoxes += $dummy
}
# add the array of controls to the form
$form.Controls.AddRange($chkBoxes)
</code>```

Hope that helps

Body:
I've started with powershell forms and this is my first attempt.

I'd like to add more checkboxes and I've no problem with "CheckStateChanged".
I'm looking for an alternative code with foreach declaration.
How can I shorten the code with my checkboxes using foreach x in y?

My first attempt works well:

$CheckBox1.Add_CheckStateChanged({
if ($CheckBox1.Checked){$CheckBox2.Enabled = $false} else {$CheckBox2.Enabled = $true}
if ($CheckBox1.Checked){$CheckBox3.Enabled = $false} else {$CheckBox3.Enabled = $true}
if ($CheckBox1.Checked){$CheckBox4.Enabled = $false} else {$CheckBox4.Enabled = $true}
})

$CheckBox2.Add_CheckStateChanged({
if ($CheckBox2.Checked){$CheckBox1.Enabled = $false} else {$CheckBox1.Enabled = $true}
if ($CheckBox2.Checked){$CheckBox3.Enabled = $false} else {$CheckBox3.Enabled = $true}
if ($CheckBox2.Checked){$CheckBox4.Enabled = $false} else {$CheckBox4.Enabled = $true}
})

$CheckBox3.Add_CheckStateChanged({
if ($CheckBox3.Checked){$CheckBox1.Enabled = $false} else {$CheckBox1.Enabled = $true}
if ($CheckBox3.Checked){$CheckBox2.Enabled = $false} else {$CheckBox2.Enabled = $true}
if ($CheckBox3.Checked){$CheckBox4.Enabled = $false} else {$CheckBox4.Enabled = $true}
})

$CheckBox4.Add_CheckStateChanged({
if ($CheckBox4.Checked){$CheckBox1.Enabled = $false} else {$CheckBox1.Enabled = $true}
if ($CheckBox4.Checked){$CheckBox2.Enabled = $false} else {$CheckBox2.Enabled = $true}
if ($CheckBox4.Checked){$CheckBox3.Enabled = $false} else {$CheckBox3.Enabled = $true}
})

An alternative I'm looking for might look like:

CheckBox1.Add_CheckStateChanged({
if (CheckBox1.Checked){foreach CheckBox in $_.Enabled = $false} else {$CheckBox2.Enabled = true}

Unfortunately I can't figure it out how to use a foreach function with checkboxes. I'd like to add more than ten checkboxes to my form.

Body:
I agree with Mathias R. Jessen that I too think you are better off using a radio button group.

However, if you want to have mutually exclusive checkboxes and shorten your code, you could do this:

# create a scriptblock to be used in every checkboxes CheckStateChanged event
$checkChange = {
    # loop through all the forms checkbox controls.
    # the sender object is captured in the automatic variable '$this'
    $form.Controls | Where-Object {$_ -is [System.Windows.Forms.Checkbox]} | ForEach-Object {
        # if this checkbox is checked, disable all others, otherwise
        # set all checkbox controls to Enabled
        $_.Enabled = if ($this.Checked) { ($_ -eq $this) } else { $true }
    }
}

# add the scriptblock to the individual checkbox objects
$CheckBox1.Add_CheckStateChanged($checkChange)
$CheckBox2.Add_CheckStateChanged($checkChange)
$CheckBox3.Add_CheckStateChanged($checkChange)
$CheckBox4.Add_CheckStateChanged($checkChange)

As per your comment, yes, it is possible to collect all checkbox controls in an array and use that to build the form. It may shorten your code, but makes it less readable at the same time. Here's an example:

$chkBoxes = @()
for ($i = 0; $i -lt 4; $i++) {
    $dummy = New-Object System.Windows.Forms.Checkbox
    $dummy.Location = New-Object System.Drawing.Size(10,(20 + $i * 20))
    # add more COMMON properties if need be.
    # individual properties need to be set on each box by index.
    # e.g. $chkBoxes[0].Cursor = [System.Windows.Forms.Cursors]::Hand

    # set the CheckStateChanged handler on the control
    $dummy.Add_CheckStateChanged($checkChange)
    # add the new control to the $chkBoxes array
    $chkBoxes += $dummy
}
# add the array of controls to the form
$form.Controls.AddRange($chkBoxes)

Hope that helps


问:
Ruby on Rails: Bundler couldn't find some gems.Did you run 'bundle install'
I am trying to run Fedena which is Ruby on Rails application. I have a hosting account with CPanel. When I try to run Ruby on Rails application, I see the following error in logs:

```<code>Bundler couldn't find some gems.Did you run 'bundle install'
</code>```

Questions:

Is this issue related to Ruby on Rails version? How do I know which version I am running?

How do I fix this issue?

Here's complete error:

```<code>/home/abc/rails_apps/abc/config/../config/preinitializer.rb:18: Bundler couldn't find some gems.Did you run `bundle install`? (RuntimeError)
    from /home/abc/rails_apps/abc/config/boot.rb:29:in `load'
    from /home/abc/rails_apps/abc/config/boot.rb:29:in `preinitialize'
    from /home/abc/rails_apps/abc/config/boot.rb:11:in `boot!'
    from /home/abc/rails_apps/abc/config/boot.rb:127
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /home/abc/rails_apps/abc/config/environment.rb:1
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/rails.rb:147:in `rails'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:113:in `cloaker_'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:149:in `call'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:149:in `listener'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:99:in `cloaker_'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:50:in `call'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:50:in `initialize'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:84:in `new'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:84:in `run'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/command.rb:212:in `run'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
    from /usr/bin/mongrel_rails:23:in `load'
</code>```

答:
As you mentioned that you are deploying in Cpanel.
First, you should get SSH access then you can run command bundle install in the root folder on the app.

You can run rails -v via SSH to know about the Rails version.

Run command bundle install in the root folder on the app to fix this issue.

Body:
I am trying to run Fedena which is Ruby on Rails application. I have a hosting account with CPanel. When I try to run Ruby on Rails application, I see the following error in logs:

Bundler couldn't find some gems.Did you run 'bundle install'

Questions:

Is this issue related to Ruby on Rails version? How do I know which version I am running?

How do I fix this issue?

Here's complete error:

/home/abc/rails_apps/abc/config/../config/preinitializer.rb:18: Bundler couldn't find some gems.Did you run `bundle install`? (RuntimeError)
    from /home/abc/rails_apps/abc/config/boot.rb:29:in `load'
    from /home/abc/rails_apps/abc/config/boot.rb:29:in `preinitialize'
    from /home/abc/rails_apps/abc/config/boot.rb:11:in `boot!'
    from /home/abc/rails_apps/abc/config/boot.rb:127
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /home/abc/rails_apps/abc/config/environment.rb:1
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/rails.rb:147:in `rails'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:113:in `cloaker_'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:149:in `call'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:149:in `listener'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:99:in `cloaker_'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:50:in `call'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:50:in `initialize'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:84:in `new'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:84:in `run'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/command.rb:212:in `run'
    from /usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
    from /usr/bin/mongrel_rails:23:in `load'


问:
Pseudo element hides content when opacity set to 1
Consider the HTML

get in touch

        speak to one of our experts

```
</div>
</div>
</p>

<p>The following CSS causes me problems with the text in the anchor element.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#speak-to-our-experts {
  .mega-link {
    display: block;
    padding: 3.5rem 0 4.625rem;
    width: 100%;
    text-decoration: none;
    text-align: center;
    transition: background-color .3s;
    position: relative;

    &.mega-link--primary {
      background-color: #ef0d33;
      color: $white;
      overflow: hidden;
    }
    &.mega-link--primary:hover:before {
      transform: translateX(10%) skew(-20deg);
      opacity: 1;
    }
    &.mega-link--primary:before {
      content: "";
      position: absolute;
      top: 0;
      right: 0;
      width: 140%;
      height: 100%;
      transform: translateX(100%);
      background-color: #cb0b2b;
      opacity: 0;
      transition: transform 1.1s ease,opacity .3s ease;
    }
  }
}</code>```

Although I get the slide in effect from the pseudo element as required - the opacity causes me problems as it hides the text underneath. I've experimented with z-index to no avail. What's happening here?

答:
Adjust z-index like below. The one in .mega-link will create a stacking context preventing the pseudo element to go behind and the one on the pseudo element will make it the lowest layer inside that stacking context.

.mega-link {
  display: block;
  padding: 3.5rem 0 4.625rem;
  width: 100%;
  text-decoration: none;
  text-align: center;
  transition: background-color .3s;
  position: relative;
  z-index:0; /*added*/
}

.mega-link--primary {
  background-color: #ef0d33;
  color: #fff;
  overflow: hidden;
}

.mega-link--primary:hover:before {
  transform: translateX(10%) skew(-20deg);
  opacity: 1;
}

.mega-link--primary:before {
  content: "";
  position: absolute;
  z-index:-1; /*added*/
  top: 0;
  right: 0;
  width: 140%;
  height: 100%;
  transform: translateX(100%);
  background-color: #cb0b2b;
  opacity: 0;
  transition: transform 1.1s ease, opacity .3s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="speak-to-our-experts">

    <h2>get in touch</h2>
    <span>speak to one of our experts</span>

</section></code>```

Related: Why can't an element with a z-index value cover its child?

Another idea is to make sure the text will be painted later by adding position:relative for example:

.mega-link {
  display: block;
  padding: 3.5rem 0 4.625rem;
  width: 100%;
  text-decoration: none;
  text-align: center;
  transition: background-color .3s;
  position: relative;
}

.mega-link--primary {
  background-color: #ef0d33;
  color: #fff;
  overflow: hidden;
}

.mega-link--primary:hover:before {
  transform: translateX(10%) skew(-20deg);
  opacity: 1;
}

.mega-link--primary:before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 140%;
  height: 100%;
  transform: translateX(100%);
  background-color: #cb0b2b;
  opacity: 0;
  transition: transform 1.1s ease, opacity .3s ease;
}

.mega-link--primary *{
  position:relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="speak-to-our-experts">

    <h2>get in touch</h2>
    <span>speak to one of our experts</span>

</section></code>```

Related: Why does position:relative; appear to change the z-index?

Body:
Consider the HTML

get in touch

        speak to one of our experts

The following CSS causes me problems with the text in the anchor element.

#speak-to-our-experts {
  .mega-link {
    display: block;
    padding: 3.5rem 0 4.625rem;
    width: 100%;
    text-decoration: none;
    text-align: center;
    transition: background-color .3s;
    position: relative;

    &.mega-link--primary {
      background-color: #ef0d33;
      color: $white;
      overflow: hidden;
    }
    &.mega-link--primary:hover:before {
      transform: translateX(10%) skew(-20deg);
      opacity: 1;
    }
    &.mega-link--primary:before {
      content: "";
      position: absolute;
      top: 0;
      right: 0;
      width: 140%;
      height: 100%;
      transform: translateX(100%);
      background-color: #cb0b2b;
      opacity: 0;
      transition: transform 1.1s ease,opacity .3s ease;
    }
  }
}

Although I get the slide in effect from the pseudo element as required - the opacity causes me problems as it hides the text underneath. I've experimented with z-index to no avail. What's happening here?

Body:
Adjust z-index like below. The one in .mega-link will create a stacking context preventing the pseudo element to go behind and the one on the pseudo element will make it the lowest layer inside that stacking context.

.mega-link {
  display: block;
  padding: 3.5rem 0 4.625rem;
  width: 100%;
  text-decoration: none;
  text-align: center;
  transition: background-color .3s;
  position: relative;
  z-index:0; /*added*/
}

.mega-link--primary {
  background-color: #ef0d33;
  color: #fff;
  overflow: hidden;
}

.mega-link--primary:hover:before {
  transform: translateX(10%) skew(-20deg);
  opacity: 1;
}

.mega-link--primary:before {
  content: "";
  position: absolute;
  z-index:-1; /*added*/
  top: 0;
  right: 0;
  width: 140%;
  height: 100%;
  transform: translateX(100%);
  background-color: #cb0b2b;
  opacity: 0;
  transition: transform 1.1s ease, opacity .3s ease;
}

<section id="speak-to-our-experts">
  <a class="mega-link mega-link--primary" href="#">
    <h2>get in touch</h2>
    <span>speak to one of our experts</span>
  </a>
</section>

Related: Why can't an element with a z-index value cover its child?

Another idea is to make sure the text will be painted later by adding position:relative for example:

.mega-link {
  display: block;
  padding: 3.5rem 0 4.625rem;
  width: 100%;
  text-decoration: none;
  text-align: center;
  transition: background-color .3s;
  position: relative;
}

.mega-link--primary {
  background-color: #ef0d33;
  color: #fff;
  overflow: hidden;
}

.mega-link--primary:hover:before {
  transform: translateX(10%) skew(-20deg);
  opacity: 1;
}

.mega-link--primary:before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 140%;
  height: 100%;
  transform: translateX(100%);
  background-color: #cb0b2b;
  opacity: 0;
  transition: transform 1.1s ease, opacity .3s ease;
}

.mega-link--primary *{
  position:relative;
}

<section id="speak-to-our-experts">
  <a class="mega-link mega-link--primary" href="#">
    <h2>get in touch</h2>
    <span>speak to one of our experts</span>
  </a>
</section>

Related: Why does position:relative; appear to change the z-index?


问:
WSO2 enterprise integrator. - datasource on server
It is possible deploy datasource  in WSO2 EI on server without GUI? I try find something on internet but i found only create datasource in GUI.

Thanks

答:
You can add your datasource into master-datasources.xml that is located in EI_HOME\conf\datasources\master-datasources.xml

here is the example code:

```<code><datasource>
    <name>WSO2_ESB_LOGS_DB</name>
    <description/>
    <jndiConfig>
        <name>jdbc/WSO2EsbLogsDB</name>
    </jndiConfig>
    <definition type="RDBMS">
        <configuration>
            <url>jdbc:postgresql://localhost:5432/mydb</url>
            <username>myusername</username>
            <password>mypassword</password>
            <driverClassName>org.postgresql.Driver</driverClassName>
            <maxActive>50</maxActive>
            <maxWait>60000</maxWait>
            <defaultAutoCommit>false</defaultAutoCommit>
            <testOnBorrow>true</testOnBorrow>
            <validationQuery>SELECT 1</validationQuery>
            <validationInterval>30000</validationInterval>
        </configuration>
    </definition>
</datasource>
</code>```

Body:
You can add your datasource into master-datasources.xml that is located in EI_HOME\conf\datasources\master-datasources.xml

here is the example code:

<datasource>
    <name>WSO2_ESB_LOGS_DB</name>
    <description/>
    <jndiConfig>
        <name>jdbc/WSO2EsbLogsDB</name>
    </jndiConfig>
    <definition type="RDBMS">
        <configuration>
            <url>jdbc:postgresql://localhost:5432/mydb</url>
            <username>myusername</username>
            <password>mypassword</password>
            <driverClassName>org.postgresql.Driver</driverClassName>
            <maxActive>50</maxActive>
            <maxWait>60000</maxWait>
            <defaultAutoCommit>false</defaultAutoCommit>
            <testOnBorrow>true</testOnBorrow>
            <validationQuery>SELECT 1</validationQuery>
            <validationInterval>30000</validationInterval>
        </configuration>
    </definition>
</datasource>


问:
What is meaning of calling superview's viewwillappear?
```<code>-(void)viewwillAppear
{
[super viewwillAppear:animated];
}
</code>```

What does mean of calling [super viewwillAppear:animated] and what happen if we not call it?

答:
Apple's documentation for viewWillAppear: just says:

If you override this method, you must call super at some point in your implementation.

It will probably lead to some unexpected behavior if you don't call it. Note that 'at some point' means you don't have to call it first.

Body:
-(void)viewwillAppear
{
[super viewwillAppear:animated];
}

What does mean of calling [super viewwillAppear:animated] and what happen if we not call it?


问:
Actions-on-Google user.storage not saved on Dialogflow SDK
I've developing an action by using Dialogflow SDK and Firebase Functions. I'm using conv.user.storage to save user ID between conversations. However, every time user comes to action, Action can not recognize saved ID and shows it "undefined". I've been developing this action for a while and users that I created for test 2-3 months ago, have conv.user.storage and they can be recognized. Is there a limit for storing data or something else?

Here is my code:

```<code>if (!conv.user.storage.userId || typeof conv.user.storage.userId === "undefined") {
  conv.user.storage.userId = uuidv1();
  console.log("new implemented userID.", conv.user.storage.userId);
}
else {
  console.log("ID from storage", conv.user.storage.userId);
}
</code>```

答: i was facing the same problem as you.. I found the fix in this comment in a github issue. Basically when enabling the Web & App permissions in the Activity Center you need also to check " include chrome history .... "</p>

Body:
I've developing an action by using Dialogflow SDK and Firebase Functions. I'm using conv.user.storage to save user ID between conversations. However, every time user comes to action, Action can not recognize saved ID and shows it "undefined". I've been developing this action for a while and users that I created for test 2-3 months ago, have conv.user.storage and they can be recognized. Is there a limit for storing data or something else?

Here is my code:

if (!conv.user.storage.userId || typeof conv.user.storage.userId === "undefined") {
  conv.user.storage.userId = uuidv1();
  console.log("new implemented userID.", conv.user.storage.userId);
}
else {
  console.log("ID from storage", conv.user.storage.userId);
}


问:
ggplot - get axis ranges of the CURRENT plot
Suppose you have the following code:

```<code>grid.arrange(
  ggplot(data[data$Year = 2018,], aes(x = Var1, y = Var2))+
    geom_violin()+
    geom_jitter()+
    ggtitle("2018"),
  ggplot(data[data$Year = 2019,], aes(x = Var1, y = Var2))+
    geom_violin()+
    geom_jitter()+
    ggtitle("2019"), ncol = 2)
</code>```

This will produce a side-by-side combined violin and jittered scatterplot of Var1 and Var 2 at two timepoints (2018 and 2019). However, it can happen that the y-axis range will not be the same in 2018 and 2019, which is bad for visual comparison of the data. Therefore, we can add the following line:

```<code>+scale_y_continuous(limits = c(1, 5))
</code>```

to both ggplot object in the grid.arrange function in order to constrain the y-axes to be the same on both plots (1 is the minimum possible result on the scale and 5 is the maximum).

However, the usage of geom_jitter() resulted in some points exceeding the y-axis limits of 1 and 5. Is it possible to somehow see what is the scale range that ggplot has internally produced and to manually set the scale limits to these values on both plots?

I have found this answer, but I do not want to first save the plot in an object and then pull the information from that object and modify the plot. I want to produce a clean plot as described above with no intermediate saved objects. Is it possible to do so?

答:
```<code>ggplot(data, aes(x=Var1, y=Var2)) +
    geom_violin() +
    geom_jitter() +
    facet_grid(.~Year)
</code>```

Try Year~. if the plots come out stacked. I keep forgetting the proper order. You may have to turn Year into a factor beforehand.

Body:
Suppose you have the following code:

grid.arrange(
  ggplot(data[data$Year = 2018,], aes(x = Var1, y = Var2))+
    geom_violin()+
    geom_jitter()+
    ggtitle("2018"),
  ggplot(data[data$Year = 2019,], aes(x = Var1, y = Var2))+
    geom_violin()+
    geom_jitter()+
    ggtitle("2019"), ncol = 2)

This will produce a side-by-side combined violin and jittered scatterplot of Var1 and Var 2 at two timepoints (2018 and 2019). However, it can happen that the y-axis range will not be the same in 2018 and 2019, which is bad for visual comparison of the data. Therefore, we can add the following line:

+scale_y_continuous(limits = c(1, 5))

to both ggplot object in the grid.arrange function in order to constrain the y-axes to be the same on both plots (1 is the minimum possible result on the scale and 5 is the maximum).

However, the usage of geom_jitter() resulted in some points exceeding the y-axis limits of 1 and 5. Is it possible to somehow see what is the scale range that ggplot has internally produced and to manually set the scale limits to these values on both plots?

I have found this answer, but I do not want to first save the plot in an object and then pull the information from that object and modify the plot. I want to produce a clean plot as described above with no intermediate saved objects. Is it possible to do so?

Body:
ggplot(data, aes(x=Var1, y=Var2)) +
    geom_violin() +
    geom_jitter() +
    facet_grid(.~Year)

Try Year~. if the plots come out stacked. I keep forgetting the proper order. You may have to turn Year into a factor beforehand.


问:
React - Component Full Screen (with height 100%)
I'm stuck with displaying a React component named "home" that take 100% of the height of my screen.
Whatever I use CSS or React inline style it doesn't work.

In the example below, html, body and #app are set to  height: 100% in CSS. For .home I used inline style (but whatever I used CSS or inline style is the same):

The issue seems to come from
 that is not set with height: 100%.

If I hacked it with Chrome developer tool, it's work:

So what is the proper way to display a full height component in React ?

Any help is welcome :)

答:
I managed this with a css class in my app.css

```<code>.fill-window {
    height: 100%;
    position: absolute;
    left: 0;
    width: 100%;
    overflow: hidden;
}
</code>```

Apply it to your root element in your render() method

```<code>render() {
   return ( <div className="fill-window">{content}</div> );
}
</code>```

Or inline

```<code>render() {
   return (
      <div style={{ height: '100%', position: 'absolute', left: '0px', width: '100%', overflow: 'hidden'}}>
          {content}
      </div>
   );
}
</code>```

Body:
I managed this with a css class in my app.css

.fill-window {
    height: 100%;
    position: absolute;
    left: 0;
    width: 100%;
    overflow: hidden;
}

Apply it to your root element in your render() method

render() {
   return ( <div className="fill-window">{content}</div> );
}

Or inline

render() {
   return (
      <div style={{ height: '100%', position: 'absolute', left: '0px', width: '100%', overflow: 'hidden'}}>
          {content}
      </div>
   );
}


问:
Difference in numpy array masking
I have three numpy arrays, one the source array, one destination array and one mask array. I want to replace the values in the destination with the same values from the source only at the places where the mask is equal to one.

My naiive try was:

```<code>import numpy as np
destination = np.arange(9).reshape((3,3))
source = np.ones((3,3))
mask = np.zeros((3,3)).astype(np.uint8)
mask[1,1]=1

destination[mask] = source[mask]
</code>```

which leads me to destination being

```<code>[[1, 1, 1],
 [1, 1, 1],
 [6, 7, 8]]
</code>```

whereas I expect it to be

```<code>[[0, 1, 2],
 [3, 1, 5],
 [6, 7, 8]].
</code>```

I do get the correct result, when I do

```<code>destination[mask==1] = source[mask==1].
</code>```

My question is: Why are these two commands not identical, or what does the first even do?

答:
First you must check inside the matrices and which matrix gives you what you want.

```<code>mask
</code>```

Output

```<code>[[0, 0, 0],
 [0, 1, 0],
 [0, 0, 0]]
</code>```

but destination[mask == 1] gives you a boolean matrix

```<code>mask == 1
</code>```

Output

```<code>[[False, False, False],
 [False,  True, False],
 [False, False, False]]
</code>```

whereas:

```<code>destination[mask]
</code>```

Output

```<code>[[[0, 1, 2],
  [0, 1, 2],
  [0, 1, 2]]

[[0, 1, 2],
 [3, 4, 5],
 [0, 1, 2]],

[[0, 1, 2],
 [0, 1, 2],
 [0, 1, 2]]]
</code>```

but using destination[mask == 1] gives you a single value which is 4. It's the same for the source[mask == 1] which gives you the single value 1.

and if you use destination[mask==1] = source[mask==1] instead of destination[mask] = source[mask]  you will only change the value 4 in the destination matrix.

I hope my explanation is clear.

Edit:

I hope I understand your question correct:

The simple integer indexing structure x[[i]] gives you the i'th row of the matrix.

So destination[0,1,2] gives:

```<code>[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8]]
</code>```

and for an understandable example the input destination[1,2,0] leads to

```<code>[[3, 4, 5],
 [6, 7, 8],
 [0, 1, 2]]
</code>```

Title: Difference in numpy array masking

Body:
I have three numpy arrays, one the source array, one destination array and one mask array. I want to replace the values in the destination with the same values from the source only at the places where the mask is equal to one.

My naiive try was:

import numpy as np
destination = np.arange(9).reshape((3,3))
source = np.ones((3,3))
mask = np.zeros((3,3)).astype(np.uint8)
mask[1,1]=1

destination[mask] = source[mask]

which leads me to destination being

[[1, 1, 1],
 [1, 1, 1],
 [6, 7, 8]]

whereas I expect it to be

[[0, 1, 2],
 [3, 1, 5],
 [6, 7, 8]].

I do get the correct result, when I do

destination[mask==1] = source[mask==1].

My question is: Why are these two commands not identical, or what does the first even do?

Body:
First you must check inside the matrices and which matrix gives you what you want.

mask

Output

[[0, 0, 0],
 [0, 1, 0],
 [0, 0, 0]]

but destination[mask == 1] gives you a boolean matrix

mask == 1

Output

[[False, False, False],
 [False,  True, False],
 [False, False, False]]

whereas:

destination[mask]

Output

[[[0, 1, 2],
  [0, 1, 2],
  [0, 1, 2]]

[[0, 1, 2],
 [3, 4, 5],
 [0, 1, 2]],

[[0, 1, 2],
 [0, 1, 2],
 [0, 1, 2]]]

but using destination[mask == 1] gives you a single value which is 4. It's the same for the source[mask == 1] which gives you the single value 1.

and if you use destination[mask==1] = source[mask==1] instead of destination[mask] = source[mask]  you will only change the value 4 in the destination matrix.

I hope my explanation is clear.

Edit:

I hope I understand your question correct:

The simple integer indexing structure x[[i]] gives you the i'th row of the matrix.

So destination[0,1,2] gives:

[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8]]

and for an understandable example the input destination[1,2,0] leads to

[[3, 4, 5],
 [6, 7, 8],
 [0, 1, 2]]


问:
Datagrid rowbackground color
I'm trying to change a background color of a row datagrid in codebehing I'm using a binding property
in code behing I see the color changes but when displayed the background color doesn't change.
When  I play with the scroll I some of the </p>

答:
Complete Row:

```<code>datagrid1.Rows(0).DefaultCellStyle.BackColor = Color.Beige
</code>```

Complete Column:

```<code>datagrid1.Columns(0).DefaultCellStyle.BackColor = Color.Yellow
</code>```

With Condition and Particular cell

```<code>If (dataset1.Tables(0).Rows(1)(0) == "") Then
  datagrid1.Rows(0).Cells(1).Style.BackColor = Color.Red
End if
</code>```

Title: Datagrid rowbackground color

Body:
Complete Row:

datagrid1.Rows(0).DefaultCellStyle.BackColor = Color.Beige

Complete Column:

datagrid1.Columns(0).DefaultCellStyle.BackColor = Color.Yellow

With Condition and Particular cell

If (dataset1.Tables(0).Rows(1)(0) == "") Then
  datagrid1.Rows(0).Cells(1).Style.BackColor = Color.Red
End if


问:
How should I run custom management command on heroku?
I have my first django app deployed on heroku. Within this app I have an assortment of custom management commands that I would like to run periodically. For example I need one command to run once every two weeks, another to run every Sunday and Wednesday, and another to run once a week. I've read about a couple different options including celery, Heroku scheduler, and Cron. I'm unsure which solution to choose and why.</p>

答: Another option which might work for you is an Heroku add-on we've added recently, called Cron To Go. It's more reliable than Heroku Scheduler and more flexible because you can use any cron expression to schedule your background jobs. It'll probably be cheaper to use than Celery which requires you to have dynos on at all times, and easier to maintain as you don't have to push code changes every time you want to change a schedule.</p>


问:
Creating variables for destructured objects in addition to their properties
I have:

```<code>const { state: { mode } } = this

console.log(mode) //'mode'
console.log(state) //undefined
</code>```

I want to declare the state variable as well.

Is there a way to destructure this without breaking it into two statements?

```<code>const { state } = this
const { mode } = state
</code>```

答:
While all the other answer here suggested a word around to get values, but i am adding this answer to explain why we getting only the deep most nested value

```<code>let state = {
    state: {
      mode : 'some value'
 }
}

const { state: { mode } } = state
</code>```

When you do nested destructing you will be complied to something like this

```<code>var state = {
  state: {
    mode: 'some value'
  }
};
var mode = state.state.mode;  // this is how your de-structuring is interpreted
</code>```

It is not creating a separate variable for each of the property,

Body:
I have:

const { state: { mode } } = this

console.log(mode) //'mode'
console.log(state) //undefined

I want to declare the state variable as well.

Is there a way to destructure this without breaking it into two statements?

const { state } = this
const { mode } = state

Body:
While all the other answer here suggested a word around to get values, but i am adding this answer to explain why we getting only the deep most nested value

let state = {
    state: {
      mode : 'some value'
 }
}

const { state: { mode } } = state

When you do nested destructing you will be complied to something like this

var state = {
  state: {
    mode: 'some value'
  }
};
var mode = state.state.mode;  // this is how your de-structuring is interpreted

It is not creating a separate variable for each of the property,


问:
Count unique users if user visit n times
I want to implement FreqCapping in an ad network. I want to serve a campaign to unique users only n time in day. If n=1, I could implement this with BloomFilter in redis, but usually n is greater than 1. Is there any data structure (even probabilistic data structure) that aims this issue? And is that implemented in redis?</p>

答: It sounds like you're describing the Count-min sketch, and while Redis core doesn't have it, RedisBloom does :)</p>


问:
Checking last element of a string in a list
I have got some serial communications logs to analyze regarding time, so I record messages with timestamps in format YYYY-MM-DD HH:MM:SS.ffffff:
So my file looks like this:

YYYY-MM-DD HH:MM:SS.ffffff:

few lines of bytes

YYYY-MM-DD HH:MM:SS.ffffff:

and so on...

I want to extract dates from my file so I could calculate times between messages

I want to operate on dates using datetime module, and for the beginning I wanted to get rid of the colons at the end of each date. I have read my file and saved it in variable which is a list of strings, and each element is a line. Now I want to create a second list of only dates, extracting only those lines that end with colons.

f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    if lines[i].endswith(":"):
        dates.append(lines[i])
    i+=1
print (dates)
```

I checked that lines is created correctly, however there are no elements appended to the list dates. It remains empty. Is there something wrong with my ifcondition? Or is there another way of checking last character of a string if it is a list element?

答:
This should work, if it doesn't then your lines probably don't end with :.

```<code>with open("sniffinglog.txt", "r") as f:
    content = f.readlines()

dates = []
for line in content:
    if line.strip().endswith(":"):
        dates.append(line.rstrip(":"))

print(dates)
</code>```

Body:
I have got some serial communications logs to analyze regarding time, so I record messages with timestamps in format YYYY-MM-DD HH:MM:SS.ffffff:
So my file looks like this:

YYYY-MM-DD HH:MM:SS.ffffff:

few lines of bytes

YYYY-MM-DD HH:MM:SS.ffffff:

and so on...

I want to extract dates from my file so I could calculate times between messages

I want to operate on dates using datetime module, and for the beginning I wanted to get rid of the colons at the end of each date. I have read my file and saved it in variable which is a list of strings, and each element is a line. Now I want to create a second list of only dates, extracting only those lines that end with colons.

f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    if lines[i].endswith(":"):
        dates.append(lines[i])
    i+=1
print (dates)

I checked that lines is created correctly, however there are no elements appended to the list dates. It remains empty. Is there something wrong with my ifcondition? Or is there another way of checking last character of a string if it is a list element?

Body:
This should work, if it doesn't then your lines probably don't end with :.

with open("sniffinglog.txt", "r") as f:
    content = f.readlines()

dates = []
for line in content:
    if line.strip().endswith(":"):
        dates.append(line.rstrip(":"))

print(dates)


问:
Android: Null Pointer Exception at Text View
Here is a code for which I face the Exception

```<code>public class SHOSuper extends Activity{

String officerName;
String arr[];
String[] offN;
public void onCreate(Bundle savedInstanceState) {
    try{
        super.onCreate(savedInstanceState);
        final TextView tv;
        tv=(TextView)findViewById(R.id.txt1);
        System.out.println("I AM NEW ACTIVITY");
        arr=Receiver.split(Receiver.orignal, ",");
        String value1= arr[1];
        System.out.println("Array index " + value1);
        String value2=arr[2];
        System.out.println("Array 2nd index " + value2);
        tv.setText(value1 + " At " + value2);
        officerName= arr[5];
        offN =new String[officerName.length()];
        offN=Receiver.split(officerName, "_");
    }
    catch(Exception e){
        e.printStackTrace();
    }

setContentView(R.layout.main);
  }
}
</code>```

On line tv.setText(value1 + " At " + value2); I face Null pointer Exception like this

```<code>**04-12 13:25:18.105: WARN/System.err(527): java.lang.NullPointerException
04-12 13:25:18.265: WARN/System.err(527):     at com.sho.SHOSuper.onCreate(SHOSuper.java:24)**
</code>```

Can you help me?

答:
findViewById() finds the view in your current contentView, not a random id in an xml.

So when you do this:

```<code>tv=(TextView)findViewById(R.id.txt1);
</code>```

It cannot find the ID, even if it is available in your layout.main: the layout isn't set yet. Call the setContentView(R.layout.main); before you try and find any views.

(you can also use an inflater to get a 'random' view, and then add it to another view, but that doesn't seem what you are looking for)

Body:
Here is a code for which I face the Exception

public class SHOSuper extends Activity{

String officerName;
String arr[];
String[] offN;
public void onCreate(Bundle savedInstanceState) {
    try{
        super.onCreate(savedInstanceState);
        final TextView tv;
        tv=(TextView)findViewById(R.id.txt1);
        System.out.println("I AM NEW ACTIVITY");
        arr=Receiver.split(Receiver.orignal, ",");
        String value1= arr[1];
        System.out.println("Array index " + value1);
        String value2=arr[2];
        System.out.println("Array 2nd index " + value2);
        tv.setText(value1 + " At " + value2);
        officerName= arr[5];
        offN =new String[officerName.length()];
        offN=Receiver.split(officerName, "_");
    }
    catch(Exception e){
        e.printStackTrace();
    }

setContentView(R.layout.main);
  }
}

On line tv.setText(value1 + " At " + value2); I face Null pointer Exception like this

**04-12 13:25:18.105: WARN/System.err(527): java.lang.NullPointerException
04-12 13:25:18.265: WARN/System.err(527):     at com.sho.SHOSuper.onCreate(SHOSuper.java:24)**

Can you help me?

Body:
findViewById() finds the view in your current contentView, not a random id in an xml.

So when you do this:

tv=(TextView)findViewById(R.id.txt1);

It cannot find the ID, even if it is available in your layout.main: the layout isn't set yet. Call the setContentView(R.layout.main); before you try and find any views.

(you can also use an inflater to get a 'random' view, and then add it to another view, but that doesn't seem what you are looking for)


问:
Take various Integer Inputs on same line JAVA
I want to take various integer inputs on same line, lets say 2. Actually I want to take input in shape of a Matrix as input values will be stored in a form of matrix.

The problem is that I can only take one input per line and it goes to the next line for taking next input. I think its Scanner.nextInt() that causes the cursor to got to the next line as I have to press enter after giving each input.

Code:

```<code>import java.util.Scanner;
public class Matrix
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        boolean flag = false;
        int row = 2 , col =2;
        int[][] array = new int[row][col];
        do
        {
            System.out.printf("\n>>>>> Enter values for Matrix <<<<<\n");
            try
            {
                for (int i = 0; i < row; i++)
                {
                    System.out.print("\n[  ");
                    for (int j = 0; j < col; j++)
                    {
                        array[i][j] = input.nextInt();
                        System.out.print("   ");
                    }
                    System.out.print("  ]\n");
                }
                flag = true;
            }
            catch(Exception e)
            {
                System.out.println("Invalid Input. Try Again.");
                String flush = input.next();
                flag = false;
            }
        }while(!flag);
    }
}
</code>```

Output:

Desired Output:

[  2  3  ]

[  8  4  ]

I have searched this problem on internet but everyone is taking one input per line but I want it to take input in Matrix style.

答:
You can read the input line as a string of numbers separated by spaces then split it </p>

```<code>for (int i = 0; i < row; i++)
{
    System.out.print("\n[  ");
    String matrixRow = input.next();
    String[] numbers = matrixRow.split(" ");
    for (int j = 0; j < col; j++)
    {
         array[i][j] = Integer.parseInt(numbers[j]);
     }
     System.out.print("  ]\n");
}
</code>```

Body:
I want to take various integer inputs on same line, lets say 2. Actually I want to take input in shape of a Matrix as input values will be stored in a form of matrix.

The problem is that I can only take one input per line and it goes to the next line for taking next input. I think its Scanner.nextInt() that causes the cursor to got to the next line as I have to press enter after giving each input.

Code:

import java.util.Scanner;
public class Matrix
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        boolean flag = false;
        int row = 2 , col =2;
        int[][] array = new int[row][col];
        do
        {
            System.out.printf("\n>>>>> Enter values for Matrix <<<<<\n");
            try
            {
                for (int i = 0; i < row; i++)
                {
                    System.out.print("\n[  ");
                    for (int j = 0; j < col; j++)
                    {
                        array[i][j] = input.nextInt();
                        System.out.print("   ");
                    }
                    System.out.print("  ]\n");
                }
                flag = true;
            }
            catch(Exception e)
            {
                System.out.println("Invalid Input. Try Again.");
                String flush = input.next();
                flag = false;
            }
        }while(!flag);
    }
}

Output:

Desired Output:

[  2  3  ]

[  8  4  ]

I have searched this problem on internet but everyone is taking one input per line but I want it to take input in Matrix style.

Body:
You can read the input line as a string of numbers separated by spaces then split it

for (int i = 0; i < row; i++)
{
    System.out.print("\n[  ");
    String matrixRow = input.next();
    String[] numbers = matrixRow.split(" ");
    for (int j = 0; j < col; j++)
    {
         array[i][j] = Integer.parseInt(numbers[j]);
     }
     System.out.print("  ]\n");
}


问:
HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory
I just created a new empty website in Visual Studio 2012 and clicked on run (i.e view in browser) and I get this error:

HTTP Error 403.14 - Forbidden

The Web server is configured to not list the contents of this directory.

I went into IIS and clicked on Directory browsing and then ensured that Directory browsing was enabled but I still get this error. I can't figure it out?

The website project I just created is not listed in Default web sites in IIS Manager which I thought was odd.

How do I get rid of this error?

答:
SOLVED

Search "Windows Feature" on start ->
 Click "turn features on and off" ->
 Expand "Internet Information Services" and
 Check every progrm in every subfolder and
Click "OK"

This will fix all your problems.


问:
How to merge two rectangles given arrays of their coordinates?
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

```<code>   _ _
 _|_  |
|_|_|_|
</code>```

to

```<code>   _ _
 _|   |
|_ _ _|
</code>```

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.

答:
(Never hurts to order things (but here it might not help): order the points in positive rotation, say starting from left-upper edge.)

For a merge (a.topx .. a.bottomx) and (b.topx .. b.bottomx) must overlap, same for y.

The outer rect is outer.topx = min(a.topx, b.topx) and so on.

X-coordinates, possibly incidental, are outer.topx, a.topx, b.topx, outer.bottom.x.
Now you find one border of the polygon. And so on.

The connecting inner edges are trivial.

Mind that there are many forms, but the generalized one is:

```<code>...._____.....
:___|    |___:
|___      ___|
:...|____|...:
</code>```

Whether you might desire a more general algorithm to merge any polygon is the question, as adding a third rectangle will become an entirely different case.

Body:
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

   _ _
 _|_  |
|_|_|_|

to

   _ _
 _|   |
|_ _ _|

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.

Body:
(Never hurts to order things (but here it might not help): order the points in positive rotation, say starting from left-upper edge.)

For a merge (a.topx .. a.bottomx) and (b.topx .. b.bottomx) must overlap, same for y.

The outer rect is outer.topx = min(a.topx, b.topx) and so on.

X-coordinates, possibly incidental, are outer.topx, a.topx, b.topx, outer.bottom.x.
Now you find one border of the polygon. And so on.

The connecting inner edges are trivial.

Mind that there are many forms, but the generalized one is:

...._____.....
:___|    |___:
|___      ___|
:...|____|...:

Whether you might desire a more general algorithm to merge any polygon is the question, as adding a third rectangle will become an entirely different case.


问:
Creating nodes and Realtionships in Neo4j Dynamically
I have a Directory structure like below

```<code>C:\Users\Shiva\Desktop\Internship\shiva.txt
</code>```

I want to Create nodes as each folder and I want a relationship between them.

Example Graph will be like this

```<code>C <-contains-> Users <-contains-> Shiva <-contains-> desktop <-contains->

Internship <-contains-> shiva.txt
</code>```

I am going to pass the path in a dynamic way.

答:
I imagine a solution could be to use Python's os.walk()

This function can be used as this:

from os import walk

def add_node(root, elem):
    query = 'MATCH (r: Directory {{name: "{0}"}})\
                CREATE (e: Directory {{name: "{1}")\
                CREATE (r)-[l: CONTAINS]->(e)\
                RETURN id(e), id(l)'.format(root, elem)
    # Run the query with your driver instance here

# Add the node for root here

for root, dirs, files in os.walk(your_dynamic_path, topdown = False):
    for dir in dirs:
        add_node(root, dir)
    for file in files:
        add_node(root, file)
```

With add_node(root, elem) being a function adding/merging the node elem to your Neo4J graph and adding the relation you want.

Body:
I have a Directory structure like below

C:\Users\Shiva\Desktop\Internship\shiva.txt

I want to Create nodes as each folder and I want a relationship between them.

Example Graph will be like this

C <-contains-> Users <-contains-> Shiva <-contains-> desktop <-contains->

Internship <-contains-> shiva.txt

I am going to pass the path in a dynamic way.

Body:
I imagine a solution could be to use Python's os.walk()

This function can be used as this:

from os import walk

def add_node(root, elem):
    query = 'MATCH (r: Directory {{name: "{0}"}})\
                CREATE (e: Directory {{name: "{1}")\
                CREATE (r)-[l: CONTAINS]->(e)\
                RETURN id(e), id(l)'.format(root, elem)
    # Run the query with your driver instance here

# Add the node for root here

for root, dirs, files in os.walk(your_dynamic_path, topdown = False):
    for dir in dirs:
        add_node(root, dir)
    for file in files:
        add_node(root, file)

With add_node(root, elem) being a function adding/merging the node elem to your Neo4J graph and adding the relation you want.


问:
it shows array outofbound exception
I want to store it in a Arraylist in the following order :

topcompany.get(i).getText(),

avg_exp.get(i).getText(),

avg_sal.get(i).getText(),

inlakhs.get(j).getText(),

circle_text.get(i).getText(),

inlakhs.get(j+1).getText()

My code:

```<code> List<WebElement> topcompany = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_exp = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='245']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_sal = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='295']//*[name()='tspan' and @dy='4']"));
 List<WebElement> inlakhs = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @fill='#000000']//*[name()='tspan' and @dy='3.5']"));
 List<WebElement> circle_text = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text' and @fill='#ffffff']//*[name()='tspan' and @dy='3.5']"));

 for(int i=0;i<topcompany.size();i++) {
     for(int j=4;j<inlakhs.size();j++) {
         //main_list.add(new String[] {topcompany.get(i).getText(),avg_exp.get(i).getText(),avg_sal.get(i).getText(),inlakhs.get(j).getText(),circle_text.get(i).getText(),inlakhs.get(j+1).getText()});
     }
 }
</code>```

答:
Your issues is clearly caused by accessing a list with an index out of range. Run the following code to debug and find out what list in particular is causing the exception:</p>

```<code>    List<WebElement> topcompany = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text']//*[name()='tspan' and @dy='4']"));
    List<WebElement> avg_exp = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='245']//*[name()='tspan' and @dy='4']"));
    List<WebElement> avg_sal = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='295']//*[name()='tspan' and @dy='4']"));
    List<WebElement> inlakhs = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @fill='#000000']//*[name()='tspan' and @dy='3.5']"));
    List<WebElement> circle_text = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text' and @fill='#ffffff']//*[name()='tspan' and @dy='3.5']"));

    java.util.List<java.util.List<WebElement>> elements = new java.util.ArrayList<java.util.List<WebElement>>();
    for(int i=0;i<topcompany.size();i++)
    {
        for(int j=4;j<inlakhs.size();j++)
        {
            for (java.util.List<WebElement> list : elements) {
                try {
                    WebElement element = list.get(i);
                }
                catch (ArrayIndexOutOfBoundsException e) {
                    System.out.printf("%s caused an exception at index %d", element.toString(), i);
                }
            }
        }
    }
</code>```

Title: it shows array outofbound exception

Body:
I want to store it in a Arraylist in the following order :

topcompany.get(i).getText(),

avg_exp.get(i).getText(),

avg_sal.get(i).getText(),

inlakhs.get(j).getText(),

circle_text.get(i).getText(),

inlakhs.get(j+1).getText()

My code:

 List<WebElement> topcompany = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_exp = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='245']//*[name()='tspan' and @dy='4']"));
 List<WebElement> avg_sal = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='295']//*[name()='tspan' and @dy='4']"));
 List<WebElement> inlakhs = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @fill='#000000']//*[name()='tspan' and @dy='3.5']"));
 List<WebElement> circle_text = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text' and @fill='#ffffff']//*[name()='tspan' and @dy='3.5']"));

 for(int i=0;i<topcompany.size();i++) {
     for(int j=4;j<inlakhs.size();j++) {
         //main_list.add(new String[] {topcompany.get(i).getText(),avg_exp.get(i).getText(),avg_sal.get(i).getText(),inlakhs.get(j).getText(),circle_text.get(i).getText(),inlakhs.get(j+1).getText()});
     }
 }

Body:
Your issues is clearly caused by accessing a list with an index out of range. Run the following code to debug and find out what list in particular is causing the exception:

    List<WebElement> topcompany = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text']//*[name()='tspan' and @dy='4']"));
    List<WebElement> avg_exp = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='245']//*[name()='tspan' and @dy='4']"));
    List<WebElement> avg_sal = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @x='295']//*[name()='tspan' and @dy='4']"));
    List<WebElement> inlakhs = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text' and @fill='#000000']//*[name()='tspan' and @dy='3.5']"));
    List<WebElement> circle_text = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='a']//*[name()='text' and @fill='#ffffff']//*[name()='tspan' and @dy='3.5']"));

    java.util.List<java.util.List<WebElement>> elements = new java.util.ArrayList<java.util.List<WebElement>>();
    for(int i=0;i<topcompany.size();i++)
    {
        for(int j=4;j<inlakhs.size();j++)
        {
            for (java.util.List<WebElement> list : elements) {
                try {
                    WebElement element = list.get(i);
                }
                catch (ArrayIndexOutOfBoundsException e) {
                    System.out.printf("%s caused an exception at index %d", element.toString(), i);
                }
            }
        }
    }