答:
We could loop through the list column with map and do the join

```<code>library(tidyverse)
library(data.table)
df1 %>%
  mutate(data = map(data, ~
       as.data.table(df2)[, date_ret := date][data.table(.x),
     .(ID, date, Var1, filing_date, mgnt, start_date, end_date),
       on = .(ID, date > start_date, date <= end_date)]))
# A tibble: 2 x 2
#  period          data
#  <chr>           <list>
#1 Jy_2014_Je_2015 <df[,7] [7 × 7]>
#2 Jy_2013_Je_2014 <df[,7] [15 × 7]>
</code>```

Title: join dataframe to nested tibbles

Body:
I have a nested tibble:

> df1
# A tibble: 2 x 2
  period          data
  <chr>           <list>
1 Jy_2014_Je_2015 <tibble [7 x 7]>
2 Jy_2013_Je_2014 <tibble [3 x 7]>

Where one of the nests looks like:

> unnest(df1)
# A tibble: 10 x 8
   period          ID       CompYear  filing_date  mgnt  risk start_date end_date
   <chr>           <chr>    <chr>     <date>      <dbl> <dbl> <date>     <date>
 1 Jy_2014_Je_2015 71327810 2013_2014 2014-08-20  0.871 0.749 2015-06-01 2016-05-30
 2 Jy_2014_Je_2015 56357140 2014_2015 2015-02-24  0.915 0.958 2015-06-01 2016-05-30
 3 Jy_2014_Je_2015 71340910 2014_2015 2015-02-10  0.787 0.934 2015-06-01 2016-05-30
 4 Jy_2014_Je_2015 09367110 2013_2014 2014-08-26  0.852 0.750 2015-06-01 2016-05-30
 5 Jy_2014_Je_2015 G5785G10 2014_2015 2015-02-26  0.966 0.991 2015-06-01 2016-05-30
 6 Jy_2014_Je_2015 20825150 2014_2015 2015-03-02  0.966 0.973 2015-06-01 2016-05-30
 7 Jy_2014_Je_2015 55616P10 2014_2015 2015-02-23  0.991 0.920 2015-06-01 2016-05-30
 8 Jy_2013_Je_2014 08499Z00 2013_2014 2014-03-19  0.936 0.282 2014-06-01 2015-05-30
 9 Jy_2013_Je_2014 59268810 2013_2014 2014-02-21  0.952 0.911 2014-06-01 2015-05-30
10 Jy_2013_Je_2014 01858110 2013_2014 2014-01-31  0.953 0.966 2014-06-01 2015-05-30

The df2 looks like:

> df2
           ID       date   Var1   date_ret
  1: 01858110 2012-01-31 110.80 2012-01-31
  2: 01858110 2012-02-29 121.36 2012-02-29
  3: 01858110 2012-03-30 125.96 2012-03-30
  4: 01858110 2012-04-30 128.49 2012-04-30
  5: 01858110 2012-05-31 126.00 2012-05-31
 ---
231: G5785G10 2014-08-29  81.49 2014-08-29
232: G5785G10 2014-09-30  90.15 2014-09-30
233: G5785G10 2014-10-31  92.18 2014-10-31
234: G5785G10 2014-11-28  92.22 2014-11-28
235: G5785G10 2014-12-31  99.03 2014-12-31

I am trying to join df2 and df1 together. df2 is a normal dataframe whereas df1 is a nested tibble. They both contain ID variables I wish to join on and a date - df2 contains monthly dates whereas df1 contains yearly dates. Therefore I create a start_date and end_date to begin and end the joining dates. i.e. I want to join by the ID variable in both df1 and df2 and also the monthly data in df2 to fit "between" the start_date and end_date in df1.

As far as I have got is to unnest the data I want and join them individually.

unnested_data <- unnest(df1)

myJoinedData <- setDT(df2)[, date_ret:=date][data.table(unnested_data),
                                                      .(ID, date, Var1,
                                                        period, filing_date, mgnt, start_date, end_date),
                                                      on = .(ID, date > start_date, date <= end_date)]

Data:

    df1 <- structure(list(period = c("Jy_2014_Je_2015", "Jy_2013_Je_2014"
), data = list(structure(list(ID = c("71327810", "56357140",
"71340910", "09367110", "G5785G10", "20825150", "55616P10"),
    CompYear = c("2013_2014", "2014_2015", "2014_2015", "2013_2014",
    "2014_2015", "2014_2015", "2014_2015"), filing_date = structure(c(16302,
    16490, 16476, 16308, 16492, 16496, 16489), class = "Date"),
    mgnt = c(0.871267898855628, 0.915166869000075, 0.786638982683625,
    0.852085258472343, 0.965682470009356, 0.965813590885971,
    0.990809585984218), risk = c(0.748733465269009, 0.958314403117101,
    0.934083811166365, 0.749665010947671, 0.990592523426367,
    0.973022180801192, 0.920155039512913), start_date = structure(c(16587,
    16587, 16587, 16587, 16587, 16587, 16587), class = "Date"),
    end_date = structure(c(16951, 16951, 16951, 16951, 16951,
    16951, 16951), class = "Date")), row.names = c(NA, -7L), class = c("tbl_df",
"tbl", "data.frame")), structure(list(ID = c("08499Z00", "59268810",
"01858110"), CompYear = c("2013_2014", "2013_2014", "2013_2014"
), filing_date = structure(c(16148, 16122, 16101), class = "Date"),
    mgnt = c(0.936233012426363, 0.951806853733034, 0.953036137199852
    ), risk = c(0.281925228286195, 0.911441002298349, 0.966068420793039
    ), start_date = structure(c(16222, 16222, 16222), class = "Date"),
    end_date = structure(c(16585, 16585, 16585), class = "Date")), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame")))), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"))

Data to join

df2 <- structure(list(ID = c("01858110", "01858110", "01858110", "01858110",
"01858110", "01858110", "01858110", "01858110", "01858110", "01858110",
"01858110", "01858110", "01858110", "01858110", "01858110", "01858110",
"01858110", "01858110", "01858110", "01858110", "01858110", "01858110",
"01858110", "01858110", "01858110", "01858110", "01858110", "01858110",
"01858110", "01858110", "01858110", "01858110", "01858110", "01858110",
"01858110", "01858110", "09367110", "09367110", "09367110", "09367110",
"09367110", "09367110", "09367110", "09367110", "09367110", "09367110",
"09367110", "09367110", "09367110", "09367110", "09367110", "09367110",
"09367110", "09367110", "09367110", "09367110", "09367110", "09367110",
"09367110", "09367110", "09367110", "09367110", "09367110", "09367110",
"09367110", "09367110", "09367110", "09367110", "09367110", "09367110",
"09367110", "09367110", "55616P10", "55616P10", "55616P10", "55616P10",
"55616P10", "55616P10", "55616P10", "55616P10", "55616P10", "55616P10",
"55616P10", "55616P10", "55616P10", "55616P10", "55616P10", "55616P10",
"55616P10", "55616P10", "55616P10", "55616P10", "55616P10", "55616P10",
"55616P10", "55616P10", "55616P10", "55616P10", "55616P10", "55616P10",
"55616P10", "55616P10", "55616P10", "55616P10", "55616P10", "55616P10",
"55616P10", "55616P10", "56357140", "56357140", "56357140", "56357140",
"56357140", "56357140", "56357140", "56357140", "56357140", "56357140",
"56357140", "56357140", "56357140", "56357140", "56357140", "56357140",
"56357140", "56357140", "56357140", "56357140", "56357140", "56357140",
"56357140", "56357140", "56357140", "56357140", "56357140", "56357140",
"56357140", "56357140", "56357140", "56357140", "56357140", "56357140",
"56357140", "56357140", "59268810", "59268810", "59268810", "59268810",
"59268810", "59268810", "59268810", "59268810", "59268810", "59268810",
"59268810", "59268810", "59268810", "59268810", "59268810", "59268810",
"59268810", "59268810", "59268810", "59268810", "59268810", "59268810",
"59268810", "59268810", "59268810", "59268810", "59268810", "59268810",
"59268810", "59268810", "59268810", "59268810", "59268810", "59268810",
"59268810", "59268810", "71327810", "71327810", "71327810", "71327810",
"71327810", "71327810", "71327810", "71327810", "71327810", "71327810",
"71327810", "71327810", "71327810", "71327810", "71327810", "71327810",
"71327810", "71327810", "71327810", "71327810", "71327810", "71327810",
"71327810", "71327810", "71327810", "71327810", "71327810", "71327810",
"71327810", "71327810", "71327810", "71327810", "71327810", "71327810",
"71327810", "71327810", "G5785G10", "G5785G10", "G5785G10", "G5785G10",
"G5785G10", "G5785G10", "G5785G10", "G5785G10", "G5785G10", "G5785G10",
"G5785G10", "G5785G10", "G5785G10", "G5785G10", "G5785G10", "G5785G10",
"G5785G10", "G5785G10", "G5785G10"), date = structure(c(15370,
15399, 15429, 15460, 15491, 15520, 15552, 15583, 15611, 15644,
15674, 15705, 15736, 15764, 15792, 15825, 15856, 15884, 15917,
15947, 15978, 16009, 16038, 16070, 16101, 16129, 16160, 16190,
16220, 16251, 16282, 16311, 16343, 16374, 16402, 16435, 15370,
15399, 15429, 15460, 15491, 15520, 15552, 15583, 15611, 15644,
15674, 15705, 15736, 15764, 15792, 15825, 15856, 15884, 15917,
15947, 15978, 16009, 16038, 16070, 16101, 16129, 16160, 16190,
16220, 16251, 16282, 16311, 16343, 16374, 16402, 16435, 15370,
15399, 15429, 15460, 15491, 15520, 15552, 15583, 15611, 15644,
15674, 15705, 15736, 15764, 15792, 15825, 15856, 15884, 15917,
15947, 15978, 16009, 16038, 16070, 16101, 16129, 16160, 16190,
16220, 16251, 16282, 16311, 16343, 16374, 16402, 16435, 15370,
15399, 15429, 15460, 15491, 15520, 15552, 15583, 15611, 15644,
15674, 15705, 15736, 15764, 15792, 15825, 15856, 15884, 15917,
15947, 15978, 16009, 16038, 16070, 16101, 16129, 16160, 16190,
16220, 16251, 16282, 16311, 16343, 16374, 16402, 16435, 15370,
15399, 15429, 15460, 15491, 15520, 15552, 15583, 15611, 15644,
15674, 15705, 15736, 15764, 15792, 15825, 15856, 15884, 15917,
15947, 15978, 16009, 16038, 16070, 16101, 16129, 16160, 16190,
16220, 16251, 16282, 16311, 16343, 16374, 16402, 16435, 15370,
15399, 15429, 15460, 15491, 15520, 15552, 15583, 15611, 15644,
15674, 15705, 15736, 15764, 15792, 15825, 15856, 15884, 15917,
15947, 15978, 16009, 16038, 16070, 16101, 16129, 16160, 16190,
16220, 16251, 16282, 16311, 16343, 16374, 16402, 16435, 15884,
15917, 15947, 15978, 16009, 16038, 16070, 16101, 16129, 16160,
16190, 16220, 16251, 16282, 16311, 16343, 16374, 16402, 16435
), class = "Date"), Var1 = c(110.800003051758, 121.360000610352,
125.959999084473, 128.490005493164, 126, 135, 130, 137.649993896484,
141.949996948242, 143.050003051758, 142.490005493164, 144.759994506836,
157.600006103516, 158.690002441406, 161.889999389648, 171.770004272461,
177.089996337891, 181.029998779297, 197.779998779297, 195.699996948242,
211.470001220703, 237.059997558594, 242.259994506836, 262.929992675781,
239.660003662109, 285.109985351562, 272.450012207031, 241.899993896484,
256.049987792969, 281.25, 262.290008544922, 264.640014648438,
248.270004272461, 283.350006103516, 285.869995117188, 286.049987792969,
16.3600006103516, 16.2999992370605, 16.4699993133545, 14.6999998092651,
15.2700004577637, 15.9799995422363, 16.1299991607666, 16.5599994659424,
17.3299999237061, 17.7000007629395, 18.0300006866455, 18.5699996948242,
22.7700004577637, 24.8600006103516, 29.4200000762939, 27.7399997711182,
29.2700004577637, 27.75, 31.4300003051758, 27.9099998474121,
26.6599998474121, 28.4400005340576, 27.8899993896484, 29.0400009155273,
30.3999996185303, 31.6399993896484, 30.1900005340576, 28.4200000762939,
29.7800006866455, 33.5200004577637, 32.1300010681152, 33.5299987792969,
31.0100002288818, 32.310001373291, 33.6399993896484, 33.6800003051758,
33.689998626709, 37.9700012207031, 39.7299995422363, 41.0200004577637,
38.0499992370605, 34.3499984741211, 35.8400001525879, 40.310001373291,
37.6199989318848, 38.0699996948242, 38.7000007629395, 39.0200004577637,
39.5099983215332, 41.0999984741211, 41.8400001525879, 44.5999984741211,
48.3400001525879, 48, 48.3400001525879, 44.4300003051758, 43.2700004577637,
46.1100006103516, 53.2599983215332, 53.4000015258789, 53.2000007629395,
57.8600006103516, 59.2900009155273, 57.4300003051758, 59.8899993896484,
58.0200004577637, 57.7900009155273, 62.2900009155273, 58.1800003051758,
57.8199996948242, 64.9100036621094, 65.75, 13.4399995803833,
15.7399997711182, 13.8599996566772, 13.8500003814697, 10.3999996185303,
11.6999998092651, 12, 12.8800001144409, 13.3400001525879, 14.25,
15, 15.6800003051758, 17.6000003814697, 18.5200004577637, 20.5599994659424,
18.7600002288818, 21.0100002288818, 17.9099998474121, 20.5300006866455,
19.9799995422363, 19.5610008239746, 19.4599990844727, 20.5900001525879,
23.3199996948242, 28.4500007629395, 30.9400005340576, 31.4500007629395,
31.7800006866455, 27.0499992370605, 32.8600006103516, 26.5599994659424,
29.4200000762939, 23.4500007629395, 20.8400001525879, 20.1399993896484,
22.1000003814697, 175.5, 180.279998779297, 184.75, 179.320007324219,
156.119995117188, 155.850006103516, 154.800003051758, 165.110000610352,
170.740005493164, 169.369995117188, 187.089996337891, 193.300003051758,
212.529998779297, 212.800003051758, 213.220001220703, 208.960006713867,
218.259994506836, 201.199996948242, 220.600006103516, 220.229995727539,
240.089996337891, 247.460006713867, 246.570007324219, 242.589996337891,
246.300003051758, 245.759994506836, 235.679992675781, 233.119995117188,
245.020004272461, 253.179992675781, 257.140014648438, 270.480010986328,
256.130004882812, 258.470001220703, 293.260009765625, 302.459991455078,
15, 15.039999961853, 14.9200000762939, 14.9300003051758, 9.27999973297119,
9.89999961853027, 9.06999969482422, 8.98999977111816, 10.1800003051758,
9.98999977111816, 10.5699996948242, 9.82999992370605, 11.1300001144409,
11.1300001144409, 11.789999961853, 11.6000003814697, 12.3400001525879,
11.5799999237061, 12.4499998092651, 11.2299995422363, 12.4700002670288,
12.9399995803833, 13.6999998092651, 12.1400003433228, 11.9399995803833,
12.5900001525879, 12.7200002670288, 10.2200002670288, 10.1899995803833,
11.460000038147, 10.5799999237061, 11.1199998855591, 8.90999984741211,
9.52999973297119, 9.73999977111816, 9.81999969482422, NA, 45.8899993896484,
43.6500015258789, 44.0900001525879, 42.0099983215332, 51.9599990844727,
52.2599983215332, 57.8300018310547, 67.6900024414062, 63.4099998474121,
71.2300033569336, 77.7600021362305, 80.0199966430664, 69.620002746582,
81.4899978637695, 90.1500015258789, 92.1800003051758, 92.2200012207031,
99.0299987792969)), row.names = c(NA, -235L), class = "data.frame")

Body:
We could loop through the list column with map and do the join

library(tidyverse)
library(data.table)
df1 %>%
  mutate(data = map(data, ~
       as.data.table(df2)[, date_ret := date][data.table(.x),
     .(ID, date, Var1, filing_date, mgnt, start_date, end_date),
       on = .(ID, date > start_date, date <= end_date)]))
# A tibble: 2 x 2
#  period          data
#  <chr>           <list>
#1 Jy_2014_Je_2015 <df[,7] [7 × 7]>
#2 Jy_2013_Je_2014 <df[,7] [15 × 7]>


来源: stackexchange

问:
Is it safe to use HashSet as a very simple cache in a multi-threaded environment?
I realize there are similar questions/answers to this, but I can't seem to find exactly what I'm looking for.

I'm looking to implement an in-memory cache that caches the result of a call to the DB, which is doing an existence check.  This existence check is quite expensive and once the object exists in the DB it will never be removed, so a very simple cache in-memory (in-process even) is all I need.  Once the DB call is made the process remembers the result of the existence check for that ID and shouldn't call the DB again.

(Maybe another thing to mention is if the object doesn't exist in the DB, it will be created).

I'm using a HashSet (java) for this and just adding the ID to the set when the check/create is done, however this is a highly concurrent environment and I am unsure about the implications of HashSet's lack-of-threadsafeness.

The code only ever uses the add() and contains() methods (no iteration).

I don't really care about a cache miss (and a resulting extra DB call) here and there, but what I'm wondering is if this pattern of add() and contains() being called on the set in concurrent threads could lead to more catastrophic errors.

答:
You can use ConcurrentHashMap for multi threaded access and write operation. If you want only HashSet, you can ConcurrentHashSet derived from ConcurrentHashMap. You can use like this.</p>

```<code>Set<String> myConcurrentSet = ConcurrentHashMap.newKeySet();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use ConcurrentHashMap for multi threaded access and write operation. If you want only HashSet, you can ConcurrentHashSet derived from ConcurrentHashMap. You can use like this.

Set<String> myConcurrentSet = ConcurrentHashMap.newKeySet();


问:
Understanding TransactionScope and SQL Connection
In .NET, when we use TransactionScope we can share a same transaction across multiple connections.

```<code>using(TransactionScope tran = new TransactionScope()) {
  //this method open a new connection
  CallAMethodThatDoesSomeWork();
  //this method open another new connection
  CallAMethodThatDoesSomeMoreWork();
  tran.Complete();
}
</code>```

I can't understand how it is possible, taking account that a transaction need a specific connection to run in the database.

How is it working? I think that maybe the physical connection is always the same. Could be this possible?

Update: suppose that the connection string is the same for all connections, i.e. I don't work with different databases, is always the same...

答:
Thanks to the comments I was able to find the answer here.

When we use TransactionScope we can share a same transaction across multiple connections because this transaction is converted to a distributed transaction; and the Distributed Transaction Coordinator (DTC) do its magic.

In general, even when the connections are to the same DB, TransactionScope will escalate to DTC.

The exception to the rule could be when we open and close different connections to the same DB not simultaneously; but this isn't supported by all DB engines.

Body:
In .NET, when we use TransactionScope we can share a same transaction across multiple connections.

using(TransactionScope tran = new TransactionScope()) {
  //this method open a new connection
  CallAMethodThatDoesSomeWork();
  //this method open another new connection
  CallAMethodThatDoesSomeMoreWork();
  tran.Complete();
}

I can't understand how it is possible, taking account that a transaction need a specific connection to run in the database.

How is it working? I think that maybe the physical connection is always the same. Could be this possible?

Update: suppose that the connection string is the same for all connections, i.e. I don't work with different databases, is always the same...


问:
Don't update if null is given in a procedure
I know an around-about way of accomplishing this but I would like to know the clean and best way to solve my problem. I am using an INSERT INTO with an ON DUPLICATE KEY UPDATE. Sometimes a value is not given but I still have to pass it into the parameter of the procedure otherwise it would fail. So I have been passing in a null value but this will update the field with nulls and I will lose data. So, I would like to "ignore" a field if it a null value gets passed into it. In other words just not update it or get the current value instead and pass that in.

I could use multiple IF statements to just check if a value is null or not but this procedure is about 20 values long and that would seem ridiculous and gratuitous. If there is a better way, I know that it can be done differently.

I'm only going to include part of my procedure for simplicity sake.

```<code>PROCEDURE `p_my_record_create`(
    IN in_group varchar(255),
    IN in_package varchar(255),
    IN in_type enum('A', 'M'),
    IN in_uid varchar(255),
    IN in_member_id int(11),
    IN in_first_name varchar(255)
)
BEGIN
    INSERT INTO myDatabase.my_record
    (`group`, `package`, `type`, `uid`, `member_id`, `first_name`)
    VALUES
    (in_group, in_package, in_type, in_uid, in_member_id, in_first_name)
    ON DUPLICATE KEY UPDATE
        `group` = in_group,
        `package` = in_package,
        `type` = in_type,  #if this is passed in as null then I would like for it to be "ignored" or if any of them are.
        `uid` = in_uid,
        `client_member_id` = in_client_member_id,
        `first_name` = in_first_name;

    SELECT
        record_id
    FROM
        myDatabase.my_record
    WHERE
        record_id = LAST_INSERT_ID();
END
</code>```

If there is a simple way to accomplish this in MySQL, please enlighten me that would really help. Thanks.

答:
```<code>PROCEDURE `p_my_record_create`(
    IN in_group varchar(255),
    IN in_package varchar(255),
    IN in_type enum('A', 'M'),
    IN in_uid varchar(255),
    IN in_member_id int(11),
    IN in_first_name varchar(255)
)
BEGIN
    INSERT INTO myDatabase.my_record
    (`group`, `package`, `type`, `uid`, `member_id`, `first_name`)
    VALUES
    (in_group, in_package, in_type, in_uid, in_member_id, in_first_name)
    ON DUPLICATE KEY UPDATE
        `group` = in_group,
        `package` = COALESCE(in_package, `package`),
        `type` = COALESCE(in_type, `type`),
        `uid` = in_uid,
        `client_member_id` = in_client_member_id,
        `first_name` = COALESCE(in_first_name, `first_name`);

    SELECT
        record_id
    FROM
        myDatabase.my_record
    WHERE
        record_id = LAST_INSERT_ID();
END
</code>```

Body:
I know an around-about way of accomplishing this but I would like to know the clean and best way to solve my problem. I am using an INSERT INTO with an ON DUPLICATE KEY UPDATE. Sometimes a value is not given but I still have to pass it into the parameter of the procedure otherwise it would fail. So I have been passing in a null value but this will update the field with nulls and I will lose data. So, I would like to "ignore" a field if it a null value gets passed into it. In other words just not update it or get the current value instead and pass that in.

I could use multiple IF statements to just check if a value is null or not but this procedure is about 20 values long and that would seem ridiculous and gratuitous. If there is a better way, I know that it can be done differently.

I'm only going to include part of my procedure for simplicity sake.

PROCEDURE `p_my_record_create`(
    IN in_group varchar(255),
    IN in_package varchar(255),
    IN in_type enum('A', 'M'),
    IN in_uid varchar(255),
    IN in_member_id int(11),
    IN in_first_name varchar(255)
)
BEGIN
    INSERT INTO myDatabase.my_record
    (`group`, `package`, `type`, `uid`, `member_id`, `first_name`)
    VALUES
    (in_group, in_package, in_type, in_uid, in_member_id, in_first_name)
    ON DUPLICATE KEY UPDATE
        `group` = in_group,
        `package` = in_package,
        `type` = in_type,  #if this is passed in as null then I would like for it to be "ignored" or if any of them are.
        `uid` = in_uid,
        `client_member_id` = in_client_member_id,
        `first_name` = in_first_name;

    SELECT
        record_id
    FROM
        myDatabase.my_record
    WHERE
        record_id = LAST_INSERT_ID();
END

If there is a simple way to accomplish this in MySQL, please enlighten me that would really help. Thanks.


问:
Integrating Multiple Codes into One Worksheet_Change
I am trying to implement multiple functions into one worksheet_change. I was able to integrate 3 functions before (all pertaining to hiding/unhiding rows), however, am having trouble adding a function that allows multiples selections within a dropdown.

I have tried to add the new multiple selection code to the previously existing code and it does not give me errors, however it wont run. In a perfect world, it would keep the hiding/unhiding functions, as well as allow for multiple selections in the identified rows.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

ActiveSheet.Activate

If Not Application.Intersect(Range("C10:AA10"), Range(Target.Address))

Is Nothing Then
    Select Case Target.Value

    Case Is = "Select One": Rows("14:58").EntireRow.Hidden = True
                         Rows("10").EntireRow.Hidden = False
    Case Is = "1": Rows("17:58").EntireRow.Hidden = True
                        Rows("14:16").EntireRow.Hidden = False
    Case Is = "2":  Rows("20:58").EntireRow.Hidden = True
                        Rows("14:19").EntireRow.Hidden = False
    Case Is = "3": Rows("23:58").EntireRow.Hidden = True
                        Rows("14:22").EntireRow.Hidden = False
    Case Is = "4":  Rows("26:58").EntireRow.Hidden = True
                        Rows("14:25").EntireRow.Hidden = False
    Case Is = "5": Rows("29:58").EntireRow.Hidden = True
                        Rows("14:28").EntireRow.Hidden = False
    Case Is = "6":  Rows("32:58").EntireRow.Hidden = True
                        Rows("14:31").EntireRow.Hidden = False
    Case Is = "7": Rows("35:58").EntireRow.Hidden = True
                        Rows("14:34").EntireRow.Hidden = False
    Case Is = "8":  Rows("38:58").EntireRow.Hidden = True
                        Rows("14:37").EntireRow.Hidden = False
    Case Is = "9": Rows("41:58").EntireRow.Hidden = True
                        Rows("14:40").EntireRow.Hidden = False
    Case Is = "10":  Rows("44:58").EntireRow.Hidden = True
                        Rows("14:43").EntireRow.Hidden = False
    Case Is = "11": Rows("47:58").EntireRow.Hidden = True
                        Rows("14:46").EntireRow.Hidden = False
    Case Is = "12":  Rows("50:58").EntireRow.Hidden = True
                        Rows("14:49").EntireRow.Hidden = False
    Case Is = "13": Rows("30:58").EntireRow.Hidden = True
                        Rows("14:52").EntireRow.Hidden = False
    Case Is = "14":  Rows("56:58").EntireRow.Hidden = True
                        Rows("14:55").EntireRow.Hidden = False
    Case Is = "15":  Rows("14:58").EntireRow.Hidden = False
End Select
End If
If Not Intersect(Range("C66:AA66"), Target) Is Nothing Then
    Select Case Target.Value
    Case "GBP", "USD", "Yuan", "EUR", "LRD", "Select One"
        Rows("67").Hidden = True
    Case "Other"
        Rows("67").Hidden = False

    End Select
End If
If Not Intersect(Range("C11:AA11"), Target) Is Nothing Then
    Select Case Target.Value
    Case "$"
        Rows("13").Hidden = True
        Rows("12").Hidden = False
    Case "%"
        Rows("13").Hidden = False
        Rows("12").Hidden = True
    Case "Select One"
        Rows("13").Hidden = True
        Rows("12").Hidden = True

    End Select
End If
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Row = "15",”18”,”21” Then
  If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
GoTo Exitsub
  Else: If Target.Value = "" Then GoTo Exitsub Else
    Application.EnableEvents = False
    Newvalue = Target.Value
    Application.Undo
    Oldvalue = Target.Value
      If Oldvalue = "" Then
        Target.Value = Newvalue
      Else
        If InStr(1, Oldvalue, Newvalue) = 0 Then
            Target.Value = Oldvalue & ", " & Newvalue
      Else:
        Target.Value = Oldvalue
      End If
    End If
  End If
End If
 Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True

End Sub
</code>```

I want this to be able to continue hiding/unhiding the given rows based upon selections, as well as allow for multi-selects from the drop downs in the rows outlined in the code. The code does not give me errors, but the multi-select does not run

答:
I think I see what you're trying to do and I hope these remarks can help your code. So a few comments...

Always use Option Explicit. No matter what example code you find on the webz, using this habit will be a big help to you in the future.

It's a BIG help to use intermediate variables in your code that makes the code self-documenting. There is no penalty for assigning interim values and objects, so use this to your advantage.

Separate logic blocks into separate subroutines or functions. This makes your code "functionally isolated" -- meaning that each block of code has a specific focus and if you need to change it, you're only changing it in one location. It also makes your code easier to read without scrolling up and down to get a sense of the overall logic.

In the case of your Worksheet_Change event code, I can reduce the logic into a much easier to understand flow:

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal target As Range)
    Dim groupsRange As Range
    Dim currencyRange As Range
    Dim valuesRange As Range
    Set groupsRange = ActiveSheet.Range("C10:AA10")
    Set currencyRange = ActiveSheet.Range("C66:AA66")
    Set valuesRange = ActiveSheet.Range("C11:AA11")

    If Not Intersect(groupsRange, target) Is Nothing Then
        ShowActiveGroups target
    ElseIf Not Intersect(currencyRange, target) Is Nothing Then
        ShowCurrency target
    ElseIf Not Intersect(valuesRange, target) Is Nothing Then
        ShowValues target
    End If

    If target.Count > 1 Then Exit Sub

    If (target.Row = 15) Or (target.Row = 18) Or (target.Row = 21) Then
        CheckMultiSelect target
    End If
End Sub
</code>```

Clearly, I may not be getting the "point" of your ranges (using "groups", "currency", "values") but you should use descriptive names that make it easier to understand WHAT and WHY the logic is working on certain sections.

The code for the Subs called in the Worksheet_Change event are placed into a separate module and all of them are tagged as Public. Each of them have similar logic and there are a few things working here.

In each of the logic blocks (i.e. in the Sub code in this case) you should go through the steps of establishing exactly which worksheet is being referenced. It's critical to always fully qualify your range references (see #5). The easiest way to do that (without very long, compound statements) is to use intermediate variables.

So in each of the "Show" routines called above I'm setting up a reference to the Worksheet of the target cell (the cell that caused the Worksheet_Change event).

```<code>Dim targetWS As Worksheet
Set targetWS = target.Parent
</code>```

Try to define constants for seemingly "random" numbers or values that have no real meaning outside the context of your worksheet.

In your case, you are referencing many different rows and hiding/unhiding them. I have no idea why. But if you could "name" the rows in your code, it could make more sense. Here are some examples I used:

```<code>Const RED_GROUP_1 As String = "14:58"
Const RED_GROUP_2 As String = "10"
Const GREEN_GROUP_1 As String = "17:58"
Const GREEN_GROUP_2 As String = "14:16"
</code>```

So the first three "Show" routines could look something like this:

```<code>Public Sub ShowActiveGroups(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    Const RED_GROUP_1 As String = "14:58"
    Const RED_GROUP_2 As String = "10"
    Const GREEN_GROUP_1 As String = "17:58"
    Const GREEN_GROUP_2 As String = "14:16"

    With targetWS
        Select Case target.Value
            Case "Select One"
                .Rows(RED_GROUP_1).EntireRow.Hidden = True
                .Rows(RED_GROUP_2).EntireRow.Hidden = False
            Case 1
                .Rows(GREEN_GROUP_1).EntireRow.Hidden = True
                .Rows(GREEN_GROUP_2).EntireRow.Hidden = False
            Case 2
                .Rows("20:58").EntireRow.Hidden = True
                .Rows("14:19").EntireRow.Hidden = False

            ' ...

            Case Else
                '--- what should we do if it's not a valid value?
        End Select
    End With
End Sub

Public Sub ShowCurrency(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    Const CURRENCY_LINE As String = "67"

    With targetWS
        Select Case target.Value
            Case "GBP", "USD", "Yuan", "EUR", "LRD", "Select One"
                .Rows(CURRENCY_LINE).EntireRow.Hidden = True
            Case "Other"
                .Rows(CURRENCY_LINE).EntireRow.Hidden = False
            Case Else
                '--- what should we do if it's not a valid value?
        End Select
    End With
End Sub

Public Sub ShowValues(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    Const MONEY_LINE As String = "13"
    Const PERCENT_LINE As String = "12"

    With targetWS
        Select Case target.Value
            Case "$"
                .Rows(MONEY_LINE).EntireRow.Hidden = True
                .Rows(PERCENT_LINE).EntireRow.Hidden = False
            Case "%"
                .Rows(MONEY_LINE).EntireRow.Hidden = False
                .Rows(PERCENT_LINE).EntireRow.Hidden = True
            Case "Select One"
                .Rows(MONEY_LINE).EntireRow.Hidden = True
                .Rows(PERCENT_LINE).EntireRow.Hidden = True
            Case Else
                '--- what should we do if it's not a valid value?
        End Select
    End With
End Sub
</code>```

Finally, I always had trouble with the data-validation/multi-select code that you found on the webz. So I'm tossing in the one I use that has a couple slight mods. This code goes in the regular code module as well.

```<code>Public Sub CheckMultiSelect(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    On Error Resume Next
    Dim dvCheck As Range
    Set dvCheck = targetWS.Cells.SpecialCells(xlCellTypeAllValidation)
    If dvCheck Is Nothing Then Exit Sub

    Application.EnableEvents = False
    '--- only allow multi-select if the cell has defined data validation
    If Not Intersect(dvCheck, target) Is Nothing Then
        Dim currentValue As String
        Dim oldValue As String
        currentValue = target.Value
        Application.Undo
        oldValue = target.Value
        If oldValue = vbNullString Then
            target.Value = currentValue
        Else
            If InStr(1, oldValue, currentValue) = 0 Then
                target.Value = oldValue & "," & currentValue
            Else
                If currentValue = vbNullString Then
                    target.Value = vbNullString
                Else
                    target.Value = oldValue
                End If
            End If
        End If
    End If
    Application.EnableEvents = True
End Sub
</code>```

Using the code above in both the worksheet module and a regular code module, I sucessfully was able to perform some of the operations in your original question.

Body:
I am trying to implement multiple functions into one worksheet_change. I was able to integrate 3 functions before (all pertaining to hiding/unhiding rows), however, am having trouble adding a function that allows multiples selections within a dropdown.

I have tried to add the new multiple selection code to the previously existing code and it does not give me errors, however it wont run. In a perfect world, it would keep the hiding/unhiding functions, as well as allow for multiple selections in the identified rows.

Private Sub Worksheet_Change(ByVal Target As Range)

ActiveSheet.Activate

If Not Application.Intersect(Range("C10:AA10"), Range(Target.Address))

Is Nothing Then
    Select Case Target.Value

    Case Is = "Select One": Rows("14:58").EntireRow.Hidden = True
                         Rows("10").EntireRow.Hidden = False
    Case Is = "1": Rows("17:58").EntireRow.Hidden = True
                        Rows("14:16").EntireRow.Hidden = False
    Case Is = "2":  Rows("20:58").EntireRow.Hidden = True
                        Rows("14:19").EntireRow.Hidden = False
    Case Is = "3": Rows("23:58").EntireRow.Hidden = True
                        Rows("14:22").EntireRow.Hidden = False
    Case Is = "4":  Rows("26:58").EntireRow.Hidden = True
                        Rows("14:25").EntireRow.Hidden = False
    Case Is = "5": Rows("29:58").EntireRow.Hidden = True
                        Rows("14:28").EntireRow.Hidden = False
    Case Is = "6":  Rows("32:58").EntireRow.Hidden = True
                        Rows("14:31").EntireRow.Hidden = False
    Case Is = "7": Rows("35:58").EntireRow.Hidden = True
                        Rows("14:34").EntireRow.Hidden = False
    Case Is = "8":  Rows("38:58").EntireRow.Hidden = True
                        Rows("14:37").EntireRow.Hidden = False
    Case Is = "9": Rows("41:58").EntireRow.Hidden = True
                        Rows("14:40").EntireRow.Hidden = False
    Case Is = "10":  Rows("44:58").EntireRow.Hidden = True
                        Rows("14:43").EntireRow.Hidden = False
    Case Is = "11": Rows("47:58").EntireRow.Hidden = True
                        Rows("14:46").EntireRow.Hidden = False
    Case Is = "12":  Rows("50:58").EntireRow.Hidden = True
                        Rows("14:49").EntireRow.Hidden = False
    Case Is = "13": Rows("30:58").EntireRow.Hidden = True
                        Rows("14:52").EntireRow.Hidden = False
    Case Is = "14":  Rows("56:58").EntireRow.Hidden = True
                        Rows("14:55").EntireRow.Hidden = False
    Case Is = "15":  Rows("14:58").EntireRow.Hidden = False
End Select
End If
If Not Intersect(Range("C66:AA66"), Target) Is Nothing Then
    Select Case Target.Value
    Case "GBP", "USD", "Yuan", "EUR", "LRD", "Select One"
        Rows("67").Hidden = True
    Case "Other"
        Rows("67").Hidden = False

    End Select
End If
If Not Intersect(Range("C11:AA11"), Target) Is Nothing Then
    Select Case Target.Value
    Case "$"
        Rows("13").Hidden = True
        Rows("12").Hidden = False
    Case "%"
        Rows("13").Hidden = False
        Rows("12").Hidden = True
    Case "Select One"
        Rows("13").Hidden = True
        Rows("12").Hidden = True

    End Select
End If
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Row = "15",”18”,”21” Then
  If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
GoTo Exitsub
  Else: If Target.Value = "" Then GoTo Exitsub Else
    Application.EnableEvents = False
    Newvalue = Target.Value
    Application.Undo
    Oldvalue = Target.Value
      If Oldvalue = "" Then
        Target.Value = Newvalue
      Else
        If InStr(1, Oldvalue, Newvalue) = 0 Then
            Target.Value = Oldvalue & ", " & Newvalue
      Else:
        Target.Value = Oldvalue
      End If
    End If
  End If
End If
 Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True

End Sub

I want this to be able to continue hiding/unhiding the given rows based upon selections, as well as allow for multi-selects from the drop downs in the rows outlined in the code. The code does not give me errors, but the multi-select does not run

Body:
I think I see what you're trying to do and I hope these remarks can help your code. So a few comments...

Always use Option Explicit. No matter what example code you find on the webz, using this habit will be a big help to you in the future.

It's a BIG help to use intermediate variables in your code that makes the code self-documenting. There is no penalty for assigning interim values and objects, so use this to your advantage.

Separate logic blocks into separate subroutines or functions. This makes your code "functionally isolated" -- meaning that each block of code has a specific focus and if you need to change it, you're only changing it in one location. It also makes your code easier to read without scrolling up and down to get a sense of the overall logic.

In the case of your Worksheet_Change event code, I can reduce the logic into a much easier to understand flow:

Option Explicit

Private Sub Worksheet_Change(ByVal target As Range)
    Dim groupsRange As Range
    Dim currencyRange As Range
    Dim valuesRange As Range
    Set groupsRange = ActiveSheet.Range("C10:AA10")
    Set currencyRange = ActiveSheet.Range("C66:AA66")
    Set valuesRange = ActiveSheet.Range("C11:AA11")

    If Not Intersect(groupsRange, target) Is Nothing Then
        ShowActiveGroups target
    ElseIf Not Intersect(currencyRange, target) Is Nothing Then
        ShowCurrency target
    ElseIf Not Intersect(valuesRange, target) Is Nothing Then
        ShowValues target
    End If

    If target.Count > 1 Then Exit Sub

    If (target.Row = 15) Or (target.Row = 18) Or (target.Row = 21) Then
        CheckMultiSelect target
    End If
End Sub

Clearly, I may not be getting the "point" of your ranges (using "groups", "currency", "values") but you should use descriptive names that make it easier to understand WHAT and WHY the logic is working on certain sections.

The code for the Subs called in the Worksheet_Change event are placed into a separate module and all of them are tagged as Public. Each of them have similar logic and there are a few things working here.

In each of the logic blocks (i.e. in the Sub code in this case) you should go through the steps of establishing exactly which worksheet is being referenced. It's critical to always fully qualify your range references (see #5). The easiest way to do that (without very long, compound statements) is to use intermediate variables.

So in each of the "Show" routines called above I'm setting up a reference to the Worksheet of the target cell (the cell that caused the Worksheet_Change event).

Dim targetWS As Worksheet
Set targetWS = target.Parent

Try to define constants for seemingly "random" numbers or values that have no real meaning outside the context of your worksheet.

In your case, you are referencing many different rows and hiding/unhiding them. I have no idea why. But if you could "name" the rows in your code, it could make more sense. Here are some examples I used:

Const RED_GROUP_1 As String = "14:58"
Const RED_GROUP_2 As String = "10"
Const GREEN_GROUP_1 As String = "17:58"
Const GREEN_GROUP_2 As String = "14:16"

So the first three "Show" routines could look something like this:

Public Sub ShowActiveGroups(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    Const RED_GROUP_1 As String = "14:58"
    Const RED_GROUP_2 As String = "10"
    Const GREEN_GROUP_1 As String = "17:58"
    Const GREEN_GROUP_2 As String = "14:16"

    With targetWS
        Select Case target.Value
            Case "Select One"
                .Rows(RED_GROUP_1).EntireRow.Hidden = True
                .Rows(RED_GROUP_2).EntireRow.Hidden = False
            Case 1
                .Rows(GREEN_GROUP_1).EntireRow.Hidden = True
                .Rows(GREEN_GROUP_2).EntireRow.Hidden = False
            Case 2
                .Rows("20:58").EntireRow.Hidden = True
                .Rows("14:19").EntireRow.Hidden = False

            ' ...

            Case Else
                '--- what should we do if it's not a valid value?
        End Select
    End With
End Sub

Public Sub ShowCurrency(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    Const CURRENCY_LINE As String = "67"

    With targetWS
        Select Case target.Value
            Case "GBP", "USD", "Yuan", "EUR", "LRD", "Select One"
                .Rows(CURRENCY_LINE).EntireRow.Hidden = True
            Case "Other"
                .Rows(CURRENCY_LINE).EntireRow.Hidden = False
            Case Else
                '--- what should we do if it's not a valid value?
        End Select
    End With
End Sub

Public Sub ShowValues(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    Const MONEY_LINE As String = "13"
    Const PERCENT_LINE As String = "12"

    With targetWS
        Select Case target.Value
            Case "$"
                .Rows(MONEY_LINE).EntireRow.Hidden = True
                .Rows(PERCENT_LINE).EntireRow.Hidden = False
            Case "%"
                .Rows(MONEY_LINE).EntireRow.Hidden = False
                .Rows(PERCENT_LINE).EntireRow.Hidden = True
            Case "Select One"
                .Rows(MONEY_LINE).EntireRow.Hidden = True
                .Rows(PERCENT_LINE).EntireRow.Hidden = True
            Case Else
                '--- what should we do if it's not a valid value?
        End Select
    End With
End Sub

Finally, I always had trouble with the data-validation/multi-select code that you found on the webz. So I'm tossing in the one I use that has a couple slight mods. This code goes in the regular code module as well.

Public Sub CheckMultiSelect(ByRef target As Range)
    Dim targetWS As Worksheet
    Set targetWS = target.Parent

    On Error Resume Next
    Dim dvCheck As Range
    Set dvCheck = targetWS.Cells.SpecialCells(xlCellTypeAllValidation)
    If dvCheck Is Nothing Then Exit Sub

    Application.EnableEvents = False
    '--- only allow multi-select if the cell has defined data validation
    If Not Intersect(dvCheck, target) Is Nothing Then
        Dim currentValue As String
        Dim oldValue As String
        currentValue = target.Value
        Application.Undo
        oldValue = target.Value
        If oldValue = vbNullString Then
            target.Value = currentValue
        Else
            If InStr(1, oldValue, currentValue) = 0 Then
                target.Value = oldValue & "," & currentValue
            Else
                If currentValue = vbNullString Then
                    target.Value = vbNullString
                Else
                    target.Value = oldValue
                End If
            End If
        End If
    End If
    Application.EnableEvents = True
End Sub

Using the code above in both the worksheet module and a regular code module, I sucessfully was able to perform some of the operations in your original question.


问:
My code wont render even after installing dependencies
Failed to compile.

./src/components/Teachers.js
Module not found: Can't resolve 'semantic-ui-react' in 'C:\Users\user\Documents\GitHub\Portfolio\Rework1\src\components'

I keep getting this error my code works but it looks like my dependencies are not loading correctly I ran some terminal commands that broke my code please help.

I have tried installing dependencies in Node_Modules folder

```<code>import React from 'react';
import TeacherList from '../data/teachers';
import {  Badge, CardHeader,CardImg, CardFooter, CardBody,
 CardText,CardColumns,CardTitle,CardSubtitle,Row,Col, } from 'reactstrap';
 import { Button, Header, Modal } from 'semantic-ui-react'

 import { Card, Icon, Image } from 'semantic-ui-react'

import Description from './Description'
const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (

<img className="teacher-img" src={teacher.img_src} alt="teacher" />
  <b className="projectTitle">{teacher.name}</b>
            <hr className="divider2 my-4"/>

          <a className="link" href={teacher.code} target="_blank"  rel="noopener noreferrer"><b> Code </b></a>
  <a  className="link code" href={teacher.live} target="_blank"  rel="noopener noreferrer"><b> Live </b></a>
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>

         </CardFooter>
</Card> */}
<Card>
    <div className="container3">
    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>
      <a>
        <Icon name='user' />
        10 Friends
      </a>
    </Card.Content>
    </div>

  </Card>

</div>

    );
  });

  return (
    <div className="main-content">
      <h2>Projects </h2>
      <ul className="group">
        {teachers}
      </ul>
    </div>
  );
}

export default Teachers;
</code>```

Package.Json

```<code>{
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

答:
In your package.json you have "semantic-ui": "some version num". You need to install the semantic-ui-react version

```<code>    {
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2" ---> needs to be "semantic-ui-react": "whatever version"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

run npm i semantic-ui-react@latest instead

Body:
Failed to compile.

./src/components/Teachers.js
Module not found: Can't resolve 'semantic-ui-react' in 'C:\Users\user\Documents\GitHub\Portfolio\Rework1\src\components'

I keep getting this error my code works but it looks like my dependencies are not loading correctly I ran some terminal commands that broke my code please help.

I have tried installing dependencies in Node_Modules folder

import React from 'react';
import TeacherList from '../data/teachers';
import {  Badge, CardHeader,CardImg, CardFooter, CardBody,
 CardText,CardColumns,CardTitle,CardSubtitle,Row,Col, } from 'reactstrap';
 import { Button, Header, Modal } from 'semantic-ui-react'

 import { Card, Icon, Image } from 'semantic-ui-react'

import Description from './Description'
const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (

  {teacher.name}

           Code
   Live
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>

         </CardFooter>
</Card> */}
<Card>

    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>

        <Icon name='user' />
        10 Friends

    </Card.Content>

  </Card>

    );
  });

  return (

Projects

        {teachers}

  );
}

export default Teachers;

Package.Json

{
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Body:
In your package.json you have "semantic-ui": "some version num". You need to install the semantic-ui-react version

    {
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2" ---> needs to be "semantic-ui-react": "whatever version"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

run npm i semantic-ui-react@latest instead


问:
Add property or modify cookie in rails
I have a cookie that is already set in the code already. I just want to add a flag {httponly: true} to it. I tried with merge method but I get error saying that merge can not be applied to string. Then I tried with this  cookies[:riko_added_http_only] << '; HttpOnly', but I see in the browser cookies that the cookie is not httponly.

So the question is how to add/modify cookie property or flag(as httponly or secure) after some value is already assigned to it?

Here is some exampe:

```<code>    cookies[:riko_added_http_only] = {
      value: 'rikob',
    }
    ........ Some code here ....................
    cookies[:riko_added_http_only] << '; HttpOnly'
</code>```

EDIT:

Let me add some more information and test examples:

From this code:

```<code>    cookies[:secure_true_http_true] = {
      value: 'httpOnly, not Secure',
      httponly: true,
      secure: true
    }
    cookies[:secure_true_http_false] = {
      value: 'Secure NOT HttpOnly',
      httponly: false,
      secure: true
    }
    cookies[:secure_false_http_true] = {
      value: 'Secure and http only',
      httponly: true,
      secure: false
    }

    cookies[:riko_added_http_only] = {
      value: 'rikob',
    }

    cookies[:riko_added_http_only] = {
      value: "#{cookies[:riko_added_http_only]}; HttpOnly"
    }
</code>```

I get this result:

答:
You can update the cookie value in this way:</p>

```<code>cookies[:riko_added_http_only]= {
  value: "#{cookies[:riko_added_http_only]} ; HttpOnly"
}
</code>```

Title: Add property or modify cookie in rails

Body:
I have a cookie that is already set in the code already. I just want to add a flag {httponly: true} to it. I tried with merge method but I get error saying that merge can not be applied to string. Then I tried with this  cookies[:riko_added_http_only] << '; HttpOnly', but I see in the browser cookies that the cookie is not httponly.

So the question is how to add/modify cookie property or flag(as httponly or secure) after some value is already assigned to it?

Here is some exampe:

    cookies[:riko_added_http_only] = {
      value: 'rikob',
    }
    ........ Some code here ....................
    cookies[:riko_added_http_only] << '; HttpOnly'

EDIT:

Let me add some more information and test examples:

From this code:

    cookies[:secure_true_http_true] = {
      value: 'httpOnly, not Secure',
      httponly: true,
      secure: true
    }
    cookies[:secure_true_http_false] = {
      value: 'Secure NOT HttpOnly',
      httponly: false,
      secure: true
    }
    cookies[:secure_false_http_true] = {
      value: 'Secure and http only',
      httponly: true,
      secure: false
    }

    cookies[:riko_added_http_only] = {
      value: 'rikob',
    }

    cookies[:riko_added_http_only] = {
      value: "#{cookies[:riko_added_http_only]}; HttpOnly"
    }

I get this result:

Body:
You can update the cookie value in this way:

cookies[:riko_added_http_only]= {
  value: "#{cookies[:riko_added_http_only]} ; HttpOnly"
}


问:
Problem transmitting date over the network
I have an MVC application that sends a date value from a server in USA as JSON format and it is displayed in a PC in Chile.

Server side has this action in controller:

```<code>   public async Task<ActionResult> GetFacturas(Models.DataTableAjaxPostModel model)
    {
        // Some other code in between
        // ----
        return Json(fecha);   // fecha has the value of 2019-04-16 00:00:00
    }
</code>```

By using  Chrome development tool, I see that the date is received in JSON object as 1555383600000.

By using the site https://www.epochconverter.com/ I translated that date to a human readable format and I saw that it is:

```<code>GMT: Tuesday, 16 April 2019 3:00:00
Your time zone: Monday, 15 April 2019 23:00:00 GMT-04:00
</code>```

Even when MVC controller got date as 2019-04-16 00:00:00, it seems when Json serialized it, it was converted to GMT using -3 time zone, so, finally that GMT date was received by client computer, which in turn converted the date back to local time applying -4 operation.

Operating system is configured as Time Zone -4, and MVC application is configured this way in web.config file:

```<code><globalization culture="es-CL" uiCulture="es-CL" />
</code>```

How can I avoid this problem?

EDIT:

"fecha" variable is a DateTime object returned from a database, this way:

```<code>var fecha = db.Entity.Select(f => f.DatetimeField).FirstOrDefault();
</code>```

Of course I simplified the query, but the fact is that "fecha", before returning the function, is a DateTime object whose value is 2019-04-16 00:00:00.

Regards

Jaime

答:
I assume that the value in your JSON looks something like "/Date(1555383600000)/", which is the older JSON date format.  With this format, the local time zone of the server is applied when the .Kind property of the DateTime value is either DateTimeKind.Local or DateTimeKind.Unspecified.

Even if the value stored in your database is in UTC, there's no way for EF to know that, so it is being set as unspecified.  You can set it yourself with:

```<code>fetcha = DateTime.SpecifyKind(fetch, DateTimeKind.Utc);
</code>```

Now you'll find that the value gets serialized as "/Date(1555372800000)/".

Current versions of ASP.Net and Newtonsoft.Json use the ISO 8601 format instead.  Without any changes to your code, your values are serialized based on the .Kind property as follows:

With DateTimeKind.Unspecified, as"2019-04-16T00:00:00.0000000"`

With DateTimeKind.Utc, as  "2019-04-16T00:00:00.0000000Z"

With DateTimeKind.Local, as "2019-04-16T00:00:00.0000000-03:00" (using the server's tz offset)

You can switch between the two formats using the DateFormatHandling setting, but I recommend leaving it at the default of IsoDateFormat.  See also Serializing Dates in JSON.

Client-side deserialization is also a factor.  If you are handed a timestamp (with the old format), then that timestamp is aligned to UTC.  If you are handed a string (with the new format), the timestamp is influenced by the offset in the string, or by the local browser time zone if there is no offset provided.  Additionally, the Date object in JavaScript has many functions that can only use the browser's local time zone.

All things considered, it can be very difficult to get a date-only value to serialize end-to-end without being affected by time zone in some way.  You can try the above approaches, but if indeed you just want to save, restore, display and transmit the same date-only value, then you might also just consider sending a string without the time, as in "2019-04-16":

```<code>return Json(fetch.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture"));
</code>```

Body:
I have an MVC application that sends a date value from a server in USA as JSON format and it is displayed in a PC in Chile.

Server side has this action in controller:

   public async Task<ActionResult> GetFacturas(Models.DataTableAjaxPostModel model)
    {
        // Some other code in between
        // ----
        return Json(fecha);   // fecha has the value of 2019-04-16 00:00:00
    }

By using  Chrome development tool, I see that the date is received in JSON object as 1555383600000.

By using the site https://www.epochconverter.com/ I translated that date to a human readable format and I saw that it is:

GMT: Tuesday, 16 April 2019 3:00:00
Your time zone: Monday, 15 April 2019 23:00:00 GMT-04:00

Even when MVC controller got date as 2019-04-16 00:00:00, it seems when Json serialized it, it was converted to GMT using -3 time zone, so, finally that GMT date was received by client computer, which in turn converted the date back to local time applying -4 operation.

Operating system is configured as Time Zone -4, and MVC application is configured this way in web.config file:

<globalization culture="es-CL" uiCulture="es-CL" />

How can I avoid this problem?

EDIT:

"fecha" variable is a DateTime object returned from a database, this way:

var fecha = db.Entity.Select(f => f.DatetimeField).FirstOrDefault();

Of course I simplified the query, but the fact is that "fecha", before returning the function, is a DateTime object whose value is 2019-04-16 00:00:00.

Regards

Jaime

Body:
I assume that the value in your JSON looks something like "/Date(1555383600000)/", which is the older JSON date format.  With this format, the local time zone of the server is applied when the .Kind property of the DateTime value is either DateTimeKind.Local or DateTimeKind.Unspecified.

Even if the value stored in your database is in UTC, there's no way for EF to know that, so it is being set as unspecified.  You can set it yourself with:

fetcha = DateTime.SpecifyKind(fetch, DateTimeKind.Utc);

Now you'll find that the value gets serialized as "/Date(1555372800000)/".

Current versions of ASP.Net and Newtonsoft.Json use the ISO 8601 format instead.  Without any changes to your code, your values are serialized based on the .Kind property as follows:

With DateTimeKind.Unspecified, as"2019-04-16T00:00:00.0000000"`

With DateTimeKind.Utc, as  "2019-04-16T00:00:00.0000000Z"

With DateTimeKind.Local, as "2019-04-16T00:00:00.0000000-03:00" (using the server's tz offset)

You can switch between the two formats using the DateFormatHandling setting, but I recommend leaving it at the default of IsoDateFormat.  See also Serializing Dates in JSON.

Client-side deserialization is also a factor.  If you are handed a timestamp (with the old format), then that timestamp is aligned to UTC.  If you are handed a string (with the new format), the timestamp is influenced by the offset in the string, or by the local browser time zone if there is no offset provided.  Additionally, the Date object in JavaScript has many functions that can only use the browser's local time zone.

All things considered, it can be very difficult to get a date-only value to serialize end-to-end without being affected by time zone in some way.  You can try the above approaches, but if indeed you just want to save, restore, display and transmit the same date-only value, then you might also just consider sending a string without the time, as in "2019-04-16":

return Json(fetch.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture"));


问:
Change package name for Android in React Native
I used react-native init MyApp to initialise a new React Native app.
This created among others an Android project with the package com.myapp.

What's the best way to change this package name, for example to: com.mycompany.myapp?

I tried changing it in AndroidManifest.xml but it created other errors, so I'm assuming it's not the way.

Any idea?

答:
Go to Android Studio, open app, right click on java and choose
New and then Package.

Give the name you want (e.g. com.something).

Move the files from the other package (you want to rename) to the new Package. Delete the old package.

Go to your project in your editor and use the shortcut for searching in all the files (on mac is shift cmd F). Type in the name of your old package. Change all the references to the new package name.

Go to Android Studio, Build, Clean Project, Rebuild Project.

Done!

Happy coding :)

ContentLicense: CC BY-SA 3.0


问:
Unable to connect to the remote server from Asp.Net MVC
I'm trying to get the data from external website using webclient inside my Asp.Net MVC application. I'm using the following code to get the text.

```<code>using (WebClient client = new WebClient())
{
      string htmlCode = client.DownloadString("http://google.com");
}
</code>```

But, I'm getting The operation has timed out exception.

If I use the same code within WPF App or WinForms App, its working perfectly. Is there any configuration I'm missing in my Web Application?

note:
I have tried using WebRequest class and no success with that too.

答:
Old question but the answer for future generations might be that you need to use a web proxy. Something like this:</p>

```<code>WebClient client = new WebClient();
WebProxy proxyObject = new WebProxy("http://yourproxy.something:1234/", true);
client.Proxy = proxyObject;
</code>```

Body:
I'm trying to get the data from external website using webclient inside my Asp.Net MVC application. I'm using the following code to get the text.

using (WebClient client = new WebClient())
{
      string htmlCode = client.DownloadString("http://google.com");
}

But, I'm getting The operation has timed out exception.

If I use the same code within WPF App or WinForms App, its working perfectly. Is there any configuration I'm missing in my Web Application?

note:
I have tried using WebRequest class and no success with that too.

Body:
Old question but the answer for future generations might be that you need to use a web proxy. Something like this:

WebClient client = new WebClient();
WebProxy proxyObject = new WebProxy("http://yourproxy.something:1234/", true);
client.Proxy = proxyObject;


问:
How to send email if cell date equals today
I am trying to create a Google Apps Script that works with a spreadsheet to send out an email if certain criteria is met. Specifically to send out an email if Column C equals today & column A equals false.

Link to the spreadsheet:
https://docs.google.com/spreadsheets/d/1kULWOMtZaay6PcgF5XTwVoJnKPo7JSA_AK50J8RNYzk/edit?usp=sharing

I was able to set this up to that the spreadsheet handles most of the work. Column D checks for the date, and that column A is checked and then the script will send when column D reads TRUE. I am wondering if I can have the Google Apps Script check for today's date, instead of the spreadsheet.

```<code>function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 50;   // Number of rows to process
  var numOfColumns = sheet.getLastColumn();

  // Fetch the range of cells
  var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();

  var sendTrigger = "";

  var i = 0;
  for (i=0;i<data.length;i++) {
    var row = data[i];
    var emailAddress = row[4];  // fifth column
    var message = row[5];       // sixth column

    sendTrigger = row[3];

    if (sendTrigger == 1) {
      var subject = ("This is a test of the send email function");
      MailApp.sendEmail(emailAddress, subject, message);
    };
  };
};
</code>```

I want the script to check column A and column C and send out an email if Column A equals FALSE and column C equals TODAY

答:
Try this:</p>

```<code>function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 50;   // Number of rows to process
  var numOfColumns = sheet.getLastColumn();
  var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
  var data = dataRange.getValues();
  var sendTrigger = "";
  var dt=new Date();
  var dv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
  for (var i=0;i<data.length;i++) {
    var row = data[i];
    var emailAddress = row[4];  // fifth column
    var message = row[5];       // sixth column
    var d=new Date(row[2]);
    if (!row[0] && new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf()==dv) {
      var subject = ("This is a test of the send email function");
      MailApp.sendEmail(emailAddress, subject, message);
    }
  }
}
</code>```

Body:
I am trying to create a Google Apps Script that works with a spreadsheet to send out an email if certain criteria is met. Specifically to send out an email if Column C equals today & column A equals false.

Link to the spreadsheet:
https://docs.google.com/spreadsheets/d/1kULWOMtZaay6PcgF5XTwVoJnKPo7JSA_AK50J8RNYzk/edit?usp=sharing

I was able to set this up to that the spreadsheet handles most of the work. Column D checks for the date, and that column A is checked and then the script will send when column D reads TRUE. I am wondering if I can have the Google Apps Script check for today's date, instead of the spreadsheet.

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 50;   // Number of rows to process
  var numOfColumns = sheet.getLastColumn();

  // Fetch the range of cells
  var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();

  var sendTrigger = "";

  var i = 0;
  for (i=0;i<data.length;i++) {
    var row = data[i];
    var emailAddress = row[4];  // fifth column
    var message = row[5];       // sixth column

    sendTrigger = row[3];

    if (sendTrigger == 1) {
      var subject = ("This is a test of the send email function");
      MailApp.sendEmail(emailAddress, subject, message);
    };
  };
};

I want the script to check column A and column C and send out an email if Column A equals FALSE and column C equals TODAY

Body:
Try this:

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 50;   // Number of rows to process
  var numOfColumns = sheet.getLastColumn();
  var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
  var data = dataRange.getValues();
  var sendTrigger = "";
  var dt=new Date();
  var dv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
  for (var i=0;i<data.length;i++) {
    var row = data[i];
    var emailAddress = row[4];  // fifth column
    var message = row[5];       // sixth column
    var d=new Date(row[2]);
    if (!row[0] && new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf()==dv) {
      var subject = ("This is a test of the send email function");
      MailApp.sendEmail(emailAddress, subject, message);
    }
  }
}


问:
Stack gifs with FFmpeg without loss of quality
I have two animated gifs of the same duration and size that I am trying to stack vertically with ffmpeg:

```<code>ffmpeg input_1.gif -i input_2.gif -filter_complex vstack -q:v 1 output.gif
</code>```

The problem is that resulting gif experience quite some loss of quality. Furthermore, it seems that option -q:v has no effect at all, regardless of supplied value and (valid) positioning within command.

Does anybody know a way to overcome it?

答:
Use the vstack, split, palettegen, and paletteuse filters:</p>

```<code>ffmpeg input_1.gif -i input_2.gif -filter_complex "[0][1]vstack=inputs=2,split[y][z];[y]palettegen[pal];[z][pal]paletteuse" output.gif
</code>```

Body:
I have two animated gifs of the same duration and size that I am trying to stack vertically with ffmpeg:

ffmpeg input_1.gif -i input_2.gif -filter_complex vstack -q:v 1 output.gif

The problem is that resulting gif experience quite some loss of quality. Furthermore, it seems that option -q:v has no effect at all, regardless of supplied value and (valid) positioning within command.

Does anybody know a way to overcome it?

Body:
Use the vstack, split, palettegen, and paletteuse filters:

ffmpeg input_1.gif -i input_2.gif -filter_complex "[0][1]vstack=inputs=2,split[y][z];[y]palettegen[pal];[z][pal]paletteuse" output.gif


问:
fromEvent from rxjs is not working as expected
I have created a component with a search functionality which calls api and displays data over the page. Once I get the search result, I store them in localStorage to restore the data once you navigate back to the same search component page. Everything is working fine until I assign the stored data back to the formEvent observable result property this.searchResult$ . The issue is fromEvent doesn't trigger any more once I return to the same page via other routes. </p>

```<code>  ngOnInit() {
 const searchEvent$ = fromEvent<any>(this.inputSearch.nativeElement, 'keyup').pipe(tap(() => { console.log('working'); }));
    this.searchResult$ = searchEvent$
      .pipe(
        tap(() => { this.isDataOn = true }),
        map(event => event.target.value),
        filter(value => value ? true : false),
        switchMap(search => this.notesService.onSearchNotes(search)))
      )
 if (!this.isDataOn) {
      this.refreshData()
    }
}
refreshData() {
    if (localStorage.getItem("queryStack")) {
      const data = JSON.parse(localStorage.getItem("queryStack") || "[]");
      console.log(data);
      this.searchResult$ = of(data);
    }
  }
</code>```

答:
Try the following approach, which merges in whatever saved data you have in local storage with the results fetched from the server in response to keyup events.</p>

```<code>// in your imports
import { merge } from 'rxjs';

ngOnInit() {
    const searchEvent$ = fromEvent<any>(this.inputSearch.nativeElement, 'keyup').pipe(tap(() => { console.log('working'); }));
    this.searchResult$ = merge(
        of(this.getSavedData()),
        searchEvent$
            .pipe(
                map(event => event.target.value),
                filter(Boolean),
                debounceTime(1000),
                distinctUntilChanged(),
                switchMap(search => this.notesService.onSearchNotes(search))
            )
    );
}
getSavedData() {
    const localStorageValue = localStorage.getItem("queryStack") || "[]";
    try {
        return JSON.parse(localStorageValue);
    } catch (ex) {
        console.error('Error parsing JSON:', ex);
        return [];
    }
}
</code>```

Body:
I have created a component with a search functionality which calls api and displays data over the page. Once I get the search result, I store them in localStorage to restore the data once you navigate back to the same search component page. Everything is working fine until I assign the stored data back to the formEvent observable result property this.searchResult$ . The issue is fromEvent doesn't trigger any more once I return to the same page via other routes.

  ngOnInit() {
 const searchEvent$ = fromEvent<any>(this.inputSearch.nativeElement, 'keyup').pipe(tap(() => { console.log('working'); }));
    this.searchResult$ = searchEvent$
      .pipe(
        tap(() => { this.isDataOn = true }),
        map(event => event.target.value),
        filter(value => value ? true : false),
        switchMap(search => this.notesService.onSearchNotes(search)))
      )
 if (!this.isDataOn) {
      this.refreshData()
    }
}
refreshData() {
    if (localStorage.getItem("queryStack")) {
      const data = JSON.parse(localStorage.getItem("queryStack") || "[]");
      console.log(data);
      this.searchResult$ = of(data);
    }
  }

Body:
Try the following approach, which merges in whatever saved data you have in local storage with the results fetched from the server in response to keyup events.

// in your imports
import { merge } from 'rxjs';

ngOnInit() {
    const searchEvent$ = fromEvent<any>(this.inputSearch.nativeElement, 'keyup').pipe(tap(() => { console.log('working'); }));
    this.searchResult$ = merge(
        of(this.getSavedData()),
        searchEvent$
            .pipe(
                map(event => event.target.value),
                filter(Boolean),
                debounceTime(1000),
                distinctUntilChanged(),
                switchMap(search => this.notesService.onSearchNotes(search))
            )
    );
}
getSavedData() {
    const localStorageValue = localStorage.getItem("queryStack") || "[]";
    try {
        return JSON.parse(localStorageValue);
    } catch (ex) {
        console.error('Error parsing JSON:', ex);
        return [];
    }
}


问:
running a .py file from another Python script using os
Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.

How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks

```<code>import os

os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')
</code>```

答:
You can get the directory of the app.py file by using the following call in app.py

```<code>dir_path = os.path.dirname(os.path.realpath(__file__))
</code>```

then join the file name you want

```<code>file_path = os.path.join(dir_path,'plot.py')
</code>```

Finally your system call

```<code>os.system(f'py {file_path}') # if you're on 3.6 and above.
os.system('py %s' % file_path) # 3.5 and below
</code>```

As others have said sub-processes and multi-threading may be better, but for your specific question this is what you want.

Body:
Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.

How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks

import os

os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')

Body:
You can get the directory of the app.py file by using the following call in app.py

dir_path = os.path.dirname(os.path.realpath(__file__))

then join the file name you want

file_path = os.path.join(dir_path,'plot.py')

Finally your system call

os.system(f'py {file_path}') # if you're on 3.6 and above.
os.system('py %s' % file_path) # 3.5 and below

As others have said sub-processes and multi-threading may be better, but for your specific question this is what you want.


问:
postgres npgsql with c# - trying to write special characters to an ascii encoded database
I am using the open source library npgsql http://pgfoundry.org/projects/npgsql/ to manipulate third party data on a postgres database.  The database is encoded SQL_ASCII.

If I run a query using a standard c# string like

INSERT INTO CITIES(cityname) values("Köln")

the value that shows up in the database looks more like: пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ

e.g. scrambled.  I've spent many hours trying to use different string encodings etc with no success

答:
SQL_ASCII means you turn off the encoding functionality in the database. Thus it's up to you to make sure all your clients use the same encoding. I believe npgsql will always use UTF8, and that this cannot be changed.

So there is no "the value that shows up in the database" - it will be depending on what encoding the client that talks to the database is in.

The best way to fix it is to set an actual encoding in the database, and set it to something useful - such as UTF8 or LATIN1.


问:
Tmux will not stop auto-renaming windows
A problem I have with Tmux - in the .tmux.conf file I have told him not to rename windows after I set their names but it seems that it is not "respecting my authority" :).

My system:

OSX El Capitan

Tmux 2.1 (installed via Brew)

Zshell

Here is my ~/.tmux.conf content (I apologise it's quite long):

```<code># set correct term
set -g default-terminal screen-256color

# set prefix key to ctrl+a
#unbind C-b
set -g prefix C-a

# reload config without killing server
bind R source-file /users/edchigliak/.tmux.conf

# enable wm window titles
set -g set-titles on

# disable auto renaming
set -g automatic-rename off

# border colour
set -g pane-border-fg blue
set -g pane-border-bg default
set -g pane-active-border-fg blue
set -g pane-active-border-bg default

# wm window title string (uses statusbar variables)
set -g set-titles-string "tmux:#I [ #W ]"

# initialize sessions
bind S source-file ~/.tmux.conf
bind I source-file ~/.tmux.conf

# environment
set -g update-environment "DISPLAY SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY"

# statusbar --------------------------------------------------------------
set -g window-status-format "#I:#W"
set -g window-status-current-format "#I:#W"

set -g status-keys vi
bind-key -t vi-edit Up history-up
bind-key -t vi-edit Down history-down

set -g status-interval 1
set -g status-justify centre # center align window list

# default statusbar colors
# wm window title string (uses statusbar variables)
set -g set-titles-string "tmux:#I [ #W ]"

# initialize sessions
bind S source-file ~/.tmux.conf
bind I source-file ~/.tmux.conf

# environment
set -g update-environment "DISPLAY SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY"

# statusbar --------------------------------------------------------------
set -g window-status-format "#I:#W"
set -g window-status-current-format "#I:#W"

set -g status-keys vi
bind-key -t vi-edit Up history-up
bind-key -t vi-edit Down history-down

set -g status-interval 1
set -g status-justify centre # center align window list

# default statusbar colors
set -g status-fg white
set -g status-bg default

# default window title colors
set-window-option -g window-status-fg black
set-window-option -g window-status-bg default
set-window-option -g window-status-attr dim

# active window title colors
set-window-option -g window-status-current-fg white
set-window-option -g window-status-current-bg default
set-window-option -g window-status-current-attr dim

# command/message line colors
set -g message-fg white
set -g message-bg black
set -g message-attr bright

# Statusbar starting in X or not
# if '[ -n "$DISPLAY" ]' 'source-file ~/.tmux/inx'
# if '[ -z "$DISPLAY" ]' 'source-file ~/.tmux/xless'
</code>```

If I try:

~ > echo $TERM

I get the correct:

screen-256color

which makes me believe that it is sourcing the right .conf file. Also, control key bindings DO change from Ctrl+b to Ctrl+a. However, window names that I change via Ctrl + a and then ,simply will not stay put.

Any ideas what is going on? Thanks!

答: For people running bash and landing on this result, the thing that sets the title is the PROMPT_COMMAND environmental variable, which some shared system annoyingly set. You can do that with unset PROMPT_COMMAND (e.g. in your .bashrc)

Body:
A problem I have with Tmux - in the .tmux.conf file I have told him not to rename windows after I set their names but it seems that it is not "respecting my authority" :).

My system:

OSX El Capitan

Tmux 2.1 (installed via Brew)

Zshell

Here is my ~/.tmux.conf content (I apologise it's quite long):

# set correct term
set -g default-terminal screen-256color

# set prefix key to ctrl+a
#unbind C-b
set -g prefix C-a

# reload config without killing server
bind R source-file /users/edchigliak/.tmux.conf

# enable wm window titles
set -g set-titles on

# disable auto renaming
set -g automatic-rename off

# border colour
set -g pane-border-fg blue
set -g pane-border-bg default
set -g pane-active-border-fg blue
set -g pane-active-border-bg default

# wm window title string (uses statusbar variables)
set -g set-titles-string "tmux:#I [ #W ]"

# initialize sessions
bind S source-file ~/.tmux.conf
bind I source-file ~/.tmux.conf

# environment
set -g update-environment "DISPLAY SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY"

# statusbar --------------------------------------------------------------
set -g window-status-format "#I:#W"
set -g window-status-current-format "#I:#W"

set -g status-keys vi
bind-key -t vi-edit Up history-up
bind-key -t vi-edit Down history-down

set -g status-interval 1
set -g status-justify centre # center align window list

# default statusbar colors
# wm window title string (uses statusbar variables)
set -g set-titles-string "tmux:#I [ #W ]"

# initialize sessions
bind S source-file ~/.tmux.conf
bind I source-file ~/.tmux.conf

# environment
set -g update-environment "DISPLAY SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY"

# statusbar --------------------------------------------------------------
set -g window-status-format "#I:#W"
set -g window-status-current-format "#I:#W"

set -g status-keys vi
bind-key -t vi-edit Up history-up
bind-key -t vi-edit Down history-down

set -g status-interval 1
set -g status-justify centre # center align window list

# default statusbar colors
set -g status-fg white
set -g status-bg default

# default window title colors
set-window-option -g window-status-fg black
set-window-option -g window-status-bg default
set-window-option -g window-status-attr dim

# active window title colors
set-window-option -g window-status-current-fg white
set-window-option -g window-status-current-bg default
set-window-option -g window-status-current-attr dim

# command/message line colors
set -g message-fg white
set -g message-bg black
set -g message-attr bright

# Statusbar starting in X or not
# if '[ -n "$DISPLAY" ]' 'source-file ~/.tmux/inx'
# if '[ -z "$DISPLAY" ]' 'source-file ~/.tmux/xless'

If I try:

~ > echo $TERM

I get the correct:

screen-256color

which makes me believe that it is sourcing the right .conf file. Also, control key bindings DO change from Ctrl+b to Ctrl+a. However, window names that I change via Ctrl + a and then ,simply will not stay put.

Any ideas what is going on? Thanks!


问:
How to select the top 3 values from a group based on date and exclude duplicate value?
If I three columns and 1 column has ID, 1 column has value and 1 column has date.  Example, ID column has ID1, ID2, ID3.  The value for each ID has a numeric value, say 1,2,3,4,5 for each ID.

How do I only get 3 results for each ID based on the most recent date descending.
I am using Sybase SQL.   Is there any way I can write this?

I tried to use Row_number() and rank() but I don't get to use either of those functions with my SQL tool.

```<code>ID  value   Date
1   3   20190511
1   1   20190503
1   5   20190401
2   2   20190520
2   1   20190514
2   4   20190503
3   1   20190516
3   5   20190415
3   3   20190402
</code>```

答:
If you don't have row_number try this

```<code>SELECT *
FROM yourTable t1
WHERE (SELECT COUNT(*)
       FROM yourTable t2
       WHERE t1.id = t2.id
         AND t1.date < t2.date) < 3
</code>```

So if one id have 3 or more older rows wont appear.

with row_number

```<code>SELECT *
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) as rn
      FROM YourTable t1
     ) as t
WHERE t.rn <= 3
</code>```

I assume you cant have multiple rows in same date. In that case you may want use RANK() or DENSE_RANK() and decide how handle ties.

Body:
If I three columns and 1 column has ID, 1 column has value and 1 column has date.  Example, ID column has ID1, ID2, ID3.  The value for each ID has a numeric value, say 1,2,3,4,5 for each ID.

How do I only get 3 results for each ID based on the most recent date descending.
I am using Sybase SQL.   Is there any way I can write this?

I tried to use Row_number() and rank() but I don't get to use either of those functions with my SQL tool.

ID  value   Date
1   3   20190511
1   1   20190503
1   5   20190401
2   2   20190520
2   1   20190514
2   4   20190503
3   1   20190516
3   5   20190415
3   3   20190402

Body:
If you don't have row_number try this

SELECT *
FROM yourTable t1
WHERE (SELECT COUNT(*)
       FROM yourTable t2
       WHERE t1.id = t2.id
         AND t1.date < t2.date) < 3

So if one id have 3 or more older rows wont appear.

with row_number

SELECT *
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) as rn
      FROM YourTable t1
     ) as t
WHERE t.rn <= 3

I assume you cant have multiple rows in same date. In that case you may want use RANK() or DENSE_RANK() and decide how handle ties.


问:
How to get a specific row for testing and other for training?
I want to test a specific row from my dataset and to see the result, but I don't know how to do it. For example I want to test row number 100 and then to see the accuracy.</p>

```<code>feature_cols = [0,1,2,3,4,5]
X = df[feature_cols] # Features
y = df[6] # Target variable

# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1,
                                                    random_state=1)

#Create Decision Tree classifer object
clf = DecisionTreeClassifier(max_depth=5)

#Train Decision Tree Classifer
clf = clf.fit(X_train,y_train)

#Predict the response for test dataset
y_pred = clf.predict(X_test)

print("Accuracy:", metrics.accuracy_score(y_test, y_pred))
</code>```

答:
I recommend excluding the row you want to test from the dataset.

```<code>test_row=100
train_idx=np.arange(X.shape[0])!=test_row
test_idx=np.arange(X.shape[0])==test_row
X_train=X[train_idx]
y_train=y[train_idx]
X_test=X[test_idx]
y_test=y[test_idx]
</code>```

Now X_test will contain a single row. However, the accuracy will now be either 0 or 1 since you are only testing one sample.

Body:
I want to test a specific row from my dataset and to see the result, but I don't know how to do it. For example I want to test row number 100 and then to see the accuracy.

feature_cols = [0,1,2,3,4,5]
X = df[feature_cols] # Features
y = df[6] # Target variable

# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1,
                                                    random_state=1)

#Create Decision Tree classifer object
clf = DecisionTreeClassifier(max_depth=5)

#Train Decision Tree Classifer
clf = clf.fit(X_train,y_train)

#Predict the response for test dataset
y_pred = clf.predict(X_test)

print("Accuracy:", metrics.accuracy_score(y_test, y_pred))

Body:
I recommend excluding the row you want to test from the dataset.

test_row=100
train_idx=np.arange(X.shape[0])!=test_row
test_idx=np.arange(X.shape[0])==test_row
X_train=X[train_idx]
y_train=y[train_idx]
X_test=X[test_idx]
y_test=y[test_idx]

Now X_test will contain a single row. However, the accuracy will now be either 0 or 1 since you are only testing one sample.


问:
Is it safe to use HashSet as a very simple cache in a multi-threaded environment?
I realize there are similar questions/answers to this, but I can't seem to find exactly what I'm looking for.

I'm looking to implement an in-memory cache that caches the result of a call to the DB, which is doing an existence check.  This existence check is quite expensive and once the object exists in the DB it will never be removed, so a very simple cache in-memory (in-process even) is all I need.  Once the DB call is made the process remembers the result of the existence check for that ID and shouldn't call the DB again.

(Maybe another thing to mention is if the object doesn't exist in the DB, it will be created).

I'm using a HashSet (java) for this and just adding the ID to the set when the check/create is done, however this is a highly concurrent environment and I am unsure about the implications of HashSet's lack-of-threadsafeness.

The code only ever uses the add() and contains() methods (no iteration).

I don't really care about a cache miss (and a resulting extra DB call) here and there, but what I'm wondering is if this pattern of add() and contains() being called on the set in concurrent threads could lead to more catastrophic errors.

答:
No. If you want to use a Map in a multithreaded environment, use Collections.synchronizedMap(<map object>) or ConcurrentHashMap.newKeySet();:

Set<String> concurrentSet = Collections.synchronizedSet(new HashSet<>());
```

<p>or...</p>

<pre class="lang-java prettyprint-override"><code>Set<String> concurrentSet = ConcurrentHashMap.newKeySet();
</code>```

Body:
No. If you want to use a Map in a multithreaded environment, use Collections.synchronizedMap(<map object>) or ConcurrentHashMap.newKeySet();:

Set<String> concurrentSet = Collections.synchronizedSet(new HashSet<>());

or...

Set<String> concurrentSet = ConcurrentHashMap.newKeySet();


问:
fetching two type of json files with different beginning of structure
I'm processing json file with php with little difference in the beginning of the file ,my problem now is that i built two foreach loops and i am looking for a way to make it one loop.

```<code>{"code":0,"rid":"0","data":{"subid":"9174906486819979969","data":{"more":

{"code":0,"rid":"0","data":{"9174906486819979969":{"more":
</code>```

Now I'm doing like that and it double the code for processing , the rest of the json file is all the same.

```<code>foreach($json['data']['data'])
{

}

foreach($json['data'])
{

}
</code>```

What i need is one foreach loop instead of 2, is that possible?

答:
You can check for the key and if present use it, if not then get the first key:

```<code>if(isset($json['data']['data'])) {
    $data = $json['data']['data'];
} else {
    $data = reset($json['data']); //or current()
}
</code>```

Or shorter:

```<code>$data = $json['data']['data'] ?? reset($json['data']);
</code>```

Then:

```<code>foreach($data as $values) {
    //code
}
</code>```

Another option would be to loop and check for an array, depending on the structure you have:

```<code>foreach($json['data'] as $values) {
    if(is_array($values)) {
        foreach($values as $v) {
            //code
        }
}
</code>```

Body:
I'm processing json file with php with little difference in the beginning of the file ,my problem now is that i built two foreach loops and i am looking for a way to make it one loop.

{"code":0,"rid":"0","data":{"subid":"9174906486819979969","data":{"more":

{"code":0,"rid":"0","data":{"9174906486819979969":{"more":

Now I'm doing like that and it double the code for processing , the rest of the json file is all the same.

foreach($json['data']['data'])
{

}

foreach($json['data'])
{

}

What i need is one foreach loop instead of 2, is that possible?

Body:
You can check for the key and if present use it, if not then get the first key:

if(isset($json['data']['data'])) {
    $data = $json['data']['data'];
} else {
    $data = reset($json['data']); //or current()
}

Or shorter:

$data = $json['data']['data'] ?? reset($json['data']);

Then:

foreach($data as $values) {
    //code
}

Another option would be to loop and check for an array, depending on the structure you have:

foreach($json['data'] as $values) {
    if(is_array($values)) {
        foreach($values as $v) {
            //code
        }
}


问:
How can I use @around spring aop annotation on method declaration?
How can I use @around spring AOP annotation on method declaration? actually there are lots of duplicate code in the java class so I am thinking to optimize it.Only the @around execution values are getting changed every time  and method definition is same for 3-4 methods.Can you please suggest what I can do in this case for code optimization?Here in the given example you can see nicdStatus and nicdPortStatus are only getting changed and rest all the method definition is same.
            Please provide some suggestion for code optimization because I have duplicate code in my java class.

@Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
}

@Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
}
```

答:
AOP means you want to intercept some logic. While with @around , you are ready to put the some logic before and after some your method. That's good way to remove duplicate code.

What you need to do:

1) find all the methods with duplicate code.

2) abstract those duplicate code into some methods.

3) config with right pointcut.

here have more example. Hope can help.