Title: How do I calculate the overlap days in a dataframe in PySpark?

Body:
I need to calculate the overlap days, row wise, in a data frame.
Data looks like this:

+-------+-------------------+-------------------+------------------+
|id|             begin|                end|              days|
+-------+-------------------+-------------------+------------------+
|1|2019-01-01 00:00:00|2019-01-08 02:10:00| 7.090277777777778|
|1|2019-02-04 05:28:00|2019-03-05 19:29:00|29.584027777777777|
|1|2019-06-05 22:18:00|2020-01-01 00:00:00|209.07083333333333|
|1|2019-05-17 16:25:00|2019-06-05 22:18:00| 19.24513888888889|
|1|2019-05-03 05:05:00|2019-05-17 16:25:00|14.472222222222221|
|1|2019-01-08 02:10:00|2019-02-04 05:28:00|           27.1375|
|1|2019-01-01 00:00:00|2020-01-01 00:00:00|             365.0|
|1|2019-04-22 18:45:00|2019-05-03 05:05:00|10.430555555555555|
|1|2019-03-05 19:29:00|2019-04-22 18:45:00| 47.96944444444444|
+-------+-------------------+-------------------+------------------+

Here, the first entry spans across the year 2019 (365 days).
All other entries are overlapping with the first entry.
I want a function to calculate total days, which is 365 days in the dataset after removing the overlapping days.

I actually solved this problem in R but I'm unable to run for loops in PySpark.

I'm looking for an output like this.

+-------+-------------------+-------------------+------------------+------------------+
|     id|              begin|                end|              days|           overlap|
+-------+-------------------+-------------------+------------------+------------------+
|1      |2019-01-01 00:00:00|2020-01-01 00:00:00|             365.0|            0|
|1      |2019-01-01 00:00:00|2019-01-08 02:10:00| 7.090277777777778| 7.090277777777778|
|1      |2019-01-08 02:10:00|2019-02-04 05:28:00|           27.1375|           27.1375|
|1      |2019-02-04 05:28:00|2019-03-05 19:29:00|29.584027777777777|29.584027777777777|
|1      |2019-03-05 19:29:00|2019-04-22 18:45:00| 47.96944444444444| 47.96944444444444|
|1      |2019-04-22 18:45:00|2019-05-03 05:05:00|10.430555555555555|10.430555555555555|
|1      |2019-05-03 05:05:00|2019-05-17 16:25:00|14.472222222222221|14.472222222222221|
|1      |2019-05-17 16:25:00|2019-06-05 22:18:00| 19.24513888888889| 19.24513888888889|
|1      |2019-06-05 22:18:00|2020-01-01 00:00:00|209.07083333333333|209.07083333333333|
+-------+-------------------+-------------------+------------------+------------------+

The dates are never in order and there are scenarios where there is no overlap.

Scenario 2: No overlap

+-------+-------------------+-------------------+-----+-----+
|  id   |              begin|                end| days| over|
+-------+-------------------+-------------------+-----+-----+
|2      |2019-01-01 00:00:00|2019-12-25 00:00:00|358.0|    0|
|2      |2019-12-25 00:00:00|2020-01-01 00:00:00|  7.0|    0|
+-------+-------------------+-------------------+-----+-----+

Scenario 3: Partial overlap

+-------+-------------------+-------------------+-----+-----+
|     id|              begin|                end| days| over|
+-------+-------------------+-------------------+-----+-----+
|3      |2019-01-01 00:00:00|2019-12-25 00:00:00|358.0|    0|
|3      |2019-12-20 00:00:00|2020-01-01 00:00:00| 12.0|    5|
+-------+-------------------+-------------------+-----+-----+

Scenario 4: More complicated
Here the first entry spans across first 358 days of 2019. Second entry is completely overlapping with the first and therefore all of the days are under over. The third entry doesn't overlap with second entry but overlaps 5 days with the first and therefore 5 days under column "over".

+-------+-------------------+-------------------+-----+-----+
|     id|              begin|                end| days| over|
+-------+-------------------+-------------------+-----+-----+
|4      |2019-01-01 00:00:00|2019-12-25 00:00:00|358.0|    0|
|4      |2019-01-01 00:00:00|2019-11-25 00:00:00|328.0|328.0|
|4      |2019-12-20 00:00:00|2020-01-01 00:00:00| 12.0|    5|
+-------+-------------------+-------------------+-----+-----+

Basically, I want to know for how long a particular id was in force. I can't just take the max and min date and subtract them because there could be breaks between periods.

In R, I created another column called "overlap" and used the Overlap function in for loop to check all values against others.

R function that produces the desired output:

abc<-data.frame()
for (i in id) {
  xyz<- dataset %>% filter(id==i) %>% arrange(begin)

  for(j in 1:(nrow(xyz)-1)){
    k=j
    while(k<nrow(xyz)){
      xyz$overlap[j]<- xyz$overlap[j] + Overlap(c(xyz$begin[j], xyz$end[j]), c(xyz$begin[k+1], xyz$end[k+1]))
      k=k+1
    }

  }
  abc<- bind_rows(abc,xyz)
}

I'm still learning pyspark and need help with this.

Response to the code snippet by @murtihash

Hi,
It looks closer to the answer but still not the result I'm looking for.
Output from your code

+-------+-------------------+-------------------+-----------------+-------+
|     id|              begin|                end|             days|overlap|
+-------+-------------------+-------------------+-----------------+-------+
|7777777|2019-01-05 01:00:00|2019-04-04 00:00:00|88.95833333333333|      0|
|7777777|2019-04-04 00:00:00|2019-07-11 00:00:00|             98.0|      0|
|7777777|2019-07-11 00:00:00|2019-09-17 00:00:00|             68.0|      1|
|7777777|2019-09-17 00:00:00|2019-09-19 22:01:00|2.917361111111111|      0|
|7777777|2019-09-19 22:01:00|2020-01-01 00:00:00|103.0826388888889|     -1|
|7777777|2019-09-19 22:01:00|2020-01-01 00:00:00|103.0826388888889|     -1|
+-------+-------------------+-------------------+-----------------+-------+

Desired output should be:

+-------+-------------------+-------------------+-----------------+-------+
|     id|              begin|                end|             days|overlap|
+-------+-------------------+-------------------+-----------------+-------+
|7777777|2019-01-05 01:00:00|2019-04-04 00:00:00|88.95833333333333|      0|
|7777777|2019-04-04 00:00:00|2019-07-11 00:00:00|             98.0|      0|
|7777777|2019-07-11 00:00:00|2019-09-17 00:00:00|             68.0|      0|
|7777777|2019-09-17 00:00:00|2019-09-19 22:01:00|2.917361111111111|      0|
|7777777|2019-09-19 22:01:00|2020-01-01 00:00:00|103.0826388888889|103.082|
|7777777|2019-09-19 22:01:00|2020-01-01 00:00:00|103.0826388888889|      0|
+-------+-------------------+-------------------+-----------------+-------+

Explanation: First four rows have no overlaps. The fifth and sixth row are exactly the same period(and not overlapping with the other rows), so for one of 5th or 6th row, the overlap should be 103.08 days

Update:
Not able to work on this particular scenario.
Output from code snippet @murtihash

+-------+-------------------+-------------------+------------------+-------+
|  imono|              begin|                end|              days|overlap|
+-------+-------------------+-------------------+------------------+-------+
|9347774|2019-01-01 00:00:00|2019-01-08 02:10:00| 7.090277777777778|    0.0|
|9347774|2019-01-08 02:10:00|2019-02-04 05:28:00|           27.1375|    0.0|
|9347774|2019-02-04 05:28:00|2019-03-05 19:29:00|29.584027777777777|    0.0|
|9347774|2019-03-05 19:29:00|2019-04-22 18:45:00| 47.96944444444444|    0.0|
|9347774|2019-04-22 18:45:00|2019-05-03 05:05:00|10.430555555555555|    0.0|
|9347774|2019-05-03 05:05:00|2019-05-17 16:25:00|14.472222222222221|    0.0|
|9347774|2019-05-17 16:25:00|2019-06-05 22:18:00| 19.24513888888889|    0.0|
|9347774|2019-01-01 00:00:00|2020-01-01 00:00:00|             365.0|    7.0|
|9347774|2019-06-05 22:18:00|2020-01-01 00:00:00|209.07083333333333|    0.0|
+-------+-------------------+-------------------+------------------+-------+

Desired output:
This

 +-------+-------------------+-------------------+------------------+-------+
    |  imono|              begin|                end|              days|overlap|
    +-------+-------------------+-------------------+------------------+-------+
    |9347774|2019-01-01 00:00:00|2019-01-08 02:10:00| 7.090277777777778|    0.0|
    |9347774|2019-01-08 02:10:00|2019-02-04 05:28:00|           27.1375|    0.0|
    |9347774|2019-02-04 05:28:00|2019-03-05 19:29:00|29.584027777777777|    0.0|
    |9347774|2019-03-05 19:29:00|2019-04-22 18:45:00| 47.96944444444444|    0.0|
    |9347774|2019-04-22 18:45:00|2019-05-03 05:05:00|10.430555555555555|    0.0|
    |9347774|2019-05-03 05:05:00|2019-05-17 16:25:00|14.472222222222221|    0.0|
    |9347774|2019-05-17 16:25:00|2019-06-05 22:18:00| 19.24513888888889|    0.0|
    |9347774|2019-01-01 00:00:00|2020-01-01 00:00:00|             365.0|    365|
    |9347774|2019-06-05 22:18:00|2020-01-01 00:00:00|209.07083333333333|    0.0|
    +-------+-------------------+-------------------+------------------+-------+

Or

 +-------+-------------------+-------------------+------------------+-------+
|  imono|              begin|                end|              days|overlap|

+-------+-------------------+-------------------+------------------+-------+
|9347774|2019-01-01 00:00:00|2019-01-08 02:10:00| 7.090277777777778|    7.1|
|9347774|2019-01-08 02:10:00|2019-02-04 05:28:00|           27.1375|   27.1|
|9347774|2019-02-04 05:28:00|2019-03-05 19:29:00|29.584027777777777|   29.5|
|9347774|2019-03-05 19:29:00|2019-04-22 18:45:00| 47.96944444444444|   48.0|
|9347774|2019-04-22 18:45:00|2019-05-03 05:05:00|10.430555555555555|   10.4|
|9347774|2019-05-03 05:05:00|2019-05-17 16:25:00|14.472222222222221|   14.5|
|9347774|2019-05-17 16:25:00|2019-06-05 22:18:00| 19.24513888888889|   19.2|
|9347774|2019-01-01 00:00:00|2020-01-01 00:00:00|             365.0|    0.0|
|9347774|2019-06-05 22:18:00|2020-01-01 00:00:00|209.07083333333333|  209.1|
+-------+-------------------+-------------------+------------------+-------+

Explanation: second last entry spans the full year and all other entries are overlapping with that. So either the output is that the second last entry overlap= 365 or all the other entries have their days as overlap and second last entry have 0 days as overlap.

Update2:
Not able to work on this particular scenario.
Output from code snippet @murtihash (Update2)

+-------+-------------------+-------------------+------------------+-------+
|  imono|              begin|                end|              days|overlap|
+-------+-------------------+-------------------+------------------+-------+
|9395123|2019-01-19 05:01:00|2019-02-06 00:00:00|17.790972222222223|   17.0|
|9395123|2019-02-06 00:00:00|2019-06-17 00:00:00|             131.0|    0.0|
|9395123|2019-01-19 05:01:00|2020-01-01 00:00:00| 346.7909722222222|    0.0|
|9395123|2019-06-17 00:00:00|2020-01-01 00:00:00|             198.0|    0.0|
+-------+-------------------+-------------------+------------------+-------+

Desired output:

+-------+-------------------+-------------------+------------------+-------+
|  id   |              begin|                end|              days|overlap|
+-------+-------------------+-------------------+------------------+-------+
|8888888|2019-01-19 05:01:00|2019-02-06 00:00:00|17.790972222222223|   17.8|
|8888888|2019-02-06 00:00:00|2019-06-17 00:00:00|             131.0|    0.0|
|8888888|2019-01-19 05:01:00|2020-01-01 00:00:00| 346.7909722222222|    329|
|8888888|2019-06-17 00:00:00|2020-01-01 00:00:00|             198.0|    0.0|
+-------+-------------------+-------------------+------------------+-------+

I really don't understand what your code snippet does and therefore I'm unable to tweak it for my purpose. Thanks for your help!

Body:
Check below solution, see if that works for you.

import pyspark.sql.functions as F

df = sc.parallelize([["1","2019-01-01 00:00:00","2019-01-08 02:10:00","7.090277777777778"],
["1","2019-02-04 05:28:00","2019-03-05 19:29:00","29.584027777777777"],
["1","2019-06-05 22:18:00","2020-01-01 00:00:00","209.07083333333333"],
["1","2019-05-17 16:25:00","2019-06-05 22:18:00","19.24513888888889"],
["1","2019-05-03 05:05:00","2019-05-17 16:25:00","14.472222222222221"],
["1","2019-01-08 02:10:00","2019-02-04 05:28:00","27.1375"],
["1","2019-01-01 00:00:00","2020-01-01 00:00:00","365.0"],
["1","2019-04-22 18:45:00","2019-05-03 05:05:00","10.430555555555555"],
["1","2019-03-05 19:29:00","2019-04-22 18:45:00","47.96944444444444"]]).toDF(("id","begin","end","days"))

df.withColumn("overlap", ((F.unix_timestamp(col("end")).cast("long") - F.unix_timestamp(col("begin")).cast("long"))/(24*3600))).show()

+---+-------------------+-------------------+------------------+------------------+
| id|              begin|                end|              days|           overlap|
+---+-------------------+-------------------+------------------+------------------+
|  1|2019-01-01 00:00:00|2019-01-08 02:10:00| 7.090277777777778| 7.090277777777778|
|  1|2019-02-04 05:28:00|2019-03-05 19:29:00|29.584027777777777|29.584027777777777|
|  1|2019-06-05 22:18:00|2020-01-01 00:00:00|209.07083333333333|          209.1125|
|  1|2019-05-17 16:25:00|2019-06-05 22:18:00| 19.24513888888889| 19.24513888888889|
|  1|2019-05-03 05:05:00|2019-05-17 16:25:00|14.472222222222221|14.472222222222221|
|  1|2019-01-08 02:10:00|2019-02-04 05:28:00|           27.1375|           27.1375|
|  1|2019-01-01 00:00:00|2020-01-01 00:00:00|             365.0|             365.0|
|  1|2019-04-22 18:45:00|2019-05-03 05:05:00|10.430555555555555|10.430555555555555|
|  1|2019-03-05 19:29:00|2019-04-22 18:45:00| 47.96944444444444| 47.92777777777778|
+---+-------------------+-------------------+------------------+------------------+


来源: stackexchange

问:
Filling between two lines on python
I have the formula below:

```<code>ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.gca().fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
plt.show()
</code>```

I would like to fill between the two lines on the line graph below, but somehow my code is not working. Could anyone help understand why?

I thought that the fill_between command would work but for some reason it is not...

When I try:

```<code>ax.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
</code>```

I get the error message:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

My graph currently looks like this:

The dataframe datamax looks like this:

```<code> Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]
</code>```

And the dataframe datamin like this:

```<code> Date           ID Element  Data_Value
0     2005-01-01  USC00200032    TMIN         -56
1     2005-01-02  USC00200032    TMIN         -56
2     2005-01-03  USC00200032    TMIN           0
3     2005-01-04  USC00200032    TMIN         -39
4     2005-01-05  USC00200032    TMIN         -94
5     2005-01-06  USC00200032    TMIN        -106
6     2005-01-07  USC00200032    TMIN        -111
7     2005-01-08  USC00200032    TMIN        -100
8     2005-01-09  USC00200032    TMIN         -67
9     2005-01-10  USC00200032    TMIN         -56
10    2005-01-11  USC00200032    TMIN         -22
11    2005-01-12  USC00200032    TMIN         -17
12    2005-01-13  USC00200032    TMIN         -83
13    2005-01-14  USC00200032    TMIN        -128
14    2005-01-15  USC00200032    TMIN        -144
15    2005-01-16  USC00200032    TMIN        -150
16    2005-01-17  USC00200032    TMIN        -189
17    2005-01-18  USC00200032    TMIN        -217
18    2005-01-19  USC00200228    TMIN        -300
19    2005-01-20  USC00200032    TMIN        -156
20    2005-01-21  USC00200032    TMIN        -178
21    2005-01-22  USC00200032    TMIN        -178
22    2005-01-23  USC00200032    TMIN        -250
23    2005-01-24  USC00200032    TMIN        -267
24    2005-01-25  USC00200032    TMIN        -228
25    2005-01-26  USC00200032    TMIN        -206
26    2005-01-27  USC00200032    TMIN        -239
27    2005-01-28  USC00200032    TMIN        -250
28    2005-01-29  USC00200032    TMIN        -222
29    2005-01-30  USC00200228    TMIN        -217
...          ...          ...     ...         ...
3603  2014-11-13  USC00200032    TMIN         -71
3604  2014-11-14  USC00200032    TMIN         -78
3605  2014-11-15  USC00200032    TMIN         -94
3606  2014-11-16  USC00200032    TMIN         -72
3607  2014-11-17  USC00200032    TMIN        -106
3608  2014-11-18  USC00200032    TMIN        -144
3609  2014-11-19  USC00200032    TMIN        -128
3610  2014-11-20  USC00200032    TMIN        -122
3611  2014-11-21  USC00200032    TMIN        -182
3612  2014-11-22  USC00200032    TMIN        -172
3613  2014-11-23  USC00200032    TMIN        -100
3614  2014-11-24  USC00200032    TMIN          -5
3615  2014-11-25  USC00200032    TMIN         -33
3616  2014-11-26  USC00200032    TMIN         -67
3617  2014-11-27  USC00200032    TMIN         -82
3618  2014-11-28  USC00200032    TMIN        -133
3619  2014-11-29  USC00200032    TMIN        -106
3620  2014-11-30  USC00200032    TMIN         -56
3621  2014-12-01  USC00200032    TMIN         -88
3622  2014-12-02  USC00200032    TMIN         -99
3623  2014-12-03  USC00200032    TMIN         -71
3624  2014-12-04  USC00200032    TMIN         -77
3625  2014-12-05  USC00200032    TMIN         -61
3626  2014-12-06  USC00200032    TMIN         -50
3627  2014-12-07  USC00200032    TMIN         -78
3628  2014-12-08  USC00200032    TMIN         -78
3629  2014-12-09  USC00200032    TMIN         -39
3630  2014-12-10  USC00200032    TMIN         -72
3631  2014-12-11  USC00200032    TMIN         -88
3632  2014-12-12  USC00200032    TMIN         -78

[3631 rows x 4 columns]
</code>```

答:
Can you try

plt.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
```

<p>Instead of </p>

<pre class="lang-py prettyprint-override"><code>plt.gca().fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Filling between two lines on python

Body:
I have the formula below:

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.gca().fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
plt.show()

I would like to fill between the two lines on the line graph below, but somehow my code is not working. Could anyone help understand why?

I thought that the fill_between command would work but for some reason it is not...

When I try:

ax.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)

I get the error message:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

My graph currently looks like this:

The dataframe datamax looks like this:

 Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]

And the dataframe datamin like this:

 Date           ID Element  Data_Value
0     2005-01-01  USC00200032    TMIN         -56
1     2005-01-02  USC00200032    TMIN         -56
2     2005-01-03  USC00200032    TMIN           0
3     2005-01-04  USC00200032    TMIN         -39
4     2005-01-05  USC00200032    TMIN         -94
5     2005-01-06  USC00200032    TMIN        -106
6     2005-01-07  USC00200032    TMIN        -111
7     2005-01-08  USC00200032    TMIN        -100
8     2005-01-09  USC00200032    TMIN         -67
9     2005-01-10  USC00200032    TMIN         -56
10    2005-01-11  USC00200032    TMIN         -22
11    2005-01-12  USC00200032    TMIN         -17
12    2005-01-13  USC00200032    TMIN         -83
13    2005-01-14  USC00200032    TMIN        -128
14    2005-01-15  USC00200032    TMIN        -144
15    2005-01-16  USC00200032    TMIN        -150
16    2005-01-17  USC00200032    TMIN        -189
17    2005-01-18  USC00200032    TMIN        -217
18    2005-01-19  USC00200228    TMIN        -300
19    2005-01-20  USC00200032    TMIN        -156
20    2005-01-21  USC00200032    TMIN        -178
21    2005-01-22  USC00200032    TMIN        -178
22    2005-01-23  USC00200032    TMIN        -250
23    2005-01-24  USC00200032    TMIN        -267
24    2005-01-25  USC00200032    TMIN        -228
25    2005-01-26  USC00200032    TMIN        -206
26    2005-01-27  USC00200032    TMIN        -239
27    2005-01-28  USC00200032    TMIN        -250
28    2005-01-29  USC00200032    TMIN        -222
29    2005-01-30  USC00200228    TMIN        -217
...          ...          ...     ...         ...
3603  2014-11-13  USC00200032    TMIN         -71
3604  2014-11-14  USC00200032    TMIN         -78
3605  2014-11-15  USC00200032    TMIN         -94
3606  2014-11-16  USC00200032    TMIN         -72
3607  2014-11-17  USC00200032    TMIN        -106
3608  2014-11-18  USC00200032    TMIN        -144
3609  2014-11-19  USC00200032    TMIN        -128
3610  2014-11-20  USC00200032    TMIN        -122
3611  2014-11-21  USC00200032    TMIN        -182
3612  2014-11-22  USC00200032    TMIN        -172
3613  2014-11-23  USC00200032    TMIN        -100
3614  2014-11-24  USC00200032    TMIN          -5
3615  2014-11-25  USC00200032    TMIN         -33
3616  2014-11-26  USC00200032    TMIN         -67
3617  2014-11-27  USC00200032    TMIN         -82
3618  2014-11-28  USC00200032    TMIN        -133
3619  2014-11-29  USC00200032    TMIN        -106
3620  2014-11-30  USC00200032    TMIN         -56
3621  2014-12-01  USC00200032    TMIN         -88
3622  2014-12-02  USC00200032    TMIN         -99
3623  2014-12-03  USC00200032    TMIN         -71
3624  2014-12-04  USC00200032    TMIN         -77
3625  2014-12-05  USC00200032    TMIN         -61
3626  2014-12-06  USC00200032    TMIN         -50
3627  2014-12-07  USC00200032    TMIN         -78
3628  2014-12-08  USC00200032    TMIN         -78
3629  2014-12-09  USC00200032    TMIN         -39
3630  2014-12-10  USC00200032    TMIN         -72
3631  2014-12-11  USC00200032    TMIN         -88
3632  2014-12-12  USC00200032    TMIN         -78

[3631 rows x 4 columns]

Body:
Can you try

plt.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)

Instead of

plt.gca().fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)


问:
How to wrap a retrofit response in JAVA?
I have to use a backend that returns me this:

```<code>{
    "ok": true,
    "data": [
        {
            "id": 0,
            "name": "Intempestivo"
        },
        {
            "id": 1,
            "name": "Vacaciones"
        }
}
</code>```

But other times it returns me something like this:

```<code>{
    "ok": true,
    "data": [
        {
            "id": 10,
            "startDate": "2020-05-29T12:00:00.000Z",
            "endDate": "2020-05-30T12:00:00.000Z",
            "status": "En revision",
            "type": "Vacaciones"
        },
        {
            "id": 11,
            "startDate": "2020-05-29T12:00:00.000Z",
            "endDate": "2020-05-30T12:00:00.000Z",
            "status": "En revision",
            "type": "Vacaciones"
        }
    ]
}
</code>```

How I could wrap this responses in a General Response class where the only thing that change might be the data POJO object.

```<code>public class GeneralResponse<T> {

    @SerializedName("data")
    private WrapperData<T> wrapperData;

    @SerializedName("ok")
    private boolean ok;

    @SerializedName("error")
    private Error error;
}
</code>```

And the wrapper data is:

```<code>public class WrapperData<T> {

    private T dataResponse;

    public WrapperData(T POJOResponse) {
        this.dataResponse = POJOResponse;
    }

    public T getDataResponse() {
        return dataResponse;
    }
}
</code>```

The retrofit interface have a method like this:

```<code>@GET("permission_types/")
    Call<GeneralResponse<ArrayList<PermissionType>>> getPermissionTypesWrapped();
</code>```

But when I make the request I got the following exception:

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 'n' column 'n' path $.data
</code>```

答:
I just solve this.

I replace private WrapperData <T> wrapperData; to private <T> wrapperDate; so when I wnat to get a list I call Call<GeneralResponse<Collection<PermissionTypes>>>

Body:
I have to use a backend that returns me this:

{
    "ok": true,
    "data": [
        {
            "id": 0,
            "name": "Intempestivo"
        },
        {
            "id": 1,
            "name": "Vacaciones"
        }
}

But other times it returns me something like this:

{
    "ok": true,
    "data": [
        {
            "id": 10,
            "startDate": "2020-05-29T12:00:00.000Z",
            "endDate": "2020-05-30T12:00:00.000Z",
            "status": "En revision",
            "type": "Vacaciones"
        },
        {
            "id": 11,
            "startDate": "2020-05-29T12:00:00.000Z",
            "endDate": "2020-05-30T12:00:00.000Z",
            "status": "En revision",
            "type": "Vacaciones"
        }
    ]
}

How I could wrap this responses in a General Response class where the only thing that change might be the data POJO object.

public class GeneralResponse<T> {

    @SerializedName("data")
    private WrapperData<T> wrapperData;

    @SerializedName("ok")
    private boolean ok;

    @SerializedName("error")
    private Error error;
}

And the wrapper data is:

public class WrapperData<T> {

    private T dataResponse;

    public WrapperData(T POJOResponse) {
        this.dataResponse = POJOResponse;
    }

    public T getDataResponse() {
        return dataResponse;
    }
}

The retrofit interface have a method like this:

@GET("permission_types/")
    Call<GeneralResponse<ArrayList<PermissionType>>> getPermissionTypesWrapped();

But when I make the request I got the following exception:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 'n' column 'n' path $.data


问:
How do I find element in object typescript code
So, am trying to assign colours to my icons dynamically ... but this line of code keeps complaining,

```<code>let icon = iconsList[name];
</code>```

When I hover of it .. This is the explanation "

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.
    No index signature with a parameter of type 'string' was found on type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.ts(7053)

interface Props{
    name:string,
}

const Icon = ({ name }:Props) => {
    const iconsList = {
      heart: '',
      star: '',
      like: '',
      dislike: '',
      flash: '',
      marker: '',
      filter: '',
      user: '',
      circle: '',
      hashtag: '',
      calendar: '',
      chevronLeft: '',
      optionsV: '',
      optionsH: '',
      chat: '',
      explore: ''
    };

    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
  };

  export default Icon;
  ```

ScreenShot of the code in Vscode On line 25, am trying to pick the specific icon color but it complains

答:
You can make indexable type  for this type of object

type KeyValues = {
  [index: string]: string
}

const iconsList: KeyValues = {
   ...values...
}
```

Body:
So, am trying to assign colours to my icons dynamically ... but this line of code keeps complaining,

let icon = iconsList[name];

When I hover of it .. This is the explanation "

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.
    No index signature with a parameter of type 'string' was found on type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.ts(7053)

interface Props{
    name:string,
}

const Icon = ({ name }:Props) => {
    const iconsList = {
      heart: '',
      star: '',
      like: '',
      dislike: '',
      flash: '',
      marker: '',
      filter: '',
      user: '',
      circle: '',
      hashtag: '',
      calendar: '',
      chevronLeft: '',
      optionsV: '',
      optionsH: '',
      chat: '',
      explore: ''
    };

    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
  };

  export default Icon;

ScreenShot of the code in Vscode On line 25, am trying to pick the specific icon color but it complains


问:
R: find and set to zero each element in a vector that does not appear in another vector
I have two numeric vectors:

```<code>a <- c(1,2,3,4,5,6,7,8)
b <- c(4,2,2,3,9,10,7,7,10,14)
</code>```

I want to set any number in b that does not appear in a to zero.
 My desired result is:

```<code>c <- c(4,2,2,3,0,0,7,7,0,0)
</code>```

who can I do this in an elegant way?

(I was thinking to use left_join but I think there must be some more elegant approach)

答: ifelse(b %in% a, b, 0) seems to do it.</p>

Body:
I have two numeric vectors:

a <- c(1,2,3,4,5,6,7,8)
b <- c(4,2,2,3,9,10,7,7,10,14)

I want to set any number in b that does not appear in a to zero.
 My desired result is:

c <- c(4,2,2,3,0,0,7,7,0,0)

who can I do this in an elegant way?

(I was thinking to use left_join but I think there must be some more elegant approach)

Body: ifelse(b %in% a, b, 0) seems to do it.


问:
Shopify: Adding customer[tags] on login form
At registration i add a language tag using the customer[tags]

```<code><input type="hidden" name="customer[tags]" value="lng:fr">
</code>```

I added the same script to customer_login form to update old customer but it does not seem to work.

Any idea ?

答:
You can't add tags on login, only at register.

This is limitation set by Shopify.

If you like to create a tag on login you will be required to create a custom APP that will handle this, there is no default way to achieve this only liquid.

Body:
At registration i add a language tag using the customer[tags]

<input type="hidden" name="customer[tags]" value="lng:fr">

I added the same script to customer_login form to update old customer but it does not seem to work.

Any idea ?


问:
Associating two types together
I have some code here which implements the Command pattern.

type Type<T> = Function & { prototype: T }

export class CommandBus<Context, Command> {
  private handlers = new Map<Function, Function>()
  private defaultHandler: Handler<Context, Command> = (_, command) => {
    throw new Error(`No handler registered for commands of type ${command.constructor.name}`)
  }

  constructor(readonly target: Context) {}

  handle<HandledCommand extends Command, Result>(
    commandType: Type<HandledCommand>,
    handler: Handler<Context, HandledCommand, Result>,
  ) {
    this.handlers.set(commandType, handler)
    return this
  }

  do(command: Command) {
    const handler = this.handlers.get(command.constructor) || this.defaultHandler
    return handler(this.target, command)
  }
}

export interface Handler<Context, HandledCommand, Result = void> {
  (target: Context, command: HandledCommand): Result
}
```

The tests for it are here and some other examples of it being used are here and here.

I'm pretty new to typescript, and the thing I can't figure out is how to model the association between a Command (which in this CQRS-ish implementation of the pattern, is basically just a message) and the expected result type.

At the moment, we're having to specify the return type as we call the handler function but I feel like this could be baked into the type of the Command, and from there imply a return-type from the Handler).

I think I maybe need to use a tuple type, such that a command is defined not just as GetRefs or whatever, but as [GetRefs, Promise<Ref[]>. I'm not sure where or how to do this.

答:
As I understand it, you're looking for a way to change handle from

handle<HandledCommand extends Command, Result>(
    commandType: Type<HandledCommand>,
    handler: HandlesCommands<Context, HandledCommand, Result>,
  ): CommandBus<Context, Command> {
    this.handlers.set(commandType, handler)
    return this
  }
```

<p>to </p>

<pre class="lang-js prettyprint-override"><code>handle<HandledCommand extends Command, Result>(
    handler: HandlesCommands<Context, HandledCommand, Result>,
  ): CommandBus<Context, Command> {
    const commandType: Type<HandledCommand> = magic(handler)
    this.handlers.set(commandType, handler)
    return this
  }
</code>```

Is that right?

If so, the short answer is "no". You need a reference to the class object for commandType to use at runtime as a key for the handlers. You can get the type of commandType from the handler argument, but you can't get a reference to the class object.

The distinction is between type declaration space and variable declaration space -- more on that in TypeScript Deep Dive: Declaration Spaces.

Since you can't get the class object from a type, any answer to your question will amount to re-arranging the code so the class object is passed in as a parameter in some other way -- but it will still need to be passed in to each call to handle somehow.

Title: Associating two types together

Body:
I have some code here which implements the Command pattern.

type Type<T> = Function & { prototype: T }

export class CommandBus<Context, Command> {
  private handlers = new Map<Function, Function>()
  private defaultHandler: Handler<Context, Command> = (_, command) => {
    throw new Error(`No handler registered for commands of type ${command.constructor.name}`)
  }

  constructor(readonly target: Context) {}

  handle<HandledCommand extends Command, Result>(
    commandType: Type<HandledCommand>,
    handler: Handler<Context, HandledCommand, Result>,
  ) {
    this.handlers.set(commandType, handler)
    return this
  }

  do(command: Command) {
    const handler = this.handlers.get(command.constructor) || this.defaultHandler
    return handler(this.target, command)
  }
}

export interface Handler<Context, HandledCommand, Result = void> {
  (target: Context, command: HandledCommand): Result
}

The tests for it are here and some other examples of it being used are here and here.

I'm pretty new to typescript, and the thing I can't figure out is how to model the association between a Command (which in this CQRS-ish implementation of the pattern, is basically just a message) and the expected result type.

At the moment, we're having to specify the return type as we call the handler function but I feel like this could be baked into the type of the Command, and from there imply a return-type from the Handler).

I think I maybe need to use a tuple type, such that a command is defined not just as GetRefs or whatever, but as [GetRefs, Promise<Ref[]>. I'm not sure where or how to do this.

Body:
As I understand it, you're looking for a way to change handle from

handle<HandledCommand extends Command, Result>(
    commandType: Type<HandledCommand>,
    handler: HandlesCommands<Context, HandledCommand, Result>,
  ): CommandBus<Context, Command> {
    this.handlers.set(commandType, handler)
    return this
  }

to

handle<HandledCommand extends Command, Result>(
    handler: HandlesCommands<Context, HandledCommand, Result>,
  ): CommandBus<Context, Command> {
    const commandType: Type<HandledCommand> = magic(handler)
    this.handlers.set(commandType, handler)
    return this
  }

Is that right?

If so, the short answer is "no". You need a reference to the class object for commandType to use at runtime as a key for the handlers. You can get the type of commandType from the handler argument, but you can't get a reference to the class object.

The distinction is between type declaration space and variable declaration space -- more on that in TypeScript Deep Dive: Declaration Spaces.

Since you can't get the class object from a type, any answer to your question will amount to re-arranging the code so the class object is passed in as a parameter in some other way -- but it will still need to be passed in to each call to handle somehow.


答:
Use the negation of the %in% condition:

```<code>b[!b %in% a] <- 0
</code>```

Title: R: find and set to zero each element in a vector that does not appear in another vector

Body:
Use the negation of the %in% condition:

b[!b %in% a] <- 0


问:
How to render a component onClick with a button in another component?
I'm trying to render  component with an "Edit" button that is within the  component. I decided to use conditional rendering in my code, but I can't seem to get it to work properly. Does anyone have any ideas on how I can achieve this result? I feel like I'm coming to a break through, but I don't know what I'm missing.

ClientTable.js

```<code>import React, { Component } from "react";
import { Table, Container, Button } from "reactstrap";
import { connect } from "react-redux";
import {
  getClients,
  addClient,
  deleteClient,
  setClientToEdit,
} from "../actions/clientActions";
import PropTypes from "prop-types";
import ClientEditModal from "./ClientEditModal";

class ClientTable extends Component {
  state = {
    isOpen: false,
  };

  componentDidMount() {
    this.props.getClients();
  }

  openEditModal = () => {
    if (this.state.isOpen === false) {
      return <ClientEditModal />;
    } else {
      return null;
    }
  };

  onDeleteClick = (id) => {
    this.props.deleteClient(id);
  };

  renderClient = (clients, _id) => {
    return (
      <tr key={_id} timeout={500} classNames="fade">
        <td>
          <Button
            className="remove-btn"
            color="danger"
            size="sm"
            onClick={() => this.onDeleteClick(clients._id)}
          >
            ×
          </Button>

          <Button
            style={{ marginLeft: ".2rem" }}
            className="add-btn"
            outline
            color="warning"
            size="sm"
            onClick={this.openEditModal}
          >
            Edit
          </Button>

          <Button
            style={{ marginLeft: ".3rem" }}
            className="detail-btn"
            outline
            color="info"
            size="sm"
            onClick={this.toggleDetails}
          >
            Details
          </Button>
        </td>
        <td>{clients.name}</td>
        <td>{clients.email}</td>
        <td>{clients.number}</td>
      </tr>
    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      <Container id="listContainer">
        <Table
          id="listTable"
          className="table-striped table-bordered table-hover"
          dark
        >
          <tr class="listRow">
            <thead id="tableHeader">
              <tr>
                <th id="listActions">Actions</th>
                <th id="listName">Name</th>
                <th id="listEmail">Email</th>
                <th id="listNumber">Number</th>
              </tr>
            </thead>
            <tbody class="listRow">{clients.map(this.renderClient)}</tbody>
          </tr>
        </Table>
      </Container>
    );
  }
}

ClientTable.propTypes = {
  getClients: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
});

export default connect(mapStateToProps, {
  getClients,
  deleteClient,
  addClient,
  setClientToEdit,
})(ClientTable);
</code>```

ClientEditModal.js

```<code>import React, { Component } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input,
} from "reactstrap";
import { connect } from "react-redux";
import { editClient } from "../actions/clientActions";
import PropTypes from "prop-types";

class ClientEditModal extends Component {
  state = {
    modal: false,
  };

  componentDidMount() {
    this.props.editClient();
  }

  toggle = () => {
    this.setState({
      modal: !this.state.modal,
    });
  };

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

    // Close modal
    this.toggle();
  };

  render() {
    const { clients } = this.props.client;
    return (
      // Split button into separate component
      <div>
        <Modal isOpen={this.state.modal} toggle={this.toggle}>
          <ModalHeader toggle={this.toggle}> Edit</ModalHeader>

          <ModalBody>
            <Form onSubmit={this.onSubmit}>
              <FormGroup>
                <Label for="name"> Name </Label>
                <Input
                  type="text"
                  name="name"
                  id="client"
                  value={clients.name}
                  onChange={this.onChange}
                ></Input>
                <Label for="email"> Email </Label>
                <Input
                  type="text"
                  name="email"
                  id="client"
                  value={clients.email}
                  onChange={this.onChange}
                ></Input>
                <Label for="number"> Number </Label>
                <Input
                  type="text"
                  name="number"
                  id="number"
                  value={clients.number}
                  onChange={this.onChange}
                ></Input>
                <Button color="dark" style={{ marginTop: "2rem" }} block>
                  Submit Client Edit
                </Button>
              </FormGroup>
            </Form>
          </ModalBody>
        </Modal>
      </div>
    );
  }
}

ClientEditModal.propTypes = {
  editClient: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
});

export default connect(mapStateToProps, { editClient })(ClientEditModal);
</code>```

答:
onClick cannot return a component, that doesn't make sense.

In onClick you should set the state. And in the render you need to check the state and render the component

eg:

```<code>{this.state.isOpen ? <ClientEditModal /> : null}
</code>```

and your openEditModal function will look like this

```<code>openEditModal = () => {
    if (this.state.isOpen === false) {
      this.setState({isOpen: true})
    }
  };
</code>```

Your clientTable.jsx will be

```<code>import React, { Component } from "react";
import { Table, Container, Button } from "reactstrap";
import { connect } from "react-redux";
import {
  getClients,
  addClient,
  deleteClient,
  setClientToEdit,
} from "../actions/clientActions";
import PropTypes from "prop-types";
import ClientEditModal from "./ClientEditModal";

class ClientTable extends Component {
  state = {
    isOpen: false,
  };

  componentDidMount() {
    this.props.getClients();
  }

  openEditModal = () => {
    if (this.state.isOpen === false) {
      this.setState({isOpen: true})
    }
  };

  onDeleteClick = (id) => {
    this.props.deleteClient(id);
  };

  renderClient = (clients, _id) => {
    return (
      <tr key={_id} timeout={500} classNames="fade">
        <td>
          <Button
            className="remove-btn"
            color="danger"
            size="sm"
            onClick={() => this.onDeleteClick(clients._id)}
          >
            ×
          </Button>

          <Button
            style={{ marginLeft: ".2rem" }}
            className="add-btn"
            outline
            color="warning"
            size="sm"
            onClick={this.openEditModal}
          >
            Edit
          </Button>

          <Button
            style={{ marginLeft: ".3rem" }}
            className="detail-btn"
            outline
            color="info"
            size="sm"
            onClick={this.toggleDetails}
          >
            Details
          </Button>
        </td>
        <td>{clients.name}</td>
        <td>{clients.email}</td>
        <td>{clients.number}</td>
      </tr>
    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      <Container id="listContainer">
        {this.state.isOpen ? <ClientEditModal /> : null };
        <Table
          id="listTable"
          className="table-striped table-bordered table-hover"
          dark
        >
          <tr class="listRow">
            <thead id="tableHeader">
              <tr>
                <th id="listActions">Actions</th>
                <th id="listName">Name</th>
                <th id="listEmail">Email</th>
                <th id="listNumber">Number</th>
              </tr>
            </thead>
            <tbody class="listRow">{clients.map(this.renderClient)}</tbody>
          </tr>
        </Table>
      </Container>
    );
  }
}

ClientTable.propTypes = {
  getClients: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
});

export default connect(mapStateToProps, {
  getClients,
  deleteClient,
  addClient,
  setClientToEdit,
})(ClientTable);
</code>```

Body:
I'm trying to render  component with an "Edit" button that is within the  component. I decided to use conditional rendering in my code, but I can't seem to get it to work properly. Does anyone have any ideas on how I can achieve this result? I feel like I'm coming to a break through, but I don't know what I'm missing.

ClientTable.js

import React, { Component } from "react";
import { Table, Container, Button } from "reactstrap";
import { connect } from "react-redux";
import {
  getClients,
  addClient,
  deleteClient,
  setClientToEdit,
} from "../actions/clientActions";
import PropTypes from "prop-types";
import ClientEditModal from "./ClientEditModal";

class ClientTable extends Component {
  state = {
    isOpen: false,
  };

  componentDidMount() {
    this.props.getClients();
  }

  openEditModal = () => {
    if (this.state.isOpen === false) {
      return <ClientEditModal />;
    } else {
      return null;
    }
  };

  onDeleteClick = (id) => {
    this.props.deleteClient(id);
  };

  renderClient = (clients, _id) => {
    return (

          <Button
            className="remove-btn"
            color="danger"
            size="sm"
            onClick={() => this.onDeleteClick(clients._id)}
          >
            ×
          </Button>

          <Button
            style={{ marginLeft: ".2rem" }}
            className="add-btn"
            outline
            color="warning"
            size="sm"
            onClick={this.openEditModal}
          >
            Edit
          </Button>

          <Button
            style={{ marginLeft: ".3rem" }}
            className="detail-btn"
            outline
            color="info"
            size="sm"
            onClick={this.toggleDetails}
          >
            Details
          </Button>

        {clients.name}
        {clients.email}
        {clients.number}

    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      <Container id="listContainer">

                Actions
                Name
                Email
                Number

{clients.map(this.renderClient)}

      </Container>
    );
  }
}

ClientTable.propTypes = {
  getClients: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
});

export default connect(mapStateToProps, {
  getClients,
  deleteClient,
  addClient,
  setClientToEdit,
})(ClientTable);

ClientEditModal.js

import React, { Component } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input,
} from "reactstrap";
import { connect } from "react-redux";
import { editClient } from "../actions/clientActions";
import PropTypes from "prop-types";

class ClientEditModal extends Component {
  state = {
    modal: false,
  };

  componentDidMount() {
    this.props.editClient();
  }

  toggle = () => {
    this.setState({
      modal: !this.state.modal,
    });
  };

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

    // Close modal
    this.toggle();
  };

  render() {
    const { clients } = this.props.client;
    return (
      // Split button into separate component

        <Modal isOpen={this.state.modal} toggle={this.toggle}>
          <ModalHeader toggle={this.toggle}> Edit</ModalHeader>

          <ModalBody>
            <Form onSubmit={this.onSubmit}>
              <FormGroup>
                 Name
                <Input
                  type="text"
                  name="name"
                  id="client"
                  value={clients.name}
                  onChange={this.onChange}
                ></Input>
                 Email
                <Input
                  type="text"
                  name="email"
                  id="client"
                  value={clients.email}
                  onChange={this.onChange}
                ></Input>
                 Number
                <Input
                  type="text"
                  name="number"
                  id="number"
                  value={clients.number}
                  onChange={this.onChange}
                ></Input>
                <Button color="dark" style={{ marginTop: "2rem" }} block>
                  Submit Client Edit
                </Button>
              </FormGroup>
            </Form>
          </ModalBody>
        </Modal>

    );
  }
}

ClientEditModal.propTypes = {
  editClient: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
});

export default connect(mapStateToProps, { editClient })(ClientEditModal);

Body:
onClick cannot return a component, that doesn't make sense.

In onClick you should set the state. And in the render you need to check the state and render the component

eg:

{this.state.isOpen ? <ClientEditModal /> : null}

and your openEditModal function will look like this

openEditModal = () => {
    if (this.state.isOpen === false) {
      this.setState({isOpen: true})
    }
  };

Your clientTable.jsx will be

import React, { Component } from "react";
import { Table, Container, Button } from "reactstrap";
import { connect } from "react-redux";
import {
  getClients,
  addClient,
  deleteClient,
  setClientToEdit,
} from "../actions/clientActions";
import PropTypes from "prop-types";
import ClientEditModal from "./ClientEditModal";

class ClientTable extends Component {
  state = {
    isOpen: false,
  };

  componentDidMount() {
    this.props.getClients();
  }

  openEditModal = () => {
    if (this.state.isOpen === false) {
      this.setState({isOpen: true})
    }
  };

  onDeleteClick = (id) => {
    this.props.deleteClient(id);
  };

  renderClient = (clients, _id) => {
    return (
      <tr key={_id} timeout={500} classNames="fade">
        <td>
          <Button
            className="remove-btn"
            color="danger"
            size="sm"
            onClick={() => this.onDeleteClick(clients._id)}
          >
            &times;
          </Button>

          <Button
            style={{ marginLeft: ".2rem" }}
            className="add-btn"
            outline
            color="warning"
            size="sm"
            onClick={this.openEditModal}
          >
            Edit
          </Button>

          <Button
            style={{ marginLeft: ".3rem" }}
            className="detail-btn"
            outline
            color="info"
            size="sm"
            onClick={this.toggleDetails}
          >
            Details
          </Button>
        </td>
        <td>{clients.name}</td>
        <td>{clients.email}</td>
        <td>{clients.number}</td>
      </tr>
    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      <Container id="listContainer">
        {this.state.isOpen ? <ClientEditModal /> : null };
        <Table
          id="listTable"
          className="table-striped table-bordered table-hover"
          dark
        >
          <tr class="listRow">
            <thead id="tableHeader">
              <tr>
                <th id="listActions">Actions</th>
                <th id="listName">Name</th>
                <th id="listEmail">Email</th>
                <th id="listNumber">Number</th>
              </tr>
            </thead>
            <tbody class="listRow">{clients.map(this.renderClient)}</tbody>
          </tr>
        </Table>
      </Container>
    );
  }
}

ClientTable.propTypes = {
  getClients: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
});

export default connect(mapStateToProps, {
  getClients,
  deleteClient,
  addClient,
  setClientToEdit,
})(ClientTable);


问:
Make button width fit to the text
While I was fiddling with this 'Fancy 3D Button' example, I found that the width seemed to be hard-coded to fit the text's width.

Here is the HTML / CSS:

body {
  background-image: url(http://subtlepatterns.com/patterns/ricepaper.png)
}
a {
  position: relative;
  color: rgba(255, 255, 255, 1);
  text-decoration: none;
  background-color: rgba(219, 87, 5, 1);
  font-family: 'Yanone Kaffeesatz';
  font-weight: 700;
  font-size: 3em;
  display: block;
  padding: 4px;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
  -webkit-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  -moz-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  margin: 100px auto;
  width: 160px;
  text-align: center;
  -webkit-transition: all .1s ease;
  -moz-transition: all .1s ease;
  -ms-transition: all .1s ease;
  -o-transition: all .1s ease;
  transition: all .1s ease;
}
a:active {
  -webkit-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  -moz-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  position: relative;
  top: 6px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700' rel='stylesheet' type='text/css'>

Push me!</code>```

If I remove the width property, the button would fill the page width.

Is there any way to make the button's width fit to the text, automatically?

答:
I like Roger Cruz's answer of:

```<code>width: fit-content;
</code>```

and I just want to add that you can use

```<code>padding: 0px 10px;
</code>```

to add a nice 10px padding on the right and left side of the text in the button. Otherwise the text would be right up along the edge of the button and that wouldn't look good.

ContentLicense: CC BY-SA 3.0

Title: Make button width fit to the text

Body:
While I was fiddling with this 'Fancy 3D Button' example, I found that the width seemed to be hard-coded to fit the text's width.

Here is the HTML / CSS:

body {
  background-image: url(http://subtlepatterns.com/patterns/ricepaper.png)
}
a {
  position: relative;
  color: rgba(255, 255, 255, 1);
  text-decoration: none;
  background-color: rgba(219, 87, 5, 1);
  font-family: 'Yanone Kaffeesatz';
  font-weight: 700;
  font-size: 3em;
  display: block;
  padding: 4px;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
  -webkit-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  -moz-box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  box-shadow: 0px 9px 0px rgba(219, 31, 5, 1), 0px 9px 25px rgba(0, 0, 0, .7);
  margin: 100px auto;
  width: 160px;
  text-align: center;
  -webkit-transition: all .1s ease;
  -moz-transition: all .1s ease;
  -ms-transition: all .1s ease;
  -o-transition: all .1s ease;
  transition: all .1s ease;
}
a:active {
  -webkit-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  -moz-box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  box-shadow: 0px 3px 0px rgba(219, 31, 5, 1), 0px 3px 6px rgba(0, 0, 0, .9);
  position: relative;
  top: 6px;
}

<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700' rel='stylesheet' type='text/css'>

Push me!

If I remove the width property, the button would fill the page width.

Is there any way to make the button's width fit to the text, automatically?

Body:
I like Roger Cruz's answer of:

width: fit-content;

and I just want to add that you can use

padding: 0px 10px;

to add a nice 10px padding on the right and left side of the text in the button. Otherwise the text would be right up along the edge of the button and that wouldn't look good.


答:
You can do this by subsetting b with the %in% function:

```<code>b[! b %in% a] <- 0
</code>```

Body:
You can do this by subsetting b with the %in% function:

b[! b %in% a] <- 0


问:
create an horizontal List View inside a child of Horizontal ListView
I am new in flutter and I want to show an horizontal list when i click in a child of an Horizontal ListView.

I Tried with this code but i dont knpw how to add the child ListView when I taped in InkWell
there is another way to this,

```<code>   class Category extends StatelessWidget {
  final String image_location;
  final String image_caption;

  Category({this.image_location, this.image_caption});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: InkWell(
        onTap: () {
          //Show the other listView
        },
        child: Container(
          width: 100.0,
          child: ListTile(
            title: Image.asset(
              image_location,
              width: 100.0,
              height: 80.0,
            ),
            subtitle: Container(
              alignment: Alignment.topCenter,
              child: Text(image_caption, style: new TextStyle(fontSize: 12.0),),
            )
          ),
        ),
      ),
    );
  }
}
</code>```

My ListView

```<code>    class HorizontalList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80.0,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: <Widget>[
          Category(
            image_location: 'images/cats/tshirt.png',
            image_caption: 'shirt',
          ),

          Category(
            image_location: 'images/cats/dress.png',
            image_caption: 'dress',
          ),

          Category(
            image_location: 'images/cats/jeans.png',
            image_caption: 'pants',
          ),

        ],
      ),
    );
  }
}
</code>```

Thias an example What i Need

答:
I tried to achieve something similar using Stack, ListView, and other common widgets.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Demo App',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: SimpleTab(),
    );
  }
}

class CustomTab {
  const CustomTab({this.title, this.color});

  final String title;
  final Color color;
}

class SimpleTab extends StatefulWidget {
  @override
  _SimpleTabState createState() => _SimpleTabState();
}

class _SimpleTabState extends State<SimpleTab>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
  }

  String selectedContainer = "";
  var data = [
    {
      'name': 'Shopping',
      'icon': Icons.local_shipping,
      'submenu': [
        "Action1",
        "Action2",
        "Action1",
        "Action2",
        "Action1",
        "Action2",
        "Action1",
        "Action2"
      ]
    },
    {
      'name': 'Service',
      'icon': Icons.room_service,
      'submenu': ["Action3", "Action5"]
    },
    {
      'name': 'Hotel',
      'icon': Icons.hotel,
      'submenu': ["Action4", "Action5"]
    },
    {
      'name': 'More',
      'icon': Icons.more,
      'submenu': ["Action6", "Action7"]
    },
    {
      'name': 'Custom',
      'icon': Icons.add_to_photos,
      'submenu': ["Action8", "Action9"]
    },
    {
      'name': 'Custom2',
      'icon': Icons.add_to_photos,
      'submenu': ["Action10", "Action11"]
    },
    {
      'name': 'Custom3',
      'icon': Icons.add_to_photos,
      'submenu': ["Action11", "Action12"]
    },
    {
      'name': 'Custom4',
      'icon': Icons.add_to_photos,
      'submenu': ["Action13", "Action14"]
    },
  ];

  @override
  Widget build(BuildContext context) {
//    selectedContainer = "";
    return Scaffold(
      backgroundColor: Colors.blueGrey,
      body: Stack(
        children: <Widget>[
          SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[],
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: bottomBar(data),
          )
        ],
      ),
    );
  }

  Widget bottomBar(data) {
    return new Container(
        margin: EdgeInsets.only(bottom: 10),
        constraints: new BoxConstraints(
          minHeight: 40.0,
          maxHeight: 140.0,
        ),
        color: Colors.transparent,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Expanded(
              child: createTopMenu(),
            ),
            Expanded(
              child: new ListView(
                scrollDirection: Axis.horizontal,
                children: data
                    .map<Widget>((e) => Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    AnimatedContainer(
                      height: selectedContainer != e['name'] ? 50 : 60,
                      width: selectedContainer != e['name'] ? 70 : 80,
                      duration: Duration(milliseconds: 150),
                      curve: Curves.fastOutSlowIn,
                      child: GestureDetector(
                        child: new Container(
                          color: Colors.transparent,
                          margin: EdgeInsets.only(right: 20, left: 4),
                          child: AnimatedContainer(
                            decoration: new BoxDecoration(
                              color: Colors.white,
                              shape: BoxShape.circle,
                            ),
                            duration: Duration(milliseconds: 150),
                            curve: Curves.fastOutSlowIn,
                            width: selectedContainer != e['name']
                                ? 30
                                : 40,
                            child: new LayoutBuilder(
                                builder: (context, constraint) {
                                  return Padding(
                                      padding: EdgeInsets.all(4),
                                      child: new Icon(
                                        e['icon'],
                                        size: constraint.biggest.width - 16,
                                        color:
                                        selectedContainer != e['name']
                                            ? Colors.grey
                                            : Colors.green,
                                      ));
                                }),
                          ),
                        ),
                        onTap: () {
                          setState(() {
                            if (selectedContainer == e['name']) {
                              selectedContainer = '';
                            } else {
                              selectedContainer = e['name'];
                            }
                          });
                        },
                      ),
                    ),
                  ],
                ))
                    .toList(),
              ),
            )
          ],
        ));
  }

  Widget createTopMenu() {
    if (selectedContainer == "") {
      return Container();
    }
    var item =
    this.data.firstWhere((element) => element["name"] == selectedContainer);
    if (item == null) return Container();
    return new ListView(
      scrollDirection: Axis.horizontal,
      children: (item['submenu'] as List<String>)
          .map<Widget>((e) => Column(
        mainAxisAlignment: MainAxisAlignment.end,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          GestureDetector(
            child: new Container(
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.green, width: 2),
                    color: Colors.white,
                    borderRadius:
                    BorderRadius.all(Radius.circular(20))),
                height: 40,
                padding: EdgeInsets.all(10),
                margin: EdgeInsets.only(right: 20, left: 4),
                child: Text(
                  e,
                  style: TextStyle(color: Colors.green),
                )),
            onTap: () {},
          ),
        ],
      ))
          .toList(),
    );
  }
}
```

Body:
I am new in flutter and I want to show an horizontal list when i click in a child of an Horizontal ListView.

I Tried with this code but i dont knpw how to add the child ListView when I taped in InkWell
there is another way to this,

   class Category extends StatelessWidget {
  final String image_location;
  final String image_caption;

  Category({this.image_location, this.image_caption});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: InkWell(
        onTap: () {
          //Show the other listView
        },
        child: Container(
          width: 100.0,
          child: ListTile(
            title: Image.asset(
              image_location,
              width: 100.0,
              height: 80.0,
            ),
            subtitle: Container(
              alignment: Alignment.topCenter,
              child: Text(image_caption, style: new TextStyle(fontSize: 12.0),),
            )
          ),
        ),
      ),
    );
  }
}

My ListView

    class HorizontalList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80.0,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: <Widget>[
          Category(
            image_location: 'images/cats/tshirt.png',
            image_caption: 'shirt',
          ),

          Category(
            image_location: 'images/cats/dress.png',
            image_caption: 'dress',
          ),

          Category(
            image_location: 'images/cats/jeans.png',
            image_caption: 'pants',
          ),

        ],
      ),
    );
  }
}

Thias an example What i Need


问:
How to scroll the Scrollbox by .Perform() or SendMessage if Scrollbar.visible := False?
I have observed that when you hide the Horizontal Scrollbar, it will not scroll when using the

sbxStudyBtnHolder.Perform(WM_HSCROLL, SB_LINEDOWN, 0);

how can we make it possible?

答:
You can't be back scrolling after this.
Try this:

```<code>ScrollBox1.ScrollInView(panel[n]);
</code>```

panel[n] is the TControl you like to see.

Body:
You can't be back scrolling after this.
Try this:

ScrollBox1.ScrollInView(panel[n]);

panel[n] is the TControl you like to see.


问:
How to bin timestamp data into buckets of n minutes in postgres
I have the following query which works, binning timestamped "observations" into buckets whose boundaries are defined by the bins table:

```<code>SELECT
  count(id),
  width_bucket(
      time :: TIMESTAMP,
      (SELECT ARRAY(SELECT start_time
                    FROM bins
                    WHERE owner_id = 'some id'
                    ORDER BY start_time ASC) :: TIMESTAMP[])
  ) bucket
FROM observations
WHERE owner_id = 'some id'
GROUP BY bucket
ORDER BY bucket;
</code>```

I would like to modify this to allow for querying arbitrary n-minute bins starting from a specified timestamp, rather than having to pull from from an actual "bins" table.

That is, given a start time, a "bin width" in minutes, and a number of bins, is there a way I can generate the array of timestamps to pass into the width_bucket function?

Alternatively, is there a different/simpler approach to get the same results?

答:
A different approach without a series:

Divide the difference of time and start by the width of the bin (5 minutes in the example) and add 1 because the first bucket of width_bucket(...) is 1 not 0.

```<code>floor(extract(epoch from (time - '2019-06-04 00:00'::timestamp)) / (5 * 60) ) + 1 as bucket
</code>```

Getting the start of the bin is also possible

```<code>to_timestamp(floor(extract(epoch from a.time) / (5 * 60)) * (5 * 60)) as bin_start
</code>```

Putting this all together:

```<code>SELECT
  count(id),
  floor(extract(epoch from (time - '2019-06-04 00:00'::timestamp)) / (5 * 60) ) + 1 as bucket,
  to_timestamp(floor(extract(epoch from time) / (5 * 60)) * (5 * 60)) as bin_start
FROM observations
WHERE owner_id = 'some id'
GROUP BY bucket, bin_start
ORDER BY bucket;
</code>```

Body:
I have the following query which works, binning timestamped "observations" into buckets whose boundaries are defined by the bins table:

SELECT
  count(id),
  width_bucket(
      time :: TIMESTAMP,
      (SELECT ARRAY(SELECT start_time
                    FROM bins
                    WHERE owner_id = 'some id'
                    ORDER BY start_time ASC) :: TIMESTAMP[])
  ) bucket
FROM observations
WHERE owner_id = 'some id'
GROUP BY bucket
ORDER BY bucket;

I would like to modify this to allow for querying arbitrary n-minute bins starting from a specified timestamp, rather than having to pull from from an actual "bins" table.

That is, given a start time, a "bin width" in minutes, and a number of bins, is there a way I can generate the array of timestamps to pass into the width_bucket function?

Alternatively, is there a different/simpler approach to get the same results?

Body:
A different approach without a series:

Divide the difference of time and start by the width of the bin (5 minutes in the example) and add 1 because the first bucket of width_bucket(...) is 1 not 0.

floor(extract(epoch from (time - '2019-06-04 00:00'::timestamp)) / (5 * 60) ) + 1 as bucket

Getting the start of the bin is also possible

to_timestamp(floor(extract(epoch from a.time) / (5 * 60)) * (5 * 60)) as bin_start

Putting this all together:

SELECT
  count(id),
  floor(extract(epoch from (time - '2019-06-04 00:00'::timestamp)) / (5 * 60) ) + 1 as bucket,
  to_timestamp(floor(extract(epoch from time) / (5 * 60)) * (5 * 60)) as bin_start
FROM observations
WHERE owner_id = 'some id'
GROUP BY bucket, bin_start
ORDER BY bucket;


问:
Settings Editor for #develop?
Using Visual C# Express, if I double-click on the Properties/Settings.settings file, I automagically got a special settings editor.  Doing the same under #develop just results in a standard editor, and it looks like Settings.Designer.cs doesn't get updated, so that has to be updated by hand as well.  Is there a plug-in for #develop that I'm missing?  </p>

答:
SharpDevelop is a good free IDE that has a lot of good functionality I wish was in VS2008 pro, Test Coverage comes to mind, but being an open source project somethings are missing, a lot of the special editors for example, I think for the most part this is because the audience it's intended for doesn't use them. </p>

<p>The nice thing is this if it's important to you, you can write a plug-in and give back to the community. </p>

OwnerDisplayName: Paul Morrison

ContentLicense: CC BY-SA 2.5

Title: Settings Editor for #develop?

LastEditorDisplayName: Ian Robinson

Body:
SharpDevelop is a good free IDE that has a lot of good functionality I wish was in VS2008 pro, Test Coverage comes to mind, but being an open source project somethings are missing, a lot of the special editors for example, I think for the most part this is because the audience it's intended for doesn't use them.

The nice thing is this if it's important to you, you can write a plug-in and give back to the community.

OwnerDisplayName: Bob The Janitor


问:
Is there a way to avoid re-importing packages each time script must be executed again?
I wonder, if there a way to "constantly" load python packages and keep them assessible? I mean, assuming I have a basic flask app with three scripts with some functions. Each script has some basic imports like

```<code>#script1.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#script2.py
import pandas as pd
import numpy as np

#script3.py
import pandas as pd
import numpy as np
import smth else and heavyweight
</code>```

So each time the scripts are called from main.py the importing will be started. Is there a way to import all the packages once? Like, if they were somewhere "in cloud" and I just refer to them when I need to.

I thought to create one .py script with all the needed imports in function and make them so to say global, but unsure if it's ok

答:
Aside from being permanent between processes, python imports happen pretty much exactly how you want already. The statement import pandas (with or without the as pd), as well as from pandas import ... go something like this:

Check if the dictionary sys.modules has an entry for 'pandas'. If so, return it.

Otherwise, create an empty module object and insert it as sys.modules['pandas']

Load the module in .../pandas/__init__.py into the empty module

Notice that any occurrence of import pandas after the first will just reference the global sys.modules['pandas'], not perform a from-scratch import. The reason that an empty object is created first is to avoid problems with circular imports.

If script1 imports script2 and vice-versa, you will not go into an infinite loop:

script1 exists as an empty object in sys.modules['script1']

Somewhere in populating the empty namespace, script1 encounters import script2

script2 is creates as an empty object sys.modules['script2']

Somewhere in populating the empty namespace, script2 calls import script1

The import returns the partially initialized script1 object already in sys.modules, and does not attempt to load script1 again from scratch. script1 may not be fully populated, so using its attributes may not work, but that is a different problem.

So the python import system already handles everything at a global level through sys.modules, just not across different processes. However, all scripts run from a single main module will have access to the exact same set of imported module objects, which only get loaded from disk once.

Body:
I wonder, if there a way to "constantly" load python packages and keep them assessible? I mean, assuming I have a basic flask app with three scripts with some functions. Each script has some basic imports like

#script1.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#script2.py
import pandas as pd
import numpy as np

#script3.py
import pandas as pd
import numpy as np
import smth else and heavyweight

So each time the scripts are called from main.py the importing will be started. Is there a way to import all the packages once? Like, if they were somewhere "in cloud" and I just refer to them when I need to.

I thought to create one .py script with all the needed imports in function and make them so to say global, but unsure if it's ok


问:
react native android keyboard empty space
I am trying to fix a problem we are having with the keyboard on android. Due to react-native-gifted-chat, we have to use android:windowSoftInputMode="adjustResize" instead of adjustPan. The problem is, that the chat breaks without adjustResize and all the other stuff (e.g. some textfields in a form) break without adjustPan. I also tried adjustResize|adjustPan, adjustPan|adjustResize and tried to use KeyboardAvoidingView on the Form components, but nothing seems to work. Here is how it looks like when using adjustResize without any KeyboardAvoidingView. It creates some not-clickable grey area above the keyboard. Note that there is no way around adjustResize due to the chat...

Thanks in advance!

答:
For anyone struggling with the same:

The package react-native-set-soft-input-mode allows you to change the softInputMode, e.g. for the chat, the following works fine:

```<code>useEffect(() => {
    if (Platform.OS === 'android') {
      SoftInputMode.set(SoftInputMode.ADJUST_RESIZE);
    }
    return () => {
      if (Platform.OS === 'android') {
        SoftInputMode.set(SoftInputMode.ADJUST_PAN);
      }
    };
  }, []);
</code>```

Body:
For anyone struggling with the same:

The package react-native-set-soft-input-mode allows you to change the softInputMode, e.g. for the chat, the following works fine:

useEffect(() => {
    if (Platform.OS === 'android') {
      SoftInputMode.set(SoftInputMode.ADJUST_RESIZE);
    }
    return () => {
      if (Platform.OS === 'android') {
        SoftInputMode.set(SoftInputMode.ADJUST_PAN);
      }
    };
  }, []);


问:
Setting Label and Text values with javascript-- getting Cannot set property of null error
I have an MVC view where I am trying to set values of certain labels and textboxes in a javascript function.  I can set the label OR the textbox just fine, but if I try to do both, I end up getting a "Caanot Set Property of Null" error.  Here's my view:

```<code><div id='content'>
    Id:<br />
    <label id="datasetId" style="width:140px" />
    <br />

    Label:<br />
    <input type="text" id="txtLabel" style="width:140px" />
    <br />
</div>
</code>```

Then I have a button that calls a javascript function called editDataSet which in turn calls a js function called SetData():

```<code><script>
    function editDataSet(e) {
        //some code
        SetData(existingRecord);
        //more code
    }

    function SetData(dataSet) {
        document.getElementById('datasetId').innerText = "test";
        document.getElementById('txtLabel').value = "3";//errors out here
    }
</code>```

When I run this, I get the error, but if I comment out the line, it runs fine.  If I comment out the first line, and keep the second, it runs fine too.  So

```<code>    function SetData(dataSet) {
        //document.getElementById('datasetId').innerText = "test";
        document.getElementById('txtLabel').value = "3";//now it works
    }
</code>```

works, as does

```<code>    function SetData(dataSet) {
        document.getElementById('datasetId').innerText = "test";
        //document.getElementById('txtLabel').value = "3";//this works too
    }
</code>```

Anyone have any ideas?

答:
The  tag requires a closing .

 is invalid HTML.

MDN docs on label.

function setData() {
  document.getElementById('datasetId').innerText = "test";
  document.getElementById('txtLabel').value = "3";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="setData()">Run Test</button>
<div id='content'>
  Id:<br />

  <!-- changed to valid label -->
  <label id="datasetId" style="width:140px"></label>

  <br /> Label:

  <br />
  <input type="text" id="txtLabel" style="width:140px" />
  <br />
</div></code>```

Body:
I have an MVC view where I am trying to set values of certain labels and textboxes in a javascript function.  I can set the label OR the textbox just fine, but if I try to do both, I end up getting a "Caanot Set Property of Null" error.  Here's my view:

    Id:

    Label:

    <input type="text" id="txtLabel" style="width:140px" />

Then I have a button that calls a javascript function called editDataSet which in turn calls a js function called SetData():

Body:
The <label> tag requires a closing </label>.

<label id="datasetId" style="width:140px" /> is invalid HTML.

MDN docs on label.

function setData() {
  document.getElementById('datasetId').innerText = "test";
  document.getElementById('txtLabel').value = "3";
}

<button onclick="setData()">Run Test</button>
<div id='content'>
  Id:<br />

  <!-- changed to valid label -->
  <label id="datasetId" style="width:140px"></label>

  <br /> Label:

  <br />
  <input type="text" id="txtLabel" style="width:140px" />
  <br />
</div>


问:
python-3: object name as string
I have the following two tables:

"table1":

```<code>a x1
b y1
</code>```

"table2":

```<code>a x2
b y2
</code>```

I want to open them and create the following dictionary:

```<code>{"table1": {"a": ["x1"]}, {"b": ["y1"]}, \
 "table2": {"a": ["x2"]}, {"b": ["y2"]}}
</code>```

To do so, I am currently doing the following:

```<code>with open("table1", "r") as table1, \
    open("table2", "r") as table2:

    dictionary = {"table1": {}, \
                "table2": {}}

    for line in table1:

        col1 = line.split(" ")[0]
        col2 = line.split(" ")[1].strip()

        dictionary["table1"][col1] = col2

    for line in table2:

        col1 = line.split(" ")[0]
        col2 = line.split(" ")[1].strip()

        dictionary["table2"][col1] = col2

print(dictionary)

{'table1': {'a': 'x1', 'b': 'y1'}, 'table2': {'a': 'x2', 'b': 'y2'}}
</code>```

My question is, how can I link the name of the opened table, e.g. table1, to the dictionary key string "table1"?

Something like this (not correct):

```<code>with open("table1", "r") as table1, \
    open("table2", "r") as table2:

    dictionary = dict()

    for table in [table1, table2]:

        for line in table:

            col1 = line.split(" ")[0]
            col2 = line.split(" ")[1].strip()

            dictionary[table][col1] = col2    # HERE I WANT table TO BE "table1", NOT THE OBJECT table1
</code>```

答:
You can store the files in a dictionary with the same keys of the other:

table = dict()
with open("table1", "r") as table['table1'], \
    open("table2", "r") as table['table2']:

    dictionary = dict()

    for table_name in ['table1', 'table2']:

        for line in table[table_name]:

            col1 = line.split(" ")[0]
            col2 = line.split(" ")[1].strip()

            dictionary[table_name]={col1:[col2]}
```

Title: python-3: object name as string

Body:
I have the following two tables:

"table1":

a x1
b y1

"table2":

a x2
b y2

I want to open them and create the following dictionary:

{"table1": {"a": ["x1"]}, {"b": ["y1"]}, \
 "table2": {"a": ["x2"]}, {"b": ["y2"]}}

To do so, I am currently doing the following:

with open("table1", "r") as table1, \
    open("table2", "r") as table2:

    dictionary = {"table1": {}, \
                "table2": {}}

    for line in table1:

        col1 = line.split(" ")[0]
        col2 = line.split(" ")[1].strip()

        dictionary["table1"][col1] = col2

    for line in table2:

        col1 = line.split(" ")[0]
        col2 = line.split(" ")[1].strip()

        dictionary["table2"][col1] = col2

print(dictionary)

{'table1': {'a': 'x1', 'b': 'y1'}, 'table2': {'a': 'x2', 'b': 'y2'}}

My question is, how can I link the name of the opened table, e.g. table1, to the dictionary key string "table1"?

Something like this (not correct):

with open("table1", "r") as table1, \
    open("table2", "r") as table2:

    dictionary = dict()

    for table in [table1, table2]:

        for line in table:

            col1 = line.split(" ")[0]
            col2 = line.split(" ")[1].strip()

            dictionary[table][col1] = col2    # HERE I WANT table TO BE "table1", NOT THE OBJECT table1


问:
Replace everything from a string when it reaches a match
Given:

```<code>path = 'abc/dfg/zxc'
</code>```

Is there a way to replace the string before the first '/' with '.' ?

Expected result:

```<code>'./dfg/zxc'
</code>```

What i have tried, this approah is messy and i am wondering if there is a cleaner one to solving this issue?:

```<code> lst = path.split()

from_index = lst[0].index('/')
to_index = len(lst[0])

new_list = lst[0][from_index -1 + 1:to_index]
new_str = ''.join(new_list)
new_str2 = '.' + new_str
</code>```

答:
This is a way to use the split method:

```<code>path = f"./{path.split('/',1)[1]}"

print(path)
</code>```

Output:

```<code>'./dfg/zxc'
</code>```

Body:
Given:

path = 'abc/dfg/zxc'

Is there a way to replace the string before the first '/' with '.' ?

Expected result:

'./dfg/zxc'

What i have tried, this approah is messy and i am wondering if there is a cleaner one to solving this issue?:

 lst = path.split()

from_index = lst[0].index('/')
to_index = len(lst[0])

new_list = lst[0][from_index -1 + 1:to_index]
new_str = ''.join(new_list)
new_str2 = '.' + new_str

Body:
This is a way to use the split method:

path = f"./{path.split('/',1)[1]}"

print(path)

Output:

'./dfg/zxc'


问:
Read a very long line of text C#
I want to read a very long line of text using C#. The length of the line is about 100000 chars. I am using StreamReader.ReadLine() method. I also want to write this long string to a file. One of them or both are not working properly. I could only write 99328 characters to a file.
How can I read and write a very long line of text using  C#?</p>

答: You are probably failing to call .Flush() on your output stream.</p>

Title: Read a very long line of text C#


问:
How can I print a message say 'NO SLOTS' if there are no items in the array of that particular date in angular?
i have a project in which i am displaying time slots(of next 7 days) of a doctor and i recieve an array which consists of objects of scheduleTime type.

```<code>export class ScheduleTime{
    date: string;
    hours: number;
    minutes: number;
}
</code>```

now i am displaying these slots to the patient.

my html code for displaying the slots is :

```<code>    <div *ngFor="let todayDate of dates; let z = index" class="dateBox">
        <div style="margin-bottom: 10px;">{{fullDate[z] | date: 'fullDate'}}</div>
            <div *ngFor="let time of ScheduleTime; let i = index">
                <div *ngIf="time.date != todayDate">No available Slots</div>
                     <div *ngIf="todayDate == time.date">
                         <div class="timeSlots" [style.background-color]="startSelect>0 && endSelect>0 && i>startSelect && i<endSelect?'rgb(207, 200, 238)':null" [ngClass]="{'startClass': time.hours == st.sh && time.minutes == st.sm && startDate == time.date, 'endClass': time.hours == et.eh && time.minutes == et.em && startDate == time.date}"
                         (click)='timeSelector(time,i,todayDate)'>
                         {{time.hours}}:{{time.minutes | zero}}
                             </div>
                  </div>
             </div>
             <br>
         <hr class="timeBoxHr">
    </div>
</code>```

now the problem is : if there is no time slot for that particular date then it should display the text no time slots

What I have done till now is

If todayDate and the date in the array do not match then print the message "No available slots", else print the slots.

CHECK THIS IMAGE: In this image, I have 5 elements in the array and corresponding time slots are shown

答:
you can use property binding to add message .
eg in your html code write like this
{{message}}
and in your typescript code
you can assign value to it by
this.message="Sorry! No slots available"</p>

Body:
i have a project in which i am displaying time slots(of next 7 days) of a doctor and i recieve an array which consists of objects of scheduleTime type.

export class ScheduleTime{
    date: string;
    hours: number;
    minutes: number;
}

now i am displaying these slots to the patient.

my html code for displaying the slots is :

{{fullDate[z] | date: 'fullDate'}}

No available Slots

0 && endSelect>0 && i>startSelect && i<endSelect?'rgb(207, 200, 238)':null" [ngClass]="{'startClass': time.hours == st.sh && time.minutes == st.sm && startDate == time.date, 'endClass': time.hours == et.eh && time.minutes == et.em && startDate == time.date}"
                         (click)='timeSelector(time,i,todayDate)'>
                         {{time.hours}}:{{time.minutes | zero}}

now the problem is : if there is no time slot for that particular date then it should display the text no time slots

What I have done till now is

If todayDate and the date in the array do not match then print the message "No available slots", else print the slots.

CHECK THIS IMAGE: In this image, I have 5 elements in the array and corresponding time slots are shown