问:
How to fix 'Unchecked cast from MyClass to T'
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

```<code>private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}
</code>```

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.

答:
The solution is to use T as the type here and then you can remove your casts:

```<code>// before:
// SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
// after:
T sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
</code>```

Since according to your comment, getSonarObjectFromPage returns T, where T is the class you pass it in:

```<code><T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)
</code>```

In this case you passed the class klass, which is a Class<T>, so getSonarObjectFromPage will return a T as well.

Body:
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.

Body:
The solution is to use T as the type here and then you can remove your casts:

// before:
// SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
// after:
T sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);

Since according to your comment, getSonarObjectFromPage returns T, where T is the class you pass it in:

<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

In this case you passed the class klass, which is a Class<T>, so getSonarObjectFromPage will return a T as well.


来源: stackexchange

问:
IntelliJ how to zoom in / out
The IntelliJ keymap says:

```<code>Zoom in: Keypad +  =
Zoom out Keypad - -
</code>```

But they have no effect. Anyone have this working?

New info: Now I have added more key-bindings:

```<code>Zoom in: Alt-Shift-=
Zoom out: Alt-Shift-minus
</code>```

But these still have no effect. Does zoom in/zoom out even work at all in IntelliJ?

答:
As Mark Amery suggested in comment,  original answer is no longer working here is working solution:

Answer for IntelliJ IDEA 2022 and later

Right now the best way to switch it on is:

Double click shift, type wheel and switch change font size... to ON

Old Answer forIntelliJ IDEA <=2021

Double click shift, type zoom and switch zoom to on

ContentLicense: CC BY-SA 4.0

Title: IntelliJ how to zoom in / out

Body:
The IntelliJ keymap says:

Zoom in: Keypad +  =
Zoom out Keypad - -

But they have no effect. Anyone have this working?

New info: Now I have added more key-bindings:

Zoom in: Alt-Shift-=
Zoom out: Alt-Shift-minus

But these still have no effect. Does zoom in/zoom out even work at all in IntelliJ?


问:
Remove specific character from string (SQL Server 2012)
I have a view from which I want to remove a specific character in one of the columns. Specifically the character 'B' from the 'Fund' column below.

I tried using the following version of TRIM

```<code>  SELECT
       TRIM('B' FROM [Port_Ticker]) as "Fund"
      ,[BENCH_Ticker] as "Index ID"
      ,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
      ,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
      ,([Active_risk_contrib] / 10000000) as "TE"
      ,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
  FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
  where [BLOCK_FACTOR] = 'Total'
  and [Port_ticker] =
  'B1023'
  order by [VALUE_DATE] asc
</code>```

Which gives me the error

Msg 156, Level 15, State 1, Line 3.
   Incorrect syntax near the keyword 'FROM'.

答:
The Trim() function was introduced in 2017 version.

Naturally, you can't use it in older versions.

There are several ways this can be done, by using replace as M. Kanarkowski demonstrated in his answer, or any of these options:

stuff: STUFF([Port_Ticker], 1, 1, '') As "Fund",

substring: SUBSTRING([Port_Ticker], 2, LEN([Port_Ticker])) As "Fund"

Right: RIGHT([Port_Ticker], LEN([Port_Ticker])-1) As "Fund"

Body:
I have a view from which I want to remove a specific character in one of the columns. Specifically the character 'B' from the 'Fund' column below.

I tried using the following version of TRIM

  SELECT
       TRIM('B' FROM [Port_Ticker]) as "Fund"
      ,[BENCH_Ticker] as "Index ID"
      ,format(cast([VALUE_DATE] as Date),'dd/MM/yyyy') as "Updat"
      ,([Port_Risk_Contrib] / 10000000) as "StDev Fund"
      ,([Active_risk_contrib] / 10000000) as "TE"
      ,([BENCH_RISK_CONTRIB] / 100) as "StDev BM"
  FROM [DM_PORTFOLIO_ANALYSIS].[basedata].[PortfolioRiskFigures]
  where [BLOCK_FACTOR] = 'Total'
  and [Port_ticker] =
  'B1023'
  order by [VALUE_DATE] asc

Which gives me the error

Msg 156, Level 15, State 1, Line 3.
   Incorrect syntax near the keyword 'FROM'.


问:
C# strange with DateTime
I got some strange result for:

```<code>Console.WriteLine(new DateTime(1296346155).ToString());
</code>```

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

答:
That is correct - what were you expecting it to be and why?

The constructor System.DateTime(Int64) takes the number of 100-nanosecond intervals (known as Ticks) since January 1st 0001 (in the Gregorian calendar).

Therefore, 1296346155 / 10000000 gives you the number of seconds, which is 129.6.

Therefore, this should display 2 minutes and 9 seconds since midnight on 1st January 0001.

ContentLicense: CC BY-SA 3.0

Title: C# strange with DateTime

Body:
I got some strange result for:

Console.WriteLine(new DateTime(1296346155).ToString());

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))


问:
Hive partitioned table reads all the partitions despite having a Spark filter
I'm using spark with scala to read a specific Hive partition. The partition is year, month, day, a and b

scala> spark.sql("select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z'").show

But I get this error:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 236 in stage 0.0 failed 4 times, most recent failure: Lost task 236.3 in stage 0.0 (TID 287, server, executor 17): org.apache.hadoop.security.AccessControlException: Permission denied: user=user, access=READ, inode="/path-to-table/table/year=2019/month=2/day=27/a=w/b=x/part-00002":user:group:-rw-rw----

As you can see, spark is trying to read a different partition and I don't have permisions there.

It shouldn't be, because I created a filter and this filter is my partition.

I tried the same query with Hive and it's works perfectly (No access problems)

Hive> select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z';

Why is spark trying to read this partition and Hive doesn't?

There is a Spark configuration that am I missing?

Edit: More information

Some files were created with Hive, others were copied from one server and pasted to our server with different permissions (we can not change the permissions), then they should have refreshed the data.

We are using:
cloudera 5.13.2.1
hive 1.1.0
spark 2.3.0
hadoop 2.6.0
scala 2.11.8
java 1.8.0_144

Show create table

```<code>|CREATE EXTERNAL TABLE Columns and type
PARTITIONED BY (`year` int COMMENT '*', `month` int COMMENT '*', `day` int COMMENT '*', `a` string COMMENT '*', `b` string COMMENT '*')
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
WITH SERDEPROPERTIES (
 'serialization.format' = '1'
)
STORED AS
 INPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
 OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION 'hdfs://path'
TBLPROPERTIES (
 'transient_lastDdlTime' = '1559029332'
)
|
</code>```

答:
You will not be able to read special partition in a table you don't have access to all its partition using Spark-Hive API. Spark is using a Hive table access permission and in Hive you need to take full access to the table.

The reason you can't treat spark-hive as unix access. If you need to do it use spark.csv (or whatever format). Then read the data as file based.

You can simply use spark.csv.read("/path-to-table/table/year=2019/month=2/day=27/a=w/b=x/part-")

If you need to verify my answer, Ignore spark and try to run the same query in Hive shell it will not work as part of hive configurations.

Body:
I'm using spark with scala to read a specific Hive partition. The partition is year, month, day, a and b

scala> spark.sql("select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z'").show

But I get this error:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 236 in stage 0.0 failed 4 times, most recent failure: Lost task 236.3 in stage 0.0 (TID 287, server, executor 17): org.apache.hadoop.security.AccessControlException: Permission denied: user=user, access=READ, inode="/path-to-table/table/year=2019/month=2/day=27/a=w/b=x/part-00002":user:group:-rw-rw----

As you can see, spark is trying to read a different partition and I don't have permisions there.

It shouldn't be, because I created a filter and this filter is my partition.

I tried the same query with Hive and it's works perfectly (No access problems)

Hive> select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z';

Why is spark trying to read this partition and Hive doesn't?

There is a Spark configuration that am I missing?

Edit: More information

Some files were created with Hive, others were copied from one server and pasted to our server with different permissions (we can not change the permissions), then they should have refreshed the data.

We are using:
cloudera 5.13.2.1
hive 1.1.0
spark 2.3.0
hadoop 2.6.0
scala 2.11.8
java 1.8.0_144

Show create table

|CREATE EXTERNAL TABLE Columns and type
PARTITIONED BY (`year` int COMMENT '*', `month` int COMMENT '*', `day` int COMMENT '*', `a` string COMMENT '*', `b` string COMMENT '*')
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
WITH SERDEPROPERTIES (
 'serialization.format' = '1'
)
STORED AS
 INPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
 OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION 'hdfs://path'
TBLPROPERTIES (
 'transient_lastDdlTime' = '1559029332'
)
|


问:
DateDiff years into decimals
I have two dates in which i would like to find the number of years between them, however i would need to show the value to two decimal places.  I have tried the following but i always get a value returned of 0 as all of my dates do not cover a whole year:

```<code>DATEDIFF(yy, @EndDateTime, i.mat_exp_dte)
</code>```

I have then tried finding the number of days between the two and then dividing it by 365, but this still returns 0:

```<code>DATEDIFF(dd, @EndDateTime, i.mat_exp_dte)/365
</code>```

Am confused now as to how to calculate this.  Would i need to convert the DataDiff into a different data type?

答:
```<code>SELECT
(YEAR(@EndDte) - YEAR(@StartDate) +
(MONTH(@EndDate) - MONTH(@StartDate) /100.0 +
(DAY(@EndDate) - DAY(@StartDate) /10000.0)
</code>```

<p>If you need to determinate if there is exactly one year, less then one, or more than one. (=1, <1, >1) </p>

Title: DateDiff years into decimals

Body:
I have two dates in which i would like to find the number of years between them, however i would need to show the value to two decimal places.  I have tried the following but i always get a value returned of 0 as all of my dates do not cover a whole year:

DATEDIFF(yy, @EndDateTime, i.mat_exp_dte)

I have then tried finding the number of days between the two and then dividing it by 365, but this still returns 0:

DATEDIFF(dd, @EndDateTime, i.mat_exp_dte)/365

Am confused now as to how to calculate this.  Would i need to convert the DataDiff into a different data type?

Body:
SELECT
(YEAR(@EndDte) - YEAR(@StartDate) +
(MONTH(@EndDate) - MONTH(@StartDate) /100.0 +
(DAY(@EndDate) - DAY(@StartDate) /10000.0)

If you need to determinate if there is exactly one year, less then one, or more than one. (=1, <1, >1)


问:
Chained sections in ConstrainedLayout
I want to have a layout with a few "sections", each section containing heading and some TextViews, EdiTexts, etc.

I want the sections evenly distributed on the screen, and they can't overlap. So it seems chain is the way to go.

But the problem I always have is how to group some elements in the chain? I don't want to have individual items in each section evenely spaced, I want to have the whole sections evenly spaced. Is it somehow possible? Or will I have to use nested layouts, which pretty much breaks the whole idea of ConstraintLayout?

答: If you have a fixed number of sections, you can use Guidelines to create the "equidistant demarcations" you want. They are easier to think about that chains and you can see them in the layout editor.</p>

Title: Chained sections in ConstrainedLayout


问:
sum of columns with condition in python
I have a dataframe

```<code>id_command  command_status  stage   line_amount global_amount
61  ZeFMAA1 Pending     582.96  582.96
61  UbUjNAAV    Pending     70481.00    582.96
945 0bR8hEQAS   Pending     6400.00 12800.00
</code>```

I would like to add a new column "decision" which is a boolean value (true or false)
True if global_amount of a command is greater than 30% of the sum of line_amount     of a command, and false if is not .

Can you help me to do this ?

Thanks

答:
Use:</p>

```<code>df['decision'] = df['global_amount'].gt(df['line_amount'].mul(.3))
print (df)
   id_command command_status    stage  line_amount  global_amount  decision
0          61        ZeFMAA1  Pending       582.96         582.96      True
1          61       UbUjNAAV  Pending     70481.00         582.96     False
2         945      0bR8hEQAS  Pending      6400.00       12800.00      True
</code>```

Title: sum of columns with condition in python

Body:
I have a dataframe

id_command  command_status  stage   line_amount global_amount
61  ZeFMAA1 Pending     582.96  582.96
61  UbUjNAAV    Pending     70481.00    582.96
945 0bR8hEQAS   Pending     6400.00 12800.00

I would like to add a new column "decision" which is a boolean value (true or false)
True if global_amount of a command is greater than 30% of the sum of line_amount     of a command, and false if is not .

Can you help me to do this ?

Thanks

Body:
Use:

df['decision'] = df['global_amount'].gt(df['line_amount'].mul(.3))
print (df)
   id_command command_status    stage  line_amount  global_amount  decision
0          61        ZeFMAA1  Pending       582.96         582.96      True
1          61       UbUjNAAV  Pending     70481.00         582.96     False
2         945      0bR8hEQAS  Pending      6400.00       12800.00      True


问:
Why my function does nos continue executing the other cases when data is not found in one?
I use exception and continue statements but even though i gett error ORA-

```<code>06503. 00000 -  "PL/SQL: Function returned without value"
*Cause:    A call to PL/SQL function completed, but no RETURN statement was
           executed.
</code>```

I tries using an exception and continue.

```<code>EXECUTE IMMEDIATE v_sql INTO v_valor;

  EXCEPTION
   WHEN NO_DATA_FOUND THEN v_valor:= 0 ;

return result;

-- In the loop
 CONTINUE WHEN v_valorNuevo = 0;
</code>```

I expect to get the rest cases when one case has no data.

答: It seems you return result in the exception case only. All cases need to return a value for a function.

Body:
I use exception and continue statements but even though i gett error ORA-

06503. 00000 -  "PL/SQL: Function returned without value"
*Cause:    A call to PL/SQL function completed, but no RETURN statement was
           executed.

I tries using an exception and continue.

EXECUTE IMMEDIATE v_sql INTO v_valor;

  EXCEPTION
   WHEN NO_DATA_FOUND THEN v_valor:= 0 ;

return result;

-- In the loop
 CONTINUE WHEN v_valorNuevo = 0;

I expect to get the rest cases when one case has no data.


问:
route not found on ajax post
I'm trying to create a dependent select using ajax, here is my JS

```<code>$("#make").change(function(){
    $.ajax({
        url: "{{ url('chauffeur/ajax_vehicle_model') }}?make=" + $(this).val(),
        method: 'GET',
        success: function(data) {
            $('#model').html(data.html);
        }
    });
});
</code>```

My routing looks like this

```<code>Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('chauffeur/ajax_vehicle_model','Admin\ChauffeurController@get_vehicle_model');
});
</code>```

And in my controller I have this

```<code>public function get_vehicle_model(Request $request)
{
    ....
}
</code>```

But I get a 404 error, any idea what I'm doing wrong here?

答:
Try to change your route like this

routing file

```<code>Route::get('chauffeur/ajax_vehicle_model', ['as'=> 'chauffeur.ajax.vehicle',  'uses' => 'Admin\ChauffeurController@get_vehicle_model']);
</code>```

Now your js code should be like this (if your js code is in .blade.php file)

```<code>$("#make").change(function(){
    $.ajax({
        url: "{{ route('chauffeur.ajax.vehicle') }}?make=" + $(this).val(),
        method: 'GET',
        success: function(data) {
            $('#model').html(data.html);
        }
    });
});
</code>```

try this.

Title: route not found on ajax post

Body:
I'm trying to create a dependent select using ajax, here is my JS

$("#make").change(function(){
    $.ajax({
        url: "{{ url('chauffeur/ajax_vehicle_model') }}?make=" + $(this).val(),
        method: 'GET',
        success: function(data) {
            $('#model').html(data.html);
        }
    });
});

My routing looks like this

Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('chauffeur/ajax_vehicle_model','Admin\ChauffeurController@get_vehicle_model');
});

And in my controller I have this

public function get_vehicle_model(Request $request)
{
    ....
}

But I get a 404 error, any idea what I'm doing wrong here?

Body:
Try to change your route like this

routing file

Route::get('chauffeur/ajax_vehicle_model', ['as'=> 'chauffeur.ajax.vehicle',  'uses' => 'Admin\ChauffeurController@get_vehicle_model']);

Now your js code should be like this (if your js code is in .blade.php file)

$("#make").change(function(){
    $.ajax({
        url: "{{ route('chauffeur.ajax.vehicle') }}?make=" + $(this).val(),
        method: 'GET',
        success: function(data) {
            $('#model').html(data.html);
        }
    });
});

try this.


问:
Is there away to change previous domain address to newly assigned elastic ip address
Is there a way to reconfigure the previous instance's IP address to the newly assigned IP address.

After I configured all my instance and I tried to assign the elastic IP. I found that the IP is changed. therefore the website under apache2 /var/www/html was no longer valid / unreachable.

is there any way that I can change old IP to new IP address?

NEW: ec2-13-237-246-127.ap-southeast-2.compute.amazonaws.com

will redirect to

OLD:http://ec2-54-206-98-171.ap-southeast-2.compute.amazonaws.com/

since I changed to associate a new IP into this instance.

答:
The old DNS will not be available. These DNS entries are auto generated by AWS. If you notice the format, you would see,
ec2-<ip-address>.<region>.compute.amazonaws.com.

If you want a static DNS name, you must created a domain, add an address record pointing to your instance's public IP.


问:
How can i set retention period for state stores created by Kafka streams
I am using Streams DSL and doing stateful aggregation(Readin data from a topic, aggregating and writing data to another topic). How can i reduce the retention period of data that is written to the state store? Right now my infra team is saying that the data is retained for 5 years in the state store and i have to reduce that. Is there a specific configuration that i can set for how long the data should be retained?</p>

```<code>    KTable<Windowed<String>, JSONObject> kTable = filteredKstream
            .groupBy((key, value) -> getNewKey(value),
                    Grouped.with(Serdes.String(), new JSONObjectSerde()))
            .windowedBy(windows).aggregate(() -> {
                SampleData sampleData = new SampleData();
                return new JSONObject(mapperUtils.writeValueAsString(sampleData, mapper));
            } , (key, value, aggregate) -> {
                return getAggregateValue(aggregate, value);
            } , Materialized
                    .<String, JSONObject, WindowStore<Bytes, byte[]>> as(
                            "sample-store")
                    .withKeySerde(Serdes.String())
                    .withValueSerde(jsonSerde));
</code>```

答:
You can use Materialized#withRetention() to set the retention period of window and session stores.

https://kafka.apache.org/22/javadoc/org/apache/kafka/streams/kstream/Materialized.html#withRetention-java.time.Duration-

Body:
I am using Streams DSL and doing stateful aggregation(Readin data from a topic, aggregating and writing data to another topic). How can i reduce the retention period of data that is written to the state store? Right now my infra team is saying that the data is retained for 5 years in the state store and i have to reduce that. Is there a specific configuration that i can set for how long the data should be retained?

    KTable<Windowed<String>, JSONObject> kTable = filteredKstream
            .groupBy((key, value) -> getNewKey(value),
                    Grouped.with(Serdes.String(), new JSONObjectSerde()))
            .windowedBy(windows).aggregate(() -> {
                SampleData sampleData = new SampleData();
                return new JSONObject(mapperUtils.writeValueAsString(sampleData, mapper));
            } , (key, value, aggregate) -> {
                return getAggregateValue(aggregate, value);
            } , Materialized
                    .<String, JSONObject, WindowStore<Bytes, byte[]>> as(
                            "sample-store")
                    .withKeySerde(Serdes.String())
                    .withValueSerde(jsonSerde));


答:
Based on :

sum of line_amount of a command

Use df.groupby() to group on the id_command and use transform to get sum distributed on each row. Then multiply by 0.3 and compare by series.gt():

```<code>df['decision']=df.global_amount.gt(df.groupby('id_command').line_amount.transform('sum')*0.3)
print(df)
</code>```

```<code>   id_command command_status    stage  line_amount  global_amount  decision
0          61        ZeFMAA1  Pending       582.96         582.96     False
1          61       UbUjNAAV  Pending     70481.00         582.96     False
2         945      0bR8hEQAS  Pending      6400.00       12800.00      True
</code>```

Title: sum of columns with condition in python

Body:
Based on :

sum of line_amount of a command

Use df.groupby() to group on the id_command and use transform to get sum distributed on each row. Then multiply by 0.3 and compare by series.gt():

df['decision']=df.global_amount.gt(df.groupby('id_command').line_amount.transform('sum')*0.3)
print(df)

   id_command command_status    stage  line_amount  global_amount  decision
0          61        ZeFMAA1  Pending       582.96         582.96     False
1          61       UbUjNAAV  Pending     70481.00         582.96     False
2         945      0bR8hEQAS  Pending      6400.00       12800.00      True


问:
Creating new data object set from multiple nested arrays
I've have a complex data structure with multiple nested arrays in place.

Below is the current structure

```<code>var contentData = {
  data: {
    content: [
      {
        type: "column",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              },
              {
                type: "ordered-item",
                text: "Item 1"
              },
              {
                type: "unordered-item",
                text: "Item 2"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text 2"
              }
            ]
          }
        ]
      }
    ]
  }
}
</code>```

So What I wanted is,

I wanted to group all the ordered-item & unordered-item into a new object like {type: 'list', items:[all list items]}.

I need to extract all items which are inside sub and push it to new object embedded and it should placed in the root level like below,

{type:"acc-item",embedded:[{type:"heading-1",text:"Heading Text 2"}]};

So What I've done so far,

I can able to group acc-item, but not the ordered-item & unordered-item.

So my final expected result should like this,

```<code>[{
  "type": "column",
  "embedded": [
    {
      "type": "heading-1",
      "text": "Heading Text"
    }
  ]
},
{
  "type": "acc-group",
  "items": [
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text"
        },
        {
          "type": "list",
          "items": [
            {
              "type": "ordered-item",
              "text": "Item 1"
            },
            {
              "type": "unordered-item",
              "text": "Item 2"
            }
          ]
        }
      ]
    },
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text 2"
        }
      ]
    }
  ]
}]
</code>```

Below is my code,

var group,contentData={data:{content:[{type:"column",sections:[{sub:[{type:"heading-1",text:"Heading Text"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text"},{type:"ordered-item",text:"Item 1"},{type:"unordered-item",text:"Item 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text 2"}]}]}]}},types=[["list",["ordered-item","unordered-item"]],["accordion",["acc-item"]]];

var result = contentData.data.content.reduce((r, o) => {
  var type = (types.find(({ 1: values }) => values.indexOf(o.type) > -1)|| {})[0];
  if (!type) {
    r.push(o);
    group = undefined;
    return r;
  }
  if (!group || group.type !== type) {
    group = { type, items: [] };
    r.push(group);
  }
  group.items.push(o);
  return r;
}, []);

document.body.innerHTML = '```' + JSON.stringify(result, null, '  ') + '```';```

答:
You could store the last items array as well as the last embedded array and use them until a column type is found.

var contentData = { data: { content: [{ type: "column", sections: [{ sub: [{ type: "heading-1", text: "Heading Text" }] }] }, { type: "acc-item", sections: [{ sub: [{ type: "heading-1", text: "Heading Text" }, { type: "ordered-item", text: "Item 1" }, { type: "unordered-item", text: "Item 2" }] }] }, { type: "acc-item", sections: [{ sub: [{ type: "heading-1", text: "Heading Text 2" }] }] }] } },
    list = ["ordered-item", "unordered-item"],
    lastItems, lastEmbedded,
    result = contentData.data.content.reduce((r, { type, sections }) => {
        if (type === 'column') {
            r.push({ type, embedded: sections.reduce((q, { sub }) => q.concat(sub), []) });
            lastItems = undefined;
            lastEmbedded = undefined;
            return r;
        }
        if (!lastItems) r.push({ type: "acc-group", items: lastItems = [] });
        lastItems.push(...sections.map(({ sub }) => ({
            type,
            embedded: sub.reduce((q, o) => {
                if (list.includes(o.type)) {
                    if (!lastEmbedded) q.push({ type: 'list', items: lastEmbedded = [] });
                    lastEmbedded.push(o);
                } else {
                    q.push(o);
                    lastEmbedded = undefined;
                }
                return q;
            }, [])
        })));
        return r;
    }, []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I've have a complex data structure with multiple nested arrays in place.

Below is the current structure

var contentData = {
  data: {
    content: [
      {
        type: "column",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text"
              },
              {
                type: "ordered-item",
                text: "Item 1"
              },
              {
                type: "unordered-item",
                text: "Item 2"
              }
            ]
          }
        ]
      },
      {
        type: "acc-item",
        sections: [
          {
            sub: [
              {
                type: "heading-1",
                text: "Heading Text 2"
              }
            ]
          }
        ]
      }
    ]
  }
}

So What I wanted is,

I wanted to group all the ordered-item & unordered-item into a new object like {type: 'list', items:[all list items]}.

I need to extract all items which are inside sub and push it to new object embedded and it should placed in the root level like below,

{type:"acc-item",embedded:[{type:"heading-1",text:"Heading Text 2"}]};

So What I've done so far,

I can able to group acc-item, but not the ordered-item & unordered-item.

So my final expected result should like this,

[{
  "type": "column",
  "embedded": [
    {
      "type": "heading-1",
      "text": "Heading Text"
    }
  ]
},
{
  "type": "acc-group",
  "items": [
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text"
        },
        {
          "type": "list",
          "items": [
            {
              "type": "ordered-item",
              "text": "Item 1"
            },
            {
              "type": "unordered-item",
              "text": "Item 2"
            }
          ]
        }
      ]
    },
    {
      "type": "acc-item",
      "embedded": [
        {
          "type": "heading-1",
          "text": "Heading Text 2"
        }
      ]
    }
  ]
}]

Below is my code,

var group,contentData={data:{content:[{type:"column",sections:[{sub:[{type:"heading-1",text:"Heading Text"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text"},{type:"ordered-item",text:"Item 1"},{type:"unordered-item",text:"Item 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text 2"}]}]}]}},types=[["list",["ordered-item","unordered-item"]],["accordion",["acc-item"]]];

var result = contentData.data.content.reduce((r, o) => {
  var type = (types.find(({ 1: values }) => values.indexOf(o.type) > -1)|| {})[0];
  if (!type) {
    r.push(o);
    group = undefined;
    return r;
  }
  if (!group || group.type !== type) {
    group = { type, items: [] };
    r.push(group);
  }
  group.items.push(o);
  return r;
}, []);

document.body.innerHTML = '
' + JSON.stringify(result, null, '  ') + '
';

Body:
You could store the last items array as well as the last embedded array and use them until a column type is found.

var contentData = { data: { content: [{ type: "column", sections: [{ sub: [{ type: "heading-1", text: "Heading Text" }] }] }, { type: "acc-item", sections: [{ sub: [{ type: "heading-1", text: "Heading Text" }, { type: "ordered-item", text: "Item 1" }, { type: "unordered-item", text: "Item 2" }] }] }, { type: "acc-item", sections: [{ sub: [{ type: "heading-1", text: "Heading Text 2" }] }] }] } },
    list = ["ordered-item", "unordered-item"],
    lastItems, lastEmbedded,
    result = contentData.data.content.reduce((r, { type, sections }) => {
        if (type === 'column') {
            r.push({ type, embedded: sections.reduce((q, { sub }) => q.concat(sub), []) });
            lastItems = undefined;
            lastEmbedded = undefined;
            return r;
        }
        if (!lastItems) r.push({ type: "acc-group", items: lastItems = [] });
        lastItems.push(...sections.map(({ sub }) => ({
            type,
            embedded: sub.reduce((q, o) => {
                if (list.includes(o.type)) {
                    if (!lastEmbedded) q.push({ type: 'list', items: lastEmbedded = [] });
                    lastEmbedded.push(o);
                } else {
                    q.push(o);
                    lastEmbedded = undefined;
                }
                return q;
            }, [])
        })));
        return r;
    }, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
python os.rename can't find a file, even though the code check it exists
I have a strange error:

in the code:

```<code>if os.path.isfile(df_file):
    os.rename(df_file, df_file + '_backup.parquet')
</code>```

I am getting an error:

```<code>    os.rename(df_file, df_file + '_backup.parquet')
FileNotFoundError: [Errno 2] No such file or directory: '/data/5faf97ca101ae0413c383678186bf601.parquet' ->
    '/data/5faf97ca101ae0413c383678186bf601.parquet_backup.parquet'
</code>```

Even though I checked and the file exist!
what could be the problem ?
The source file and directory are obviously exist

The code is called within a flask thread.

答: <em>'/data/5faf97ca101ae0413c383678186bf601.parquet_backup.parquet'</em> This is an absolute path, which points to the data directory under the root path. I guess you want to use a relative path,'./data/5faf97ca101ae0413c383678186bf601.parquet_backup.parquet' </p>

Body:
I have a strange error:

in the code:

if os.path.isfile(df_file):
    os.rename(df_file, df_file + '_backup.parquet')

I am getting an error:

    os.rename(df_file, df_file + '_backup.parquet')
FileNotFoundError: [Errno 2] No such file or directory: '/data/5faf97ca101ae0413c383678186bf601.parquet' ->
    '/data/5faf97ca101ae0413c383678186bf601.parquet_backup.parquet'

Even though I checked and the file exist!
what could be the problem ?
The source file and directory are obviously exist

The code is called within a flask thread.

Body: '/data/5faf97ca101ae0413c383678186bf601.parquet_backup.parquet' This is an absolute path, which points to the data directory under the root path. I guess you want to use a relative path,'./data/5faf97ca101ae0413c383678186bf601.parquet_backup.parquet'


问:
WPF: How to hide the empty Hyperlink?
In the previous question of mine, I have asked how to hide an empty TextBlock, so that it doesn't take space in the panel. I have a new challenge now. How am I supposed to hide an empty Hyperlink:

```<code><TextBlock>
  <Hyperlink
      NavigateUri="{Binding Path=Email}"
      RequestNavigate="Hyperlink_RequestNavigate">
    <TextBlock Text="{Binding Path=Email}" />
  </Hyperlink>
</TextBlock>
</code>```

This is what made the hiding possible in the previous question:

```<code><TextBlock.Style>
  <Style TargetType="TextBlock">
    <Style.Triggers>
      <Trigger Property="Text" Value="">
        <Setter Property="Visibility" Value="Collapsed" />
      </Trigger>
    </Style.Triggers>
  </Style>
</TextBlock.Style>
</code>```

Providing this style on first TextBlock won't work because the Text property is not set. Providing style on Hyperlink doesn't hide the parent TextBlock and same happens if I try to hide the TextBlock inside the Hyperlink.

I am certain that my style needs to be applied on the Hyperlink, but the trigger inside should target the Visibility property of the 'Hyperlink's parentTextBlock`. What is the style supposed to look like?

答:
The solution provided by Foovanadil that solves the similar issue by implementing visibility converter works the best in my opinion. It is the easiest to implement and can be reused whenever needed.

The converter should be implemented like this:

```<code>using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

public class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                                                            CultureInfo culture)
    {
        if (string.IsNullOrEmpty(value as string))
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                                                             CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
</code>```

}

And used like this:

```<code><Window.Resources>
    <!-- Visibility converter -->
    <converters:VisibilityConverter x:Key="visibleConv" />
</Window.Resources>
...
<TextBlock Visibility="{Binding Something, Converter={StaticResource visibleConv}}">
    <Hyperlink NavigateUri="{Binding Something}">
        <TextBlock Text="{Binding Something}" />
    </Hyperlink>
</TextBlock>
</code>```

All credits go to the original solution provider: Foovanadil

ContentLicense: CC BY-SA 2.5

Title: WPF: How to hide the empty Hyperlink?

Body:
In the previous question of mine, I have asked how to hide an empty TextBlock, so that it doesn't take space in the panel. I have a new challenge now. How am I supposed to hide an empty Hyperlink:

<TextBlock>
  <Hyperlink
      NavigateUri="{Binding Path=Email}"
      RequestNavigate="Hyperlink_RequestNavigate">
    <TextBlock Text="{Binding Path=Email}" />
  </Hyperlink>
</TextBlock>

This is what made the hiding possible in the previous question:

<TextBlock.Style>

  </Style>
</TextBlock.Style>

Providing this style on first TextBlock won't work because the Text property is not set. Providing style on Hyperlink doesn't hide the parent TextBlock and same happens if I try to hide the TextBlock inside the Hyperlink.

I am certain that my style needs to be applied on the Hyperlink, but the trigger inside should target the Visibility property of the 'Hyperlink's parentTextBlock`. What is the style supposed to look like?

Body:
The solution provided by Foovanadil that solves the similar issue by implementing visibility converter works the best in my opinion. It is the easiest to implement and can be reused whenever needed.

The converter should be implemented like this:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

public class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                                                            CultureInfo culture)
    {
        if (string.IsNullOrEmpty(value as string))
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                                                             CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

}

And used like this:

<Window.Resources>
    <!-- Visibility converter -->
    <converters:VisibilityConverter x:Key="visibleConv" />
</Window.Resources>
...
<TextBlock Visibility="{Binding Something, Converter={StaticResource visibleConv}}">
    <Hyperlink NavigateUri="{Binding Something}">
        <TextBlock Text="{Binding Something}" />
    </Hyperlink>
</TextBlock>

All credits go to the original solution provider: Foovanadil


问:
Remove link to single page from Woocommerce product page
I have been trying to remove the link to the single product page of the Woocommerce plugin. On this forum many people asking questions about it and have read most of them. But nearly all of these questions are old. However as far as I understand now I have to use the functions.php and content-page.php to achieve this.

So after reading all the info on the i-net I came up with this code in the functions.php (which is inside my child theme folder)

```<code>if ( !function_exists('add_remove_hooks')):
function add_remove_hooks() {
    remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
    }
endif;
add_action( 'init', 'add_remove_hooks' );
</code>```

I have tried all kind of variants like only put in the remove_action rows, not wrapt in a function or use an other action in the add_action function, but none of them seem to work. The syntax, however, is as it should be.

The (part of)content-page.php looks like

```<code><li <?php post_class( $classes ); ?>>
    <?php do_action( 'woocommerce_before_shop_loop_item' ); ?>

        <?php
            /**
             * woocommerce_before_shop_loop_item_title hook
             *
             * @hooked woocommerce_show_product_loop_sale_flash - 10
             * @hooked woocommerce_template_loop_product_thumbnail - 10
             */
            do_action( 'woocommerce_before_shop_loop_item_title' ); ?>

        <?php if($product_style == 'classic') {
            do_action( 'woocommerce_shop_loop_item_title' );
            do_action( 'woocommerce_after_shop_loop_item_title' );
        } ?>

    <?php do_action( 'woocommerce_after_shop_loop_item' ); ?>

</li>
</code>```

I don't know how to debug in PHP, but I know the files are "used" by WP because if I change something in one of these files I see it on screen. However, the links are still in place. The remove_action is not working.

Does anyobody have another suggestion on how to accomplish this? Of what to look for?

Used WP 5.2 and Woocommerce 3.0

UPDATE:

Thanks to Alfaraz I was able to solve the problem. Putting the remove_actions in the functions.php of the child theme now also works. I didn't realize I also had to set the active theme in WP to my Child theme. That did the trick in the end.

答:
Try this:</p>

```<code>function remove_direct_link_to_product_page() {
 if ( is_product() && is_product_category(array('category-slug') ) ) {
remove_action( ‘woocommerce_before_shop_loop_item’,
‘woocommerce_template_loop_product_link_open’, 10 );
remove_action( ‘woocommerce_after_shop_loop_item’,
‘woocommerce_template_loop_product_link_close’, 5 );
 }
 }
</code>```

Body:
I have been trying to remove the link to the single product page of the Woocommerce plugin. On this forum many people asking questions about it and have read most of them. But nearly all of these questions are old. However as far as I understand now I have to use the functions.php and content-page.php to achieve this.

So after reading all the info on the i-net I came up with this code in the functions.php (which is inside my child theme folder)

if ( !function_exists('add_remove_hooks')):
function add_remove_hooks() {
    remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
    }
endif;
add_action( 'init', 'add_remove_hooks' );

I have tried all kind of variants like only put in the remove_action rows, not wrapt in a function or use an other action in the add_action function, but none of them seem to work. The syntax, however, is as it should be.

The (part of)content-page.php looks like

<li <?php post_class( $classes ); ?>>
    <?php do_action( 'woocommerce_before_shop_loop_item' ); ?>

        <?php
            /**
             * woocommerce_before_shop_loop_item_title hook
             *
             * @hooked woocommerce_show_product_loop_sale_flash - 10
             * @hooked woocommerce_template_loop_product_thumbnail - 10
             */
            do_action( 'woocommerce_before_shop_loop_item_title' ); ?>

        <?php if($product_style == 'classic') {
            do_action( 'woocommerce_shop_loop_item_title' );
            do_action( 'woocommerce_after_shop_loop_item_title' );
        } ?>

    <?php do_action( 'woocommerce_after_shop_loop_item' ); ?>

I don't know how to debug in PHP, but I know the files are "used" by WP because if I change something in one of these files I see it on screen. However, the links are still in place. The remove_action is not working.

Does anyobody have another suggestion on how to accomplish this? Of what to look for?

Used WP 5.2 and Woocommerce 3.0

UPDATE:

Thanks to Alfaraz I was able to solve the problem. Putting the remove_actions in the functions.php of the child theme now also works. I didn't realize I also had to set the active theme in WP to my Child theme. That did the trick in the end.

Body:
Try this:

function remove_direct_link_to_product_page() {
 if ( is_product() && is_product_category(array('category-slug') ) ) {
remove_action( ‘woocommerce_before_shop_loop_item’,
‘woocommerce_template_loop_product_link_open’, 10 );
remove_action( ‘woocommerce_after_shop_loop_item’,
‘woocommerce_template_loop_product_link_close’, 5 );
 }
 }


问:
What is local component in Yii2?
In the documentation "info" section Yii 2 says:

Using too many application components can potentially make your code harder to test and maintain. In many cases, you can simply create a local component and use it when needed.

What is local component? How create it?

答:
Local component it is just local instance of component. So instead using:

```<code>$value = Yii::$app->cache123->get($key);
</code>```

which will force you to define cache123 component in app config, you can use local instance:

```<code>$cache = new ApcCache();
$value = $cache->get($key);
</code>```

Or assign it to module for example:

```<code>class MyModule extends \yii\base\Module {

    private $_cache;

    public function getCache(): \yii\caching\Cache {
        if ($this->_cache === null) {
            $this->_cache = new ApcCache();
        }

        return $this->_cache;
    }
}
</code>```

And then in controller you can use:

```<code>$value = $this->module->getCache()->get($key);
</code>```

You can also define components in module config:

```<code>'modules' => [
    'myModule' => [
        'class' => MyModule::class,
        'components' => [
            'cache' => FileCache::class,
        ],
    ],
],
</code>```

And then in controller you can use:

```<code>$value = $this->module->cache->get($key);
</code>```

In this way you can split your app into multiple independent modules with separate components. It may be easier to maintain this if you have large number of components if they're grouped in modules, especially if some of them are used only in one place or one module.

Title: What is local component in Yii2?

Body:
Local component it is just local instance of component. So instead using:

$value = Yii::$app->cache123->get($key);

which will force you to define cache123 component in app config, you can use local instance:

$cache = new ApcCache();
$value = $cache->get($key);

Or assign it to module for example:

class MyModule extends \yii\base\Module {

    private $_cache;

    public function getCache(): \yii\caching\Cache {
        if ($this->_cache === null) {
            $this->_cache = new ApcCache();
        }

        return $this->_cache;
    }
}

And then in controller you can use:

$value = $this->module->getCache()->get($key);

You can also define components in module config:

'modules' => [
    'myModule' => [
        'class' => MyModule::class,
        'components' => [
            'cache' => FileCache::class,
        ],
    ],
],

And then in controller you can use:

$value = $this->module->cache->get($key);

In this way you can split your app into multiple independent modules with separate components. It may be easier to maintain this if you have large number of components if they're grouped in modules, especially if some of them are used only in one place or one module.


问:
I cannot return an object until and unless the curly bracket is placed right next to the return statement
```<code>compClasses: function() {
    /* IT DOES NOT WORK LIKE THIS */
    return
    {
        major: this.valA,
        minor: this.valB
    }
    /* BUT WORKS LIKE THIS KINDLY TAKE NOTICE OF THE PLACEMENT OF CURLY BRACKETS */
    return {
        major: this.valA,
        minor: this.valB
    }
}
</code>```

答:
JavaScript automatically inserts semicolons (or ends statements) when needed. If you write

```<code>return
{
    major: this.valA,
    minor: this.valB
}
</code>```

the return statement is executed directly (like if you'd write return;). If you write

```<code>return {
    major: this.valA,
    minor: this.valB
}
</code>```

the complete object is returned instead. The semicolon is added after the object.

The rules for automatic insertions of semicolons are as followed (source):

when the next line starts with code that breaks the current one (code can spawn on multiple lines)

when the next line starts with a }, closing the current block

when the end of the source code file is reached

when there is a return statement on its own line

when there is a break statement on its own line

when there is a throw statement on its own line

when there is a continue statement on its own line

Body:
JavaScript automatically inserts semicolons (or ends statements) when needed. If you write

return
{
    major: this.valA,
    minor: this.valB
}

the return statement is executed directly (like if you'd write return;). If you write

return {
    major: this.valA,
    minor: this.valB
}

the complete object is returned instead. The semicolon is added after the object.

The rules for automatic insertions of semicolons are as followed (source):

when the next line starts with code that breaks the current one (code can spawn on multiple lines)

when the next line starts with a }, closing the current block

when the end of the source code file is reached

when there is a return statement on its own line

when there is a break statement on its own line

when there is a throw statement on its own line

when there is a continue statement on its own line


问:
FirebaseAuth.getInstance().signOut() doesn't signout
I try to signout user from firebase but after i close my app and open again the user is stills connect

I tried the regular signout of user from firebase and it not solve the problem.
I am wondering what could cause the problem

 logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                Intent picture_intent = new Intent(Dashboard.this,LoginActivity.class);
                startActivity(picture_intent );
            }
        });
```

<p>my check if user connect:</p>

```@Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser currentUser = firebaseAuth.getCurrentUser();
        if(currentUser != null)
        {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            int again = preferences.getInt(String.valueOf(R.string.remember_me), 0);
            if(again == 0)
            {
                Intent i = new Intent(getApplicationContext(), PagerActivity.class);
                startActivity(i);
            }
            else
            {
                Intent i = new Intent(getApplicationContext(), Dashboard.class);
                startActivity(i);
            }

        }
    }
```

答:
Why you are using SharedPreferences? If you are maintaining the session with firebase you don't need sharedpreferences.
By the way your code seems correct. Try doing the following modification with your intent after calling the logout function.

```<code>FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getActivity(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
</code>```

And completely delete your onAuthStateChanged() method (Because I cannot see your complete code, and may be you are messing the things inside this method) so just for testing remove this method, and add the flags to your intent as I said.

If it is working let me know.

Hope this will help you. Thanks

Body:
I try to signout user from firebase but after i close my app and open again the user is stills connect

I tried the regular signout of user from firebase and it not solve the problem.
I am wondering what could cause the problem

 logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                Intent picture_intent = new Intent(Dashboard.this,LoginActivity.class);
                startActivity(picture_intent );
            }
        });

my check if user connect:

@Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser currentUser = firebaseAuth.getCurrentUser();
        if(currentUser != null)
        {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            int again = preferences.getInt(String.valueOf(R.string.remember_me), 0);
            if(again == 0)
            {
                Intent i = new Intent(getApplicationContext(), PagerActivity.class);
                startActivity(i);
            }
            else
            {
                Intent i = new Intent(getApplicationContext(), Dashboard.class);
                startActivity(i);
            }

        }
    }

Body:
Why you are using SharedPreferences? If you are maintaining the session with firebase you don't need sharedpreferences.
By the way your code seems correct. Try doing the following modification with your intent after calling the logout function.

FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getActivity(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

And completely delete your onAuthStateChanged() method (Because I cannot see your complete code, and may be you are messing the things inside this method) so just for testing remove this method, and add the flags to your intent as I said.

If it is working let me know.

Hope this will help you. Thanks


问:
Is it possible to transfer authentication from Webbrowser to WebRequest
I'm using webbrowser control to login any site. And then i want to download some sub page html using WebRequest (or WebClient). This links must requires authentication.

How to transfer Webbrowser authentication information to Webrequest or Webclient?

答:
If the question is only "How to transfer Webbrowser authentication information to Webrequest or Webclient?" this code is enough:

You can call the GetUriCookieContainer method that returns you a CookieContainer that can be used for subsequent call with WebRequest object.

```<code>  [DllImport("wininet.dll", SetLastError = true)]
    public static extern bool InternetGetCookieEx(
        string url,
        string cookieName,
        StringBuilder cookieData,
        ref int size,
        Int32  dwFlags,
        IntPtr  lpReserved);

    private const Int32 InternetCookieHttponly = 0x2000;

/// <summary>
/// Gets the URI cookie container.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public static CookieContainer GetUriCookieContainer(Uri uri)
{
    CookieContainer cookies = null;
    // Determine the size of the cookie
    int datasize = 8192 * 16;
    StringBuilder cookieData = new StringBuilder(datasize);
    if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
    {
        if (datasize < 0)
            return null;
        // Allocate stringbuilder large enough to hold the cookie
        cookieData = new StringBuilder(datasize);
        if (!InternetGetCookieEx(
            uri.ToString(),
            null, cookieData,
            ref datasize,
            InternetCookieHttponly,
            IntPtr.Zero))
            return null;
    }
    if (cookieData.Length > 0)
    {
        cookies = new CookieContainer();
        cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
    }
    return cookies;
}
</code>```

Body:
If the question is only "How to transfer Webbrowser authentication information to Webrequest or Webclient?" this code is enough:

You can call the GetUriCookieContainer method that returns you a CookieContainer that can be used for subsequent call with WebRequest object.

  [DllImport("wininet.dll", SetLastError = true)]
    public static extern bool InternetGetCookieEx(
        string url,
        string cookieName,
        StringBuilder cookieData,
        ref int size,
        Int32  dwFlags,
        IntPtr  lpReserved);

    private const Int32 InternetCookieHttponly = 0x2000;

/// <summary>
/// Gets the URI cookie container.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public static CookieContainer GetUriCookieContainer(Uri uri)
{
    CookieContainer cookies = null;
    // Determine the size of the cookie
    int datasize = 8192 * 16;
    StringBuilder cookieData = new StringBuilder(datasize);
    if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
    {
        if (datasize < 0)
            return null;
        // Allocate stringbuilder large enough to hold the cookie
        cookieData = new StringBuilder(datasize);
        if (!InternetGetCookieEx(
            uri.ToString(),
            null, cookieData,
            ref datasize,
            InternetCookieHttponly,
            IntPtr.Zero))
            return null;
    }
    if (cookieData.Length > 0)
    {
        cookies = new CookieContainer();
        cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
    }
    return cookies;
}


问:
Adding a legend to a ggplot2
I try to add a legend to my ggplot2 plots but it is not working out. Also the command show.legend does not change anything

Following the answer of this question (Adding manual legend in ggplot) I tried scal_colour_manueal but it did not work out

```<code>library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, group = kpi) ) +
  geom_line(color=color1, show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, group = kpi), colour = color2 , show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)
</code>```

How can I add a legend to this plot?

答:
Another hint: ggplot works best, when data is "tidy" (see e.g. Hadley Wickham's R for Data Science). Then solution could look like this (the gather-call reshapes / tidies the data so that it suits better to ggplot):

```<code>library(tidyverse)
library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

data <- gather(data, key = value_name, value = value, -Week, -kpi) ## tidy the data with "gahter"

ggplot(data, aes(x = Week, y = value, colour = value_name, group = value_name)) +
    geom_line() +
    facet_wrap(kpi ~ ., ncol = 1) +
    scale_colour_manual(name="Legend", values=c(color1, color2))
</code>```

Title: Adding a legend to a ggplot2

Body:
I try to add a legend to my ggplot2 plots but it is not working out. Also the command show.legend does not change anything

Following the answer of this question (Adding manual legend in ggplot) I tried scal_colour_manueal but it did not work out

library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, group = kpi) ) +
  geom_line(color=color1, show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, group = kpi), colour = color2 , show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)

How can I add a legend to this plot?

Body:
Another hint: ggplot works best, when data is "tidy" (see e.g. Hadley Wickham's R for Data Science). Then solution could look like this (the gather-call reshapes / tidies the data so that it suits better to ggplot):

library(tidyverse)
library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

data <- gather(data, key = value_name, value = value, -Week, -kpi) ## tidy the data with "gahter"

ggplot(data, aes(x = Week, y = value, colour = value_name, group = value_name)) +
    geom_line() +
    facet_wrap(kpi ~ ., ncol = 1) +
    scale_colour_manual(name="Legend", values=c(color1, color2))


问:
How to Properly Use wx.CallLater in wx.Python
I want to loop and call a function every 1000 milliseconds with wx.CallLater. I implemented this (see below), but it does not factor in the delay - it seems to execute automatically. How can I get this to wait 1000 milliseconds between function calls?

This function is within a class. In my main module, I instantiate an object of this class and call the task_loop function. I intend to keep the loop going until will_break is set to True, and task_loop returns the work_session_agenda in the main module. Thank you for your help!

```<code>def task_loop(self, duration, window, task, work_session_agenda, start, completed):

    will_break = False
    will_continue = False

    duration -= datetime.timedelta(seconds=1)
</code>```

More code in here - which, depending on conditionals, sets the values of will_break and will_continue

```<code>    if will_break:
        print('BREAKING')
        return work_session_agenda
    else:
        print('GOT HERE')
        timer = wx.CallLater(1000, self.task_loop, duration, window, task, work_session_agenda, start, completed)
</code>```

答:
Below you can find an example with wx.CallLater and with wx.Timer as suggested in the comments. Notice that in both cases the GUI remains responsive during the waiting time.

With wx.Timer

```<code>import wx
import time

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="With wx.Timer", size=(500,500))

        #### Variables
        self.will_continue = True
        self.i = 0
        self.total = 5
        self.mili = 1000

        #### Widgets
        # Parent panel
        self.panel = wx.Panel(self)
        # Button
        self.button  = wx.Button(self.panel, label="Start", pos=(50, 50))
        self.button2 = wx.Button(self.panel, label="Button", pos=(50 ,100))

        #### Timer Notice that wx.Timer is own by the frame itself
        self.timer = wx.Timer(self)

        #### Bind
        self.button.Bind(wx.EVT_BUTTON, self.OnStart)
        self.Bind(wx.EVT_TIMER, self.OnCheck, self.timer)

    def OnStart(self, event):
        ## OnStart, disable the button and change its label and start the timer.
        ## Notice with Button that the GUI remain responsive
        ## while the timer runs
        if self.will_continue:
            print(self.i)
            print(time.ctime())
            self.button.SetLabel("Running")
            self.button.Disable()
            self.timer.Start(self.mili)
        ## When finish waiting reset everything so the start button can run
        ## again and stop the timer
        else:
            self.timer.Stop()
            self.button.SetLabel("Start")
            self.button.Enable()
            self.will_continue = True
            self.i = 0

    def OnCheck(self, event):
        self.i += 1
        if self.i > self.total:
            self.will_continue = False
        else:
            pass
        self.OnStart(event)

# Run the program
if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()
</code>```

With wx.CallLater

```<code>import wx
import time

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="With wx.CallAfter", size=(500,500))

        #### Variables
        self.will_continue = True
        self.i = 0
        self.total = 5
        self.mili = 1000

        #### Widgets
        # Parent panel
        self.panel = wx.Panel(self)
        # Button
        self.button  = wx.Button(self.panel, label="Start", pos=(50, 50))
        self.button2 = wx.Button(self.panel, label="Button", pos=(50 ,100))

        #### Bind
        self.button.Bind(wx.EVT_BUTTON, self.OnStart)

    def OnStart(self, event):
        ## OnStart, disable the button and change its label and make the
        ## wx.CallLater call. Notice with Button that the GUI remain responsive
        ## while wx.CallLater waits
        if self.will_continue:
            print(self.i)
            print(time.ctime())
            self.button.SetLabel("Running")
            self.button.Disable()
            wx.CallLater(self.mili, self.OnCheck, event)
        ## When finish waiting reset everything so the start button can run
        ## again
        else:
            self.button.SetLabel("Start")
            self.button.Enable()
            self.will_continue = True
            self.i = 0

    def OnCheck(self, event):
        self.i += 1
        if self.i > self.total:
            self.will_continue = False
        else:
            pass
        self.OnStart(event)

# Run the program
if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()
</code>```

Body:
I want to loop and call a function every 1000 milliseconds with wx.CallLater. I implemented this (see below), but it does not factor in the delay - it seems to execute automatically. How can I get this to wait 1000 milliseconds between function calls?

This function is within a class. In my main module, I instantiate an object of this class and call the task_loop function. I intend to keep the loop going until will_break is set to True, and task_loop returns the work_session_agenda in the main module. Thank you for your help!

def task_loop(self, duration, window, task, work_session_agenda, start, completed):

    will_break = False
    will_continue = False

    duration -= datetime.timedelta(seconds=1)

More code in here - which, depending on conditionals, sets the values of will_break and will_continue

    if will_break:
        print('BREAKING')
        return work_session_agenda
    else:
        print('GOT HERE')
        timer = wx.CallLater(1000, self.task_loop, duration, window, task, work_session_agenda, start, completed)

Body:
Below you can find an example with wx.CallLater and with wx.Timer as suggested in the comments. Notice that in both cases the GUI remains responsive during the waiting time.

With wx.Timer

import wx
import time

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="With wx.Timer", size=(500,500))

        #### Variables
        self.will_continue = True
        self.i = 0
        self.total = 5
        self.mili = 1000

        #### Widgets
        # Parent panel
        self.panel = wx.Panel(self)
        # Button
        self.button  = wx.Button(self.panel, label="Start", pos=(50, 50))
        self.button2 = wx.Button(self.panel, label="Button", pos=(50 ,100))

        #### Timer Notice that wx.Timer is own by the frame itself
        self.timer = wx.Timer(self)

        #### Bind
        self.button.Bind(wx.EVT_BUTTON, self.OnStart)
        self.Bind(wx.EVT_TIMER, self.OnCheck, self.timer)

    def OnStart(self, event):
        ## OnStart, disable the button and change its label and start the timer.
        ## Notice with Button that the GUI remain responsive
        ## while the timer runs
        if self.will_continue:
            print(self.i)
            print(time.ctime())
            self.button.SetLabel("Running")
            self.button.Disable()
            self.timer.Start(self.mili)
        ## When finish waiting reset everything so the start button can run
        ## again and stop the timer
        else:
            self.timer.Stop()
            self.button.SetLabel("Start")
            self.button.Enable()
            self.will_continue = True
            self.i = 0

    def OnCheck(self, event):
        self.i += 1
        if self.i > self.total:
            self.will_continue = False
        else:
            pass
        self.OnStart(event)

# Run the program
if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()

With wx.CallLater

import wx
import time

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="With wx.CallAfter", size=(500,500))

        #### Variables
        self.will_continue = True
        self.i = 0
        self.total = 5
        self.mili = 1000

        #### Widgets
        # Parent panel
        self.panel = wx.Panel(self)
        # Button
        self.button  = wx.Button(self.panel, label="Start", pos=(50, 50))
        self.button2 = wx.Button(self.panel, label="Button", pos=(50 ,100))

        #### Bind
        self.button.Bind(wx.EVT_BUTTON, self.OnStart)

    def OnStart(self, event):
        ## OnStart, disable the button and change its label and make the
        ## wx.CallLater call. Notice with Button that the GUI remain responsive
        ## while wx.CallLater waits
        if self.will_continue:
            print(self.i)
            print(time.ctime())
            self.button.SetLabel("Running")
            self.button.Disable()
            wx.CallLater(self.mili, self.OnCheck, event)
        ## When finish waiting reset everything so the start button can run
        ## again
        else:
            self.button.SetLabel("Start")
            self.button.Enable()
            self.will_continue = True
            self.i = 0

    def OnCheck(self, event):
        self.i += 1
        if self.i > self.total:
            self.will_continue = False
        else:
            pass
        self.OnStart(event)

# Run the program
if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()


问:
How to determine if a string is a number with C++?
I've had quite a bit of trouble trying to write a function that checks if a string is a number.  For a game I am writing I just need to check if a line from the file I am reading is a number or not (I will know if it is a parameter this way).  I wrote the below function which I believe was working smoothly (or I accidentally edited to stop it or I'm schizophrenic or Windows is schizophrenic):</p>

```<code>bool isParam (string line)
{
    if (isdigit(atoi(line.c_str())))
        return true;

    return false;
}
</code>```

答:
C/C++ style for unsigned integers, using range based for C++11:

```<code>int isdigits(const std::string & s)
{
    for (char c : s) if (!isdigit(c)) return (0);
    return (1);
}
</code>```

Body:
I've had quite a bit of trouble trying to write a function that checks if a string is a number.  For a game I am writing I just need to check if a line from the file I am reading is a number or not (I will know if it is a parameter this way).  I wrote the below function which I believe was working smoothly (or I accidentally edited to stop it or I'm schizophrenic or Windows is schizophrenic):

bool isParam (string line)
{
    if (isdigit(atoi(line.c_str())))
        return true;

    return false;
}

Body:
C/C++ style for unsigned integers, using range based for C++11:

int isdigits(const std::string & s)
{
    for (char c : s) if (!isdigit(c)) return (0);
    return (1);
}


问:
How to fill a div but maintain aspect ratio for child divs
I have the following page showing the HTML as well as the CSS.  I want the five buttons on the left (div id=button1..5) to always be square at any aspect ratio and resolution of the screen. Also, I want the five buttons to always fill the middle div (id=menu). In fact, I AM ABLE TO DO BOTH, but NOT TOGETHER! The latter is easy with Flex and the former as you can see I have done in the code below.  I have looked at several examples on SO, notably this one, but they don't do what I am talking about.

Any suggestions?
Note: Preferably no Javascript...

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
html, body {
    margin:0;
    padding:0;
}
#container {
    display:flex;
    flex-direction: column;
    background-color: #444;
    height:100vh;
    width:100%;
    margin:0;
    padding:0;
}
#top{
    background-color: #777;
    height:5%;
    width:100%;
    margin:0;
    padding:0;
}
#main{
    background-color: #DDD;
    height:100%;
    width:100%;
    margin:0;
    padding:0;
    align-items: stretch;
}
#menu{
    display:flex;
    flex-direction: column;
    background-color: #FFF;
    height:100%;
    width:10%;
    margin:0;
    padding:0;
}
.buttons{
    display:inline-block;
    position:relative;
    height:0;
    margin:0;
    padding-bottom:100%;
}
#button1{background-color:blue; margin:2px 0 2px 0;}
#button2{background-color:green; margin:2px 0 2px 0;}
#button3{background-color:red; margin:2px 0 2px 0;}
#button4{background-color:black; margin:2px 0 2px 0;}
#button5{background-color:orange; margin:2px 0 2px 0;}
.img-container {
  justify-content: center;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  padding:16px;
}
.img-container .img-to-fit {
  flex: 1;
  height: 100%;
}

.fill {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden
}
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}

#bottom {
    height:2%;
    display:flex;
}
#bottom1{background-color:blue;}
#bottom2{background-color:green;}
#bottom3{background-color:red;}
#bottom4{background-color:white;}
#bottom5{background-color:orange;}
.bottoms{
    height:100%;
    width:20%;
    margin:0;
    padding:0;
}
</style>
</head>

<body>
    <div id="container">
        <div id="top"/>
        <div id="main">
             <div id="menu">
                <div id="button1" class="buttons">
                     <div class="img-container">
                         <img class="img-to-fit" src="parcel.png" />
                     </div>
                </div>
                <div id="button2" class="buttons"/>
                <div id="button3" class="buttons"/>
                <div id="button4" class="buttons"/>
                <div id="button5" class="buttons"/>
            </div>
        </div>
        <div id="bottom">
                <div id="bottom1" class="bottoms"/>
                <div id="bottom2" class="bottoms"/>
                <div id="bottom3" class="bottoms"/>
                <div id="bottom4" class="bottoms"/>
                <div id="bottom5" class="bottoms"/>
        </div>
    </div>
</body>
</html>
</code>```

答: Try using https://css-tricks.com/aspect-ratio-boxes/  with padding as a container. Make the content with position: absolute to fill the container. It should always keep the proportions this way.

Body:
I have the following page showing the HTML as well as the CSS.  I want the five buttons on the left (div id=button1..5) to always be square at any aspect ratio and resolution of the screen. Also, I want the five buttons to always fill the middle div (id=menu). In fact, I AM ABLE TO DO BOTH, but NOT TOGETHER! The latter is easy with Flex and the former as you can see I have done in the code below.  I have looked at several examples on SO, notably this one, but they don't do what I am talking about.

Any suggestions?
Note: Preferably no Javascript...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>


问:
How to refer slot element from its slotted element in lit-element?
I have a component named 'stack-item' which have a slot , its html will look like this

```<code><div>
<div>1<div>
<div class='slot-style'><slot></slot></div>
</div>
</code>```

I have used this component like this

```<code><stack-item>
   <another-component></another-component>
</stack-item>
</code>```

From 'another-component' how do i get the element reference for class ='slot-style' for calculating the slot width and other properties ?

I wrote a workaround

```<code>let slotElement =this.shadowRoot.host.parentElement.shadowRoot.querySelector('slot').parentElement;
</code>```

but is there a clean way of achieving this?

答:
this.shadowRoot.host is equivalent to this.

So you could try:

```<code>this.parentElement.shadowRoot.querySelector( 'div.slot-style' )
</code>```

Body:
I have a component named 'stack-item' which have a slot , its html will look like this

1

<slot></slot>

I have used this component like this

<stack-item>
   <another-component></another-component>
</stack-item>

From 'another-component' how do i get the element reference for class ='slot-style' for calculating the slot width and other properties ?

I wrote a workaround

let slotElement =this.shadowRoot.host.parentElement.shadowRoot.querySelector('slot').parentElement;

but is there a clean way of achieving this?

Body:
this.shadowRoot.host is equivalent to this.

So you could try:

this.parentElement.shadowRoot.querySelector( 'div.slot-style' )


问:
Use an external Link as the WordPress profile picture
I want to write a Single Sign On (SSO) plugin for WordPress. I want to use an external image link as user's profile picture after user login.
This image has a link which is located in http://www.example.com/image.png.

How can I do this in WordPress?

答:
Please add this code to your activated theme's functions.php file.

```<code>add_filter( 'author_link', 'modify_author_link', 10, 1 );
function modify_author_link( $link ) {
    $link = 'http://google.com/';
    return $link;
}
</code>```

You can use your any link, just change https://google.com to your link.
Thanks.

Body:
Please add this code to your activated theme's functions.php file.

add_filter( 'author_link', 'modify_author_link', 10, 1 );
function modify_author_link( $link ) {
    $link = 'http://google.com/';
    return $link;
}

You can use your any link, just change https://google.com to your link.
Thanks.


问:
Add event listener to all objects except for a few selected?
I'm trying to add event listener to all objects except for a few selected (the selected also have arbitrary child elements in arbitrary levels)?

I have asked this question before, but I didn't really got an answer to it. I have came close to solve it. Could you please help me with debugging it?

I'm adding an event listener to the body element called bodylistener and an event listener to the few selected elements called selectedElementsMarkTrue. The few selected elements that I don't want to execute some code, the listener selectedElementsMarkTrue performs prior to bodylistener with setTimeout function. selectedElementsMarkTrueset the variable selectedElements to true and bodylistenerchecks if selectedElements is true before execute some code. There is still something wrong with my code:

```<code>var selectedElements = false;
var bodylistener = function(){
    window.setTimeout(function(){//Setting timeout so that the other handler, selectedElementsMarkTrue, always performs first
        (function(){
            if(selectedElements == false){
                //Do some stuff
            }else{
                selectedElements = false;
            }
        });
    }, 10);//Could be 0, but te be sure I set 10
};
var selectedElementsMarkTrue = function(){
    selectedElements = true;
};
$('#dontAddEventListener1, #dontAddEventListener2').each(function(){
    this.addEventListener('click', selectedElementsMarkTrue, false);
});
document.body.addEventListener('click', bodylistener, false);
</code>```

I can't get the setTimeout function to execute the underlying code?

答:
Sounds like you want behavior something like this:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            window.addEventListener("DOMContentLoaded", function() {
                document.body.addEventListener("click", function(e) {
                    var el = e.target;
                    do {
                        if (el.hasAttribute && el.hasAttribute("data-nofire")) {
                            return;
                        }
                    } while (el = el.parentNode);
                    alert('do stuff');
                }, true);
            }, false);
        </script>
    </head>
    <body>
        <p><span>click me</span></p>
        <p data-nofire><span>click me</span></p>
        <p data-nofire>click me</p>
        <p>click me</p>
    </body>
</html>
</code>```

Or, you could do it something like Naren suggested:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            window.addEventListener("DOMContentLoaded", function() {
                var nofire = document.getElementsByClassName("nofire");
                for (var i = 0; i < nofire.length; ++i) {
                    nofire[i].addEventListener("click", function(e) {
                        e.stopPropagation();
                    }, true);
                }
                document.body.addEventListener("click", function(e) {
                    alert('do stuff');
                }, false);
            }, false);
        </script>
    </head>
    <body>
        <p><span>click me</span></p>
        <p class="nofire"><span>click me</span></p>
        <p class="nofire">click me</p>
        <p>click me</p>
    </body>
</html>
</code>```

Body:
I'm trying to add event listener to all objects except for a few selected (the selected also have arbitrary child elements in arbitrary levels)?

I have asked this question before, but I didn't really got an answer to it. I have came close to solve it. Could you please help me with debugging it?

I'm adding an event listener to the body element called bodylistener and an event listener to the few selected elements called selectedElementsMarkTrue. The few selected elements that I don't want to execute some code, the listener selectedElementsMarkTrue performs prior to bodylistener with setTimeout function. selectedElementsMarkTrueset the variable selectedElements to true and bodylistenerchecks if selectedElements is true before execute some code. There is still something wrong with my code:

var selectedElements = false;
var bodylistener = function(){
    window.setTimeout(function(){//Setting timeout so that the other handler, selectedElementsMarkTrue, always performs first
        (function(){
            if(selectedElements == false){
                //Do some stuff
            }else{
                selectedElements = false;
            }
        });
    }, 10);//Could be 0, but te be sure I set 10
};
var selectedElementsMarkTrue = function(){
    selectedElements = true;
};
$('#dontAddEventListener1, #dontAddEventListener2').each(function(){
    this.addEventListener('click', selectedElementsMarkTrue, false);
});
document.body.addEventListener('click', bodylistener, false);

I can't get the setTimeout function to execute the underlying code?

Body:
Sounds like you want behavior something like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            window.addEventListener("DOMContentLoaded", function() {
                document.body.addEventListener("click", function(e) {
                    var el = e.target;
                    do {
                        if (el.hasAttribute && el.hasAttribute("data-nofire")) {
                            return;
                        }
                    } while (el = el.parentNode);
                    alert('do stuff');
                }, true);
            }, false);
        </script>
    </head>
    <body>
        <p><span>click me</span></p>
        <p data-nofire><span>click me</span></p>
        <p data-nofire>click me</p>
        <p>click me</p>
    </body>
</html>

Or, you could do it something like Naren suggested:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            window.addEventListener("DOMContentLoaded", function() {
                var nofire = document.getElementsByClassName("nofire");
                for (var i = 0; i < nofire.length; ++i) {
                    nofire[i].addEventListener("click", function(e) {
                        e.stopPropagation();
                    }, true);
                }
                document.body.addEventListener("click", function(e) {
                    alert('do stuff');
                }, false);
            }, false);
        </script>
    </head>
    <body>
        <p><span>click me</span></p>
        <p class="nofire"><span>click me</span></p>
        <p class="nofire">click me</p>
        <p>click me</p>
    </body>
</html>


问:
Azure VM diagnostics for SQL server not showing in log analytics
I have enabled sql server as part of performance counters. but when I a check log analytics or under metrics or Monitor. I see nothing. does it take time for data to come through? or some more setting is required.

答:
AFAIK yes it does take some time of ~15 minutes. Before you verify SQL Perf related logs from Log Analytics, I would suggest you to double check whether SQLServer related performance counters are already added under YourLogAnalyticsWorkspaceName -> AdvancedSettings tile -> Data -> WindowsPerformanceCounters or not.

You may already be aware of this but as you are referring to VM level monitoring stuff so I would recommend you to read through this and this tutorials to understand about a new feature 'Virtual Machines (preview)' which is basically seen as a new tile under Azure Monitor.

Hope this helps!! Cheers!!


问:
Handling "raw data" in Node.js and passing on the data in a Node Express endpoint
I'm making an API call to get a file using axios:

```<code>   async function getData() {
    const config = {}; // { responseType: 'stream'};
    const { data } = await axios.get(URL, config);

    console.log(data);
    return data;
   }
</code>```

When I attempt to print the result of my HTTP request, I get a bunch of nonsense (looks like some type of raw data) - Snapshot here:

```<code>...
�nG��p���1�l�ՓA�zw:/F�  �@ǇW>
��⟿_��̠����������=�|�d�s_���A�GԢ������
...
</code>```

I want to pass on this data (an image or video file) to whoever is reaching my Node Express server's endpoint - How am I supposed to do that? I've read something about using a Stream and then pipe it into the response.

```<code>   router.get("/file", async(res,res) => {
       const file = await getFile();

       //const stream = fs.createReadStream(file)
       //res.pipe(stream)
   })
</code>```

My problem is however I don't know how to deal with the data I get back from the API in the first place. I have tried changing the responseType of axios to stream(default:json) which gives me back an object but not sure how to handle it either.

Edit - Attempt 1:

```<code> async function getData() {
    const config = { responseType: 'stream'};
    const { data } = await axios.get(URL, config);

    console.log(data);
    return data;
   }

   router.get("/file", async(res,res) => {
       const file = await getFile();

       file.pipe(res);
   })

</code>```

答:
With responseType being stream, axios resolves to a response object whose data property is a stream, which you can pipe to the response:

```<code> const file = await getFile();
 file.data.pipe(/*to*/ res);
</code>```

Body:
I'm making an API call to get a file using axios:

   async function getData() {
    const config = {}; // { responseType: 'stream'};
    const { data } = await axios.get(URL, config);

    console.log(data);
    return data;
   }

When I attempt to print the result of my HTTP request, I get a bunch of nonsense (looks like some type of raw data) - Snapshot here:

...
�nG��p���1�l�ՓA�zw:/F�  �@ǇW>
��⟿_��̠����������=�|�d�s_���A�GԢ������
...

I want to pass on this data (an image or video file) to whoever is reaching my Node Express server's endpoint - How am I supposed to do that? I've read something about using a Stream and then pipe it into the response.

   router.get("/file", async(res,res) => {
       const file = await getFile();

       //const stream = fs.createReadStream(file)
       //res.pipe(stream)
   })

My problem is however I don't know how to deal with the data I get back from the API in the first place. I have tried changing the responseType of axios to stream(default:json) which gives me back an object but not sure how to handle it either.

Edit - Attempt 1:

 async function getData() {
    const config = { responseType: 'stream'};
    const { data } = await axios.get(URL, config);

    console.log(data);
    return data;
   }

   router.get("/file", async(res,res) => {
       const file = await getFile();

       file.pipe(res);
   })

Body:
With responseType being stream, axios resolves to a response object whose data property is a stream, which you can pipe to the response:

 const file = await getFile();
 file.data.pipe(/*to*/ res);


问:
phpmailer No Relay Access Allowed Error
My website is hosted on godaddy, and I just figured out that my website is no more sending emails through phpmailer since last few months. I uploaded the latest version of phpmailer but still no success. The online web mail of my website runs fine. If I use php's "mail" function, it does send emails to gmail, but not to yahoo accounts.

I tried all the three ports 25, 465, and 587, but no luck

I am getting the following error from phpmailer:

```<code>SERVER -> CLIENT: 554 p3plsmtpa07-10.prod.phx3.secureserver.net ESMTP No Relay Access Allowed From 50.63.196.51
CLIENT -> SERVER: EHLO lostandfound.pakproject.com
SERVER -> CLIENT:
SMTP ERROR: EHLO command failed:
SMTP NOTICE: EOF caught while checking if connected
SMTP Error: Could not authenticate.
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

Following is my code that I am trying to test. (User name, passwords, emails are changed...)

```<code><?php

date_default_timezone_set('Etc/UTC');
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtpout.... my_server";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "here_i_used_my_website_email";

$mail->Password = "here_password";
$mail->setFrom('website_email', 'From name');
$mail->addReplyTo('website_email', 'From name');
$mail->addAddress('another_email', 'name_used_here');

$mail->Subject = 'About the task';
$mail->Body = 'This is email body';
$mail->AltBody = 'This is a plain-text message body';

if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
?>
</code>```

答:
```<code>    $mail->SMTPSecure = false;
    $mail->SMTPAuth = false;
</code>```

It worked for me.
Keep in mind
https://co.godaddy.com/help/mail-server-addresses-and-ports-for-business-email-24071**

Title: phpmailer No Relay Access Allowed Error

Body:
My website is hosted on godaddy, and I just figured out that my website is no more sending emails through phpmailer since last few months. I uploaded the latest version of phpmailer but still no success. The online web mail of my website runs fine. If I use php's "mail" function, it does send emails to gmail, but not to yahoo accounts.

I tried all the three ports 25, 465, and 587, but no luck

I am getting the following error from phpmailer:

SERVER -> CLIENT: 554 p3plsmtpa07-10.prod.phx3.secureserver.net ESMTP No Relay Access Allowed From 50.63.196.51
CLIENT -> SERVER: EHLO lostandfound.pakproject.com
SERVER -> CLIENT:
SMTP ERROR: EHLO command failed:
SMTP NOTICE: EOF caught while checking if connected
SMTP Error: Could not authenticate.
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Following is my code that I am trying to test. (User name, passwords, emails are changed...)

<?php

date_default_timezone_set('Etc/UTC');
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtpout.... my_server";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "here_i_used_my_website_email";

$mail->Password = "here_password";
$mail->setFrom('website_email', 'From name');
$mail->addReplyTo('website_email', 'From name');
$mail->addAddress('another_email', 'name_used_here');

$mail->Subject = 'About the task';
$mail->Body = 'This is email body';
$mail->AltBody = 'This is a plain-text message body';

if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
?>

Body:
    $mail->SMTPSecure = false;
    $mail->SMTPAuth = false;

It worked for me.
Keep in mind
https://co.godaddy.com/help/mail-server-addresses-and-ports-for-business-email-24071**


问:
What are the limitations for zip file extraction in Azure Search?
My indexer shows an error for two zip files (size of 800MB) saying that the zip file has "the size of ... bytes, which exceeds the maximum size for document extraction for your curent service tier." Azure Search is already set on a Standard tier. Is the solution to go to a higher tier? Cause from the documentation I gather that the limit is the same across all Standard tiers? If there is a limit to the size of zip files to be extracted, then what is it? And would the solution for bigger files then be to unzip it before Azure Search?</p>

答:
Maximum running times exist to provide balance and stability to the service as a whole, but larger data sets might need more indexing time than the maximum allows. If an indexing job cannot complete within the maximum time allowed, try running it on a schedule. Here is indexer limit you could refer to.

Note: A service is provisioned at a specific tier. Jumping tiers to gain capacity involves provisioning a new service (there is no in-place upgrade). For more information, see Choose a SKU or tier. To learn more about adjusting capacity within a service you've already provisioned, see Scale resource levels for query and indexing workloads.


答:
We could have two geom_line with their respective colors and then use facet_wrap

```<code>library(ggplot2)

ggplot(data) +
  aes(x = Week, y = value2, group = kpi, colour = color2) +
  geom_line() +
  geom_line(aes( x = Week, y = value, group = kpi, color = color1)) +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))
</code>```

Title: Adding a legend to a ggplot2

Body:
We could have two geom_line with their respective colors and then use facet_wrap

library(ggplot2)

ggplot(data) +
  aes(x = Week, y = value2, group = kpi, colour = color2) +
  geom_line() +
  geom_line(aes( x = Week, y = value, group = kpi, color = color1)) +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))