问:
How can I create binary label from two tables
I'm trying to analyse a trend in data that I have with Pandas. I have a two tables and I'd like to create a new binary column in one if the UID and PID in that row exists in the other table. An example of the tables I currently have would be:

```<code>>>> df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})
>>> df_a
   PID  TIM  UID
0   12   76  123
1   55   54  456
2   56   21  789
3   89   25  010

>>> df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})
>>> df_b
     FOO  PID  UID
0   2347   17  221
1  32447   89  010
2   3234   51  653
3   7999   55  456
</code>```

And I'd like the end result to be:

```<code>>>> df_a
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  010    1
</code>```

But I'm not sure exactly how to go about doing this. I thought a left join would be the way to go but I'm having trouble pulling that off also. Any help would be appreciated

答:
You can use left join with join or merge, then test FOO column if not NaN to boolean mask which is converted to 0,1 by astype:

```<code>df_a['PUR'] = df_a.join(df_b.set_index(['PID','UID']), on=['PID','UID'])['FOO']
                  .notnull().astype(int)
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1
</code>```

```<code>df_a['PUR'] = pd.merge(df_a, df_b, how='left', on=['PID','UID'])['FOO'].notnull().astype(int)
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1
</code>```

Another solution is test by isin:

```<code>df_a['PUR']  = df_a.set_index('PID')['UID'].isin(df_b.set_index('PID')['UID'])
                   .astype(int).values
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1
</code>```

EDIT:

It seems you need drop_duplicates by both columns:

```<code>#added duplicates
df_b = pd.DataFrame({'UID': [221, 12, 456, 456],
                     'PID': [17, 89, 55, 55],
                     'FOO': [2347, 32447, 3234, 7999]})
print (df_b)
     FOO  PID  UID
0   2347   17  221
1  32447   89   12
2   3234   55  456 <-duplicates by both columns
3   7999   55  456 <-duplicates by both columns

df_b = df_b.drop_duplicates(['PID','UID'])
df_a['PUR'] = df_a.join(df_b.set_index(['PID','UID']), on=['PID','UID'])['FOO']
                  .notnull().astype(int)
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1
</code>```

Body:
I'm trying to analyse a trend in data that I have with Pandas. I have a two tables and I'd like to create a new binary column in one if the UID and PID in that row exists in the other table. An example of the tables I currently have would be:

>>> df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})
>>> df_a
   PID  TIM  UID
0   12   76  123
1   55   54  456
2   56   21  789
3   89   25  010

>>> df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})
>>> df_b
     FOO  PID  UID
0   2347   17  221
1  32447   89  010
2   3234   51  653
3   7999   55  456

And I'd like the end result to be:

>>> df_a
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  010    1

But I'm not sure exactly how to go about doing this. I thought a left join would be the way to go but I'm having trouble pulling that off also. Any help would be appreciated

Body:
You can use left join with join or merge, then test FOO column if not NaN to boolean mask which is converted to 0,1 by astype:

df_a['PUR'] = df_a.join(df_b.set_index(['PID','UID']), on=['PID','UID'])['FOO']
                  .notnull().astype(int)
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1

df_a['PUR'] = pd.merge(df_a, df_b, how='left', on=['PID','UID'])['FOO'].notnull().astype(int)
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1

Another solution is test by isin:

df_a['PUR']  = df_a.set_index('PID')['UID'].isin(df_b.set_index('PID')['UID'])
                   .astype(int).values
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1

EDIT:

It seems you need drop_duplicates by both columns:

#added duplicates
df_b = pd.DataFrame({'UID': [221, 12, 456, 456],
                     'PID': [17, 89, 55, 55],
                     'FOO': [2347, 32447, 3234, 7999]})
print (df_b)
     FOO  PID  UID
0   2347   17  221
1  32447   89   12
2   3234   55  456 <-duplicates by both columns
3   7999   55  456 <-duplicates by both columns

df_b = df_b.drop_duplicates(['PID','UID'])
df_a['PUR'] = df_a.join(df_b.set_index(['PID','UID']), on=['PID','UID'])['FOO']
                  .notnull().astype(int)
print (df_a)
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25   12    1


来源: stackexchange

问:
Why switch the culture of current thread dose not cause to switch the UI language base on the resource files?
My MVC project has 2 resource file for its 2 language (lang.fa.resx and lang.resx) and every things works well until i run it on the local machine (the language of the site changes when I change the language by a drop down list in the homepage).

But when i upload it on the server it dose not work!

It seems:

Culture changes currectly

Language dose not change

What i did:

A)
I put the following codes to the body of the homepage to test the culture value of the current thread:

```<code>@Thread.CurrentThread.CurrentCulture.Name
@Thread.CurrentThread.CurrentUICulture.Name
</code>```

Result:

It show

```<code>fa-IR
fa-IR
</code>```

and

```<code>en-US
en-US
</code>```

according to the selected language in the drop down list. But the language of the site dose not change!

B)
I built and re-uploaded the dll file of the resource project to the server

C)
I checked value of the culture cookie »» It changes correctly.

What do you think about this problem? Why it works on the local machine but dose not works when it is online on the server machine?

答:
I found the reason of the problem:

Before i was just attending to the output DLL files of the main sub-projects in the solution explorer (class libraries and main web project) that they would be built in the root of the bin folder.

But, also there are some folders in the bin folder (name of them are en ru fa fr...). Also I should re-upload them to the server each time i re-build my project. I do this and everything become right.

ContentLicense: CC BY-SA 3.0

Body:
My MVC project has 2 resource file for its 2 language (lang.fa.resx and lang.resx) and every things works well until i run it on the local machine (the language of the site changes when I change the language by a drop down list in the homepage).

But when i upload it on the server it dose not work!

It seems:

Culture changes currectly

Language dose not change

What i did:

A)
I put the following codes to the body of the homepage to test the culture value of the current thread:

@Thread.CurrentThread.CurrentCulture.Name
@Thread.CurrentThread.CurrentUICulture.Name

Result:

It show

fa-IR
fa-IR

and

en-US
en-US

according to the selected language in the drop down list. But the language of the site dose not change!

B)
I built and re-uploaded the dll file of the resource project to the server

C)
I checked value of the culture cookie »» It changes correctly.

What do you think about this problem? Why it works on the local machine but dose not works when it is online on the server machine?


问:
Explain AngularJS boot process
I want to know how boot process is done in angular. Which file is executed first and when execution started js file is executed first and execution of html body is started?  </p>

答:
Placing the script tag at the bottom of the page improves app load time because the HTML loading is not blocked by loading of the angular.js script.

AngularJS does not need to be placed in the HEAD, and actually you normally shouldn't, since this would block loading the HTML.

However, when you load AngularJS at the bottom of the page, you will need to use ng-cloak or ng-bind to avoid the "flash of uncompiled content". Note that you only need to use ng-cloak/ng-bind on your "index.html" page. When ng-include or ng-view or other Angular constructs are used to pull in additional content after the initial page load, that content will be compiled by Angular before it is displayed.

Title: Explain AngularJS boot process


问:
Using setSpanSizeLookup with StaggeredGridLayoutmanager
When I try to use setSpanSizeLookup with GridLayoutManager, it works without error. However, using the same setSpanSizeLookup with StaggeredGridLayoutManager gives an error. It isn't a valid class apparently. Is there any way to use setSpanSizeLookup with StaggeredGridLayoutManager or could you suggest an alternative solution to achieve the same result?

Here is how I have used setSpanSizeLookup with GridLayoutManager -

```<code>GridLayoutManager llm = new GridLayoutManager(getActivity(), 2);
         llm.setSpanSizeLookup(new SpanSizeLookup() {

            @Override
            public int getSpanSize(int position) {
                if(position == 0)
                {
                    return 2;
                }
                else
                {
                    return 1;
                }
        }
});
</code>```

Essentially I want to set the span size of the first item to be maximum and the subsequent rows to be half. Any ideas?

答:
how this
in adapter implements:</p>

```<code>@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
    if(lp != null
            && lp instanceof StaggeredGridLayoutManager.LayoutParams
            && holder.getLayoutPosition() == 0) {
        StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
        p.setFullSpan(true);
    }
}
</code>```

Body:
When I try to use setSpanSizeLookup with GridLayoutManager, it works without error. However, using the same setSpanSizeLookup with StaggeredGridLayoutManager gives an error. It isn't a valid class apparently. Is there any way to use setSpanSizeLookup with StaggeredGridLayoutManager or could you suggest an alternative solution to achieve the same result?

Here is how I have used setSpanSizeLookup with GridLayoutManager -

GridLayoutManager llm = new GridLayoutManager(getActivity(), 2);
         llm.setSpanSizeLookup(new SpanSizeLookup() {

            @Override
            public int getSpanSize(int position) {
                if(position == 0)
                {
                    return 2;
                }
                else
                {
                    return 1;
                }
        }
});

Essentially I want to set the span size of the first item to be maximum and the subsequent rows to be half. Any ideas?

Body:
how this
in adapter implements:

@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
    if(lp != null
            && lp instanceof StaggeredGridLayoutManager.LayoutParams
            && holder.getLayoutPosition() == 0) {
        StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
        p.setFullSpan(true);
    }
}


问:
R Writing to data frame from inside for-loop
Brand new to R programming so please forgive me if I'm using wrong terminologies.
I'm trying to insert/append values to a data frame from inside a for-loop.
I can get the right values if I just print() them, but when I try to put it inside the data frame, I get mostly NA's.  If I run this code it prints out the values I want.

```<code>output <- data.frame()
for (i in seq_along(Reasons)){
  assign(paste(Reasons[i]), sum(ER$Reason == paste(Reasons[i])))
  Tot <- get(paste(Reasons[i]))
  assign(paste(Reasons[i],'ER',sep="_"), sum(grepl("ER|Er", ER$Disposition) & ER$Reason == paste(Reasons[i])))
  Er <- get(paste(Reasons[i],'ER',sep="_"))
  assign(paste(Reasons[i],'adm',sep="_"), sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & ER$Reason == paste(Reasons[i])))
  Adm <- get(paste(Reasons[i],'adm',sep="_"))
  assign(paste(Reasons[i],'admrate',sep="_"), sprintf("%.0f%%", (sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & ER$Reason == paste(Reasons[i])))/(sum(ER$Reason == paste(Reasons[i])))*100))
  Rate <- get(paste(Reasons[i],'admrate',sep="_"))
  print(c(Er,Adm,Tot,Rate))
   #clear variables just created
  rm(list=ls(pattern=Reasons[i]))
  rm(Tot,Er,Adm,Rate)
}
[1] "7"   "13"  "20"  "65%"
[1] "4"   "8"   "12"  "67%"
[1] "12"  "12"  "24"  "50%"
[1] "23"  "7"   "30"  "23%"
[1] "7"   "1"   "8"   "12%"
[1] "3"   "1"   "4"   "25%"
[1] "3"  "0"  "3"  "0%"
[1] "6"   "5"   "11"  "45%"
[1] "2"   "9"   "11"  "82%"
[1] "2"   "4"   "6"   "67%"
[1] "10"  "4"   "14"  "29%"
[1] "5"  "0"  "5"  "0%"
[1] "10"  "4"   "14"  "29%"
[1] "0"    "3"    "3"    "100%"
[1] "7"   "3"   "10"  "30%"
[1] "0"    "4"    "4"    "100%"
</code>```

But when I use

```<code>output <- rbind(output, c(Er, Adm, Tot, Rate))
</code>```

Instead of

```<code>print(c(Er,Adm,Tot,Rate))
</code>```

I get the first row of values (7, 13, 20, 65%), then all NA's except the "7" in rows 5 and 15...  What am I doing wrong?
Thank you in advance

答:
As I don't know what your data look like I cannot reproduce your error. If I understand it correctly, for each value in Reasons you want to find (a) the total number of observations, (b) the number of observations with the string "Er" in the variable Disposition, (c) the number of observations with the string "Admi" in the variable Disposition and (d) the percentage of observations with the string "Admi" in the variable Disposition. If that is the case then you don't have to use assign and get to do this.

Here is a simpler way to do it (although it's not the best way to do it, see below):

```<code>## Here I just generated some data that might look like the data
## you are dealing with:
Reasons <- LETTERS[1:10]
ER <- data.frame(Reason = LETTERS[sample.int(10,100, replace = TRUE)],
    Disposition = c("ER", "Admi", "SomethingElse")[sample.int(3,100, replace = TRUE)])

output <- data.frame()
for (i in seq(along = Reasons)){
    Tot <- sum(ER$Reason ==Reasons[i])
    Er <- sum(grepl("ER|Er", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Adm <- sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Rate <- paste(round(Adm/Tot*100), "%")
    output <- rbind(output, c(Er, Adm, Tot, Rate))
}

> output
   X.4. X.3. X.10. X.30...
1     4    3    10    30 %
2     2    3     6    50 %
3     2    1     6    17 %
4     5    2    14    14 %
5     3    5    11    45 %
6     2    4    11    36 %
7     3    6    14    43 %
8     2    2     5    40 %
9     1    7    11    64 %
10    4    4    12    33 %
</code>```

Dynamically appending rows to a data frame or matrix is generally not a very good idea as it is quite memory intensive. If you know the dimensions of your matrix beforehand (as you do) you should initialize it with the right size and then fill the entries inside your loop:

```<code>## Initialize data:
output <- matrix(nrow = length(Reasons), ncol = 4)
for (i in seq(along = Reasons)){
    Tot <- sum(ER$Reason ==Reasons[i])
    Er <- sum(grepl("ER|Er", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Adm <- sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Rate <- paste(round(Adm/Tot*100), "%")
    output[i,] <- c(Er, Adm, Tot, Rate)
}
</code>```

There are, however, even simpler ways to do this kind of evaluation. You could e.g. use the dplyr package, where you can group the data by a variable (the different Values of ER$Reason in your case) and the evaluate the values you need:

```<code>## Load the package 'dplyr'
library(dplyr)
## Group the variable and evaluate:
output <- ER %>% group_by(Reason) %>%
    dplyr::summarise(Er = sum(grepl("ER|Er", Disposition)),
            Adm = sum(grepl("Admi|admi|ADMI|ADmi", Disposition)),
            Tot = n(),
            Rate = paste(round(Adm/Tot*100), "%"))

> output
# A tibble: 10 × 5
   Reason    Er   Adm   Tot  Rate
    <chr> <int> <int> <int> <chr>
1       A     4     3    10  30 %
2       B     2     3     6  50 %
3       C     2     1     6  17 %
4       D     5     2    14  14 %
5       E     3     5    11  45 %
6       F     2     4    11  36 %
7       G     3     6    14  43 %
8       H     2     2     5  40 %
9       I     1     7    11  64 %
10      J     4     4    12  33 %
</code>```

Body:
Brand new to R programming so please forgive me if I'm using wrong terminologies.
I'm trying to insert/append values to a data frame from inside a for-loop.
I can get the right values if I just print() them, but when I try to put it inside the data frame, I get mostly NA's.  If I run this code it prints out the values I want.

output <- data.frame()
for (i in seq_along(Reasons)){
  assign(paste(Reasons[i]), sum(ER$Reason == paste(Reasons[i])))
  Tot <- get(paste(Reasons[i]))
  assign(paste(Reasons[i],'ER',sep="_"), sum(grepl("ER|Er", ER$Disposition) & ER$Reason == paste(Reasons[i])))
  Er <- get(paste(Reasons[i],'ER',sep="_"))
  assign(paste(Reasons[i],'adm',sep="_"), sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & ER$Reason == paste(Reasons[i])))
  Adm <- get(paste(Reasons[i],'adm',sep="_"))
  assign(paste(Reasons[i],'admrate',sep="_"), sprintf("%.0f%%", (sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & ER$Reason == paste(Reasons[i])))/(sum(ER$Reason == paste(Reasons[i])))*100))
  Rate <- get(paste(Reasons[i],'admrate',sep="_"))
  print(c(Er,Adm,Tot,Rate))
   #clear variables just created
  rm(list=ls(pattern=Reasons[i]))
  rm(Tot,Er,Adm,Rate)
}
[1] "7"   "13"  "20"  "65%"
[1] "4"   "8"   "12"  "67%"
[1] "12"  "12"  "24"  "50%"
[1] "23"  "7"   "30"  "23%"
[1] "7"   "1"   "8"   "12%"
[1] "3"   "1"   "4"   "25%"
[1] "3"  "0"  "3"  "0%"
[1] "6"   "5"   "11"  "45%"
[1] "2"   "9"   "11"  "82%"
[1] "2"   "4"   "6"   "67%"
[1] "10"  "4"   "14"  "29%"
[1] "5"  "0"  "5"  "0%"
[1] "10"  "4"   "14"  "29%"
[1] "0"    "3"    "3"    "100%"
[1] "7"   "3"   "10"  "30%"
[1] "0"    "4"    "4"    "100%"

But when I use

output <- rbind(output, c(Er, Adm, Tot, Rate))

Instead of

print(c(Er,Adm,Tot,Rate))

I get the first row of values (7, 13, 20, 65%), then all NA's except the "7" in rows 5 and 15...  What am I doing wrong?
Thank you in advance

Body:
As I don't know what your data look like I cannot reproduce your error. If I understand it correctly, for each value in Reasons you want to find (a) the total number of observations, (b) the number of observations with the string "Er" in the variable Disposition, (c) the number of observations with the string "Admi" in the variable Disposition and (d) the percentage of observations with the string "Admi" in the variable Disposition. If that is the case then you don't have to use assign and get to do this.

Here is a simpler way to do it (although it's not the best way to do it, see below):

## Here I just generated some data that might look like the data
## you are dealing with:
Reasons <- LETTERS[1:10]
ER <- data.frame(Reason = LETTERS[sample.int(10,100, replace = TRUE)],
    Disposition = c("ER", "Admi", "SomethingElse")[sample.int(3,100, replace = TRUE)])

output <- data.frame()
for (i in seq(along = Reasons)){
    Tot <- sum(ER$Reason ==Reasons[i])
    Er <- sum(grepl("ER|Er", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Adm <- sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Rate <- paste(round(Adm/Tot*100), "%")
    output <- rbind(output, c(Er, Adm, Tot, Rate))
}

> output
   X.4. X.3. X.10. X.30...
1     4    3    10    30 %
2     2    3     6    50 %
3     2    1     6    17 %
4     5    2    14    14 %
5     3    5    11    45 %
6     2    4    11    36 %
7     3    6    14    43 %
8     2    2     5    40 %
9     1    7    11    64 %
10    4    4    12    33 %

Dynamically appending rows to a data frame or matrix is generally not a very good idea as it is quite memory intensive. If you know the dimensions of your matrix beforehand (as you do) you should initialize it with the right size and then fill the entries inside your loop:

## Initialize data:
output <- matrix(nrow = length(Reasons), ncol = 4)
for (i in seq(along = Reasons)){
    Tot <- sum(ER$Reason ==Reasons[i])
    Er <- sum(grepl("ER|Er", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Adm <- sum(grepl("Admi|admi|ADMI|ADmi", ER$Disposition) & (ER$Reason ==Reasons[i]))
    Rate <- paste(round(Adm/Tot*100), "%")
    output[i,] <- c(Er, Adm, Tot, Rate)
}

There are, however, even simpler ways to do this kind of evaluation. You could e.g. use the dplyr package, where you can group the data by a variable (the different Values of ER$Reason in your case) and the evaluate the values you need:

## Load the package 'dplyr'
library(dplyr)
## Group the variable and evaluate:
output <- ER %>% group_by(Reason) %>%
    dplyr::summarise(Er = sum(grepl("ER|Er", Disposition)),
            Adm = sum(grepl("Admi|admi|ADMI|ADmi", Disposition)),
            Tot = n(),
            Rate = paste(round(Adm/Tot*100), "%"))

> output
# A tibble: 10 × 5
   Reason    Er   Adm   Tot  Rate
    <chr> <int> <int> <int> <chr>
1       A     4     3    10  30 %
2       B     2     3     6  50 %
3       C     2     1     6  17 %
4       D     5     2    14  14 %
5       E     3     5    11  45 %
6       F     2     4    11  36 %
7       G     3     6    14  43 %
8       H     2     2     5  40 %
9       I     1     7    11  64 %
10      J     4     4    12  33 %


问:
Finding Smallest Number in List
My goal in this code is to find the smallest number in the list. I used bubble sort method in this case; unfortunately, the code is not giving me the smallest/minimum number. Please take a look, Thanks: </p>

```<code>include irvine32.inc

.data
input               byte        100 dup(0)
stringinput         byte        "Enter any string: ",0
totallength         byte        "The total length is: ",0
minimum             byte        "The minimum value is: ",0
.code

stringLength        proc
                    push        ebp
                    mov         ebp, esp
                    push        ebx
                    push        ecx
                    mov         eax, 0
                    mov         ebx, [ebp+8]
L1:
                    mov         ecx, [ebx] ;you can use ecx, cx, ch, cl
                    cmp         ecx, 0     ;you can use ecx, cx, ch, cl
                    JE          L2
                    add         ebx, 1
                    add         eax, 1
                    jmp         L1
L2:
                    pop         ecx
                    pop         ebx
                    mov         ebp, esp
                    pop         ebp
                    ret         4

stringLength        endp

BubbleSort PROC uses ECX
    push edx
    xor ecx,ecx
    mov ecx, 50

    OUTER_LOOP:
        push ecx
        xor ecx,ecx
        mov ecx,14
        mov esi, OFFSET input

        COMPARE:
            xor ebx,ebx
            xor edx,edx
            mov bl, byte ptr ds:[esi]
            mov dl, byte ptr ds:[esi+1]
            cmp bl,dl
            jg SWAP1

            CONTINUE:
                add esi,2
                loop COMPARE

        mov esi, OFFSET input

        pop ecx
        loop OUTER_LOOP

    jmp FINISHED

    SWAP1:
        xchg bl,dl
        mov byte ptr ds:[esi+1],dl
        mov byte ptr ds:[esi],bl
        jmp CONTINUE

    FINISHED:

    pop edx

    ret 4
BubbleSort ENDP

main proc

                    call        clrscr
                    mov         edx, offset stringinput
                    call        writeString
                    mov         edx, offset input
                    call        writeString
                    call        stringLength
                    mov         edx, offset input
                    mov         ecx, sizeof input
                    call        readstring
                    call        crlf
                    mov         edx,offset totallength
                    call        writestring
                    call        writedec
                    call        crlf
                    mov         edx, offset minimum
                    call        crlf
                    call        writeString
                    push        offset input
                    call        BubbleSort
                    mov         edx, offset input
                    call        writeString
                    call        crlf

                    exit
main                endp

                    end         main
</code>```

答:
I haven't looked over your code, because sorting is an over complicated method for what you want to do. Not only that, but most of us don't pay too much attention to uncommented code. Just takes to long to figure out what you're trying to do.

Simply iterate through the entire list and start with 255 (FFH) in AL let's say. Each time you come across a number that is smaller than the one in AL, then replace it with that value and then when loop is finished, AL will have the lowest value.

If you need to know where it is in the list, you could maybe use AH which would be the difference between start address and current address. Knowledge of the instruction set is essential as finding the length of the string can be simplified by;

```<code>mov     di, input                ; Point to beginning of buffer
mov     cx, -1                   ; for a maximum of 65535 characters
xor     al,  al                  ; Looking for NULL
rep     scasb
neg     cx
dec     cx                       ; CX = length of string.
</code>```

Remember, ES needs to point to @DATA

Title: Finding Smallest Number in List

Body:
My goal in this code is to find the smallest number in the list. I used bubble sort method in this case; unfortunately, the code is not giving me the smallest/minimum number. Please take a look, Thanks:

include irvine32.inc

.data
input               byte        100 dup(0)
stringinput         byte        "Enter any string: ",0
totallength         byte        "The total length is: ",0
minimum             byte        "The minimum value is: ",0
.code

stringLength        proc
                    push        ebp
                    mov         ebp, esp
                    push        ebx
                    push        ecx
                    mov         eax, 0
                    mov         ebx, [ebp+8]
L1:
                    mov         ecx, [ebx] ;you can use ecx, cx, ch, cl
                    cmp         ecx, 0     ;you can use ecx, cx, ch, cl
                    JE          L2
                    add         ebx, 1
                    add         eax, 1
                    jmp         L1
L2:
                    pop         ecx
                    pop         ebx
                    mov         ebp, esp
                    pop         ebp
                    ret         4

stringLength        endp

BubbleSort PROC uses ECX
    push edx
    xor ecx,ecx
    mov ecx, 50

    OUTER_LOOP:
        push ecx
        xor ecx,ecx
        mov ecx,14
        mov esi, OFFSET input

        COMPARE:
            xor ebx,ebx
            xor edx,edx
            mov bl, byte ptr ds:[esi]
            mov dl, byte ptr ds:[esi+1]
            cmp bl,dl
            jg SWAP1

            CONTINUE:
                add esi,2
                loop COMPARE

        mov esi, OFFSET input

        pop ecx
        loop OUTER_LOOP

    jmp FINISHED

    SWAP1:
        xchg bl,dl
        mov byte ptr ds:[esi+1],dl
        mov byte ptr ds:[esi],bl
        jmp CONTINUE

    FINISHED:

    pop edx

    ret 4
BubbleSort ENDP

main proc

                    call        clrscr
                    mov         edx, offset stringinput
                    call        writeString
                    mov         edx, offset input
                    call        writeString
                    call        stringLength
                    mov         edx, offset input
                    mov         ecx, sizeof input
                    call        readstring
                    call        crlf
                    mov         edx,offset totallength
                    call        writestring
                    call        writedec
                    call        crlf
                    mov         edx, offset minimum
                    call        crlf
                    call        writeString
                    push        offset input
                    call        BubbleSort
                    mov         edx, offset input
                    call        writeString
                    call        crlf

                    exit
main                endp

                    end         main

Body:
I haven't looked over your code, because sorting is an over complicated method for what you want to do. Not only that, but most of us don't pay too much attention to uncommented code. Just takes to long to figure out what you're trying to do.

Simply iterate through the entire list and start with 255 (FFH) in AL let's say. Each time you come across a number that is smaller than the one in AL, then replace it with that value and then when loop is finished, AL will have the lowest value.

If you need to know where it is in the list, you could maybe use AH which would be the difference between start address and current address. Knowledge of the instruction set is essential as finding the length of the string can be simplified by;

mov     di, input                ; Point to beginning of buffer
mov     cx, -1                   ; for a maximum of 65535 characters
xor     al,  al                  ; Looking for NULL
rep     scasb
neg     cx
dec     cx                       ; CX = length of string.

Remember, ES needs to point to @DATA


问:
How to use dojo deferred to finish the query, and then call other function with it result?
I have several query tasks, some of which may also include query task. How to use dojo deferred to make sure query is finished and then run other code?

Here is the JavaScript pseudo code:

```<code>// About queryTask: https://developers.arcgis.com/javascript/3/jsapi/querytask-amd.html

var data=[];

settings for query1...;
queryTask1.execute(query1);
queryTask1.on("complete", function (evt1)
{
    var fset1 = evt1.featureSet;
    var resultFeatures1 = fset1.features;
    ...

    settings for query2...;
    queryTask2.execute(query2);
    queryTask2.on("complete", function (evt2)
    {
        var fset2 = evt2.featureSet;
        var resultFeatures2 = fset2.features;
        ...

    });

});

settings for query3...;
queryTask3.execute(query3);
queryTask3.on("complete", function (evt3)
{
    var fset3 = evt3.featureSet;
    var resultFeatures3 = fset3.features;
    ...

});

ResultToKendoGrid(data); //data is updated in the query task 1 2 and 3
</code>```

答:
You could wrap your query tasks in dojo/Deferred objects, and resolve theme when your tasks complete/reject.

If you need to run some code, when all of your query tasks are completed, therefore all your dojo deferred objects are resolved, your can use dojo/promise/all which execute only when all deferred are completed.

Docs:

https://dojotoolkit.org/reference-guide/1.10/dojo/Deferred.html

https://dojotoolkit.org/reference-guide/1.10/dojo/promise/all.html

```<code>require(['dojo/Deferred', 'dojo/promise/all'], function(Deferred, all) {
      // code to initate query tasks here
      var deferredTask1 = new Deferred();
      queryTask1.execute(query1);
      queryTask1.on("complete", function(evt1) {
        deferredTask1.resolve(evt1);
      });
      var deferredTask2 = new Deferred();
      queryTask2.execute(query1);
      queryTask2.on("complete", function(evt1) {
        deferredTask2.resolve(evt1);
      });
      all([deferredTask1, deferredTask1]).then(function(results) {
        // results will be an Array
      });

      // -- or --
      all({
        deferredTask1: deferredTask1,
        deferredTask2: deferredTask2
      }).then(function(results) {
        // results will be an Object using the keys "promise1" and "promise2"
      });
    });
</code>```

Body:
I have several query tasks, some of which may also include query task. How to use dojo deferred to make sure query is finished and then run other code?

Here is the JavaScript pseudo code:

// About queryTask: https://developers.arcgis.com/javascript/3/jsapi/querytask-amd.html

var data=[];

settings for query1...;
queryTask1.execute(query1);
queryTask1.on("complete", function (evt1)
{
    var fset1 = evt1.featureSet;
    var resultFeatures1 = fset1.features;
    ...

    settings for query2...;
    queryTask2.execute(query2);
    queryTask2.on("complete", function (evt2)
    {
        var fset2 = evt2.featureSet;
        var resultFeatures2 = fset2.features;
        ...

    });

});

settings for query3...;
queryTask3.execute(query3);
queryTask3.on("complete", function (evt3)
{
    var fset3 = evt3.featureSet;
    var resultFeatures3 = fset3.features;
    ...

});

ResultToKendoGrid(data); //data is updated in the query task 1 2 and 3

Body:
You could wrap your query tasks in dojo/Deferred objects, and resolve theme when your tasks complete/reject.

If you need to run some code, when all of your query tasks are completed, therefore all your dojo deferred objects are resolved, your can use dojo/promise/all which execute only when all deferred are completed.

Docs:

https://dojotoolkit.org/reference-guide/1.10/dojo/Deferred.html

https://dojotoolkit.org/reference-guide/1.10/dojo/promise/all.html

require(['dojo/Deferred', 'dojo/promise/all'], function(Deferred, all) {
      // code to initate query tasks here
      var deferredTask1 = new Deferred();
      queryTask1.execute(query1);
      queryTask1.on("complete", function(evt1) {
        deferredTask1.resolve(evt1);
      });
      var deferredTask2 = new Deferred();
      queryTask2.execute(query1);
      queryTask2.on("complete", function(evt1) {
        deferredTask2.resolve(evt1);
      });
      all([deferredTask1, deferredTask1]).then(function(results) {
        // results will be an Array
      });

      // -- or --
      all({
        deferredTask1: deferredTask1,
        deferredTask2: deferredTask2
      }).then(function(results) {
        // results will be an Object using the keys "promise1" and "promise2"
      });
    });


问:
How to get value in Response header Angular2
i want to get session token in response header(Set-Cookie).how can i access values in Response header ?

```<code>var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            console.log('url',this.loginUrl)
            this.http.post(this.loginUrl,
                JSON.stringify({ "username": value.username, "password": value.password }),
                { headers: headers })
                .map((res: Response) =>
                    res.json())
                .subscribe((res) => {
                    console.log("res", res);
                    this.loading.hide();
                    if (res.message_code == "SUCCESS") {
                        this.nav.setRoot(HomePage, {
                            username: value.username,
                        });
                    } else {
                        let alert =  Alert.create({
                            title: "Sign In Error !",
                            subTitle: 'Please Check Username or Password.',
                            buttons: ['Ok']
                        });
                        this.nav.present(alert);
                    }
                }, err => {
                    this.loading.hide();
                    console.log('error', err);

                });
</code>```

this is my header response

答:
.map((res: Response) => {
    localStorage.setItem('setCookie', res.headers._headers.get("Set-Cookie")[0]);
    res.json()
})

or you can take reference from https://angular.io/docs/ts/latest/api/http/index/Headers-class.html

Body:
i want to get session token in response header(Set-Cookie).how can i access values in Response header ?

var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            console.log('url',this.loginUrl)
            this.http.post(this.loginUrl,
                JSON.stringify({ "username": value.username, "password": value.password }),
                { headers: headers })
                .map((res: Response) =>
                    res.json())
                .subscribe((res) => {
                    console.log("res", res);
                    this.loading.hide();
                    if (res.message_code == "SUCCESS") {
                        this.nav.setRoot(HomePage, {
                            username: value.username,
                        });
                    } else {
                        let alert =  Alert.create({
                            title: "Sign In Error !",
                            subTitle: 'Please Check Username or Password.',
                            buttons: ['Ok']
                        });
                        this.nav.present(alert);
                    }
                }, err => {
                    this.loading.hide();
                    console.log('error', err);

                });

this is my header response


问:
matplotlib unexpected results polar plot
I am trying to plot simple function r = 3*sin(2*theta) using matplotlib:

import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0,2*np.pi,0.01)
r = 3.0*np.sin(2.0*theta)
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
plt.show()
```

This is the result I get (it is not correct):

This is what I expect to see (wolfram alpha):

Am I missing something?
Thanks!

答:
this patches the polar plot for neg r</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0,2*np.pi,0.01)
r = 3.0*np.sin(2.0*theta)
theta = theta + (1 - np.sign(r))*np.pi/2 # add pi to points with negative r values
r = np.abs(r) # make all r values postive to fake out matplotlib
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
plt.show()
</code>```

Body:
I am trying to plot simple function r = 3*sin(2*theta) using matplotlib:

import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0,2*np.pi,0.01)
r = 3.0*np.sin(2.0*theta)
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
plt.show()

This is the result I get (it is not correct):

This is what I expect to see (wolfram alpha):

Am I missing something?
Thanks!

Body:
this patches the polar plot for neg r

import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0,2*np.pi,0.01)
r = 3.0*np.sin(2.0*theta)
theta = theta + (1 - np.sign(r))*np.pi/2 # add pi to points with negative r values
r = np.abs(r) # make all r values postive to fake out matplotlib
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
plt.show()


问:
Android Intent share Image from url path without saving in local
Hi I need to share image using intent the image is stored in server path ho to achieve it

```<code>private void shareContent(String urlpath)
{
    URL url = null; //Some instantiated URL object
    try {
        url = new URL(urlpath);
        URI uri = url.toURI();

    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    URI screenshotUri = uri;
    sharingIntent.setType("image/*");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    context.startActivity(Intent.createChooser(sharingIntent, "Share image using"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

This is the method that I am using when share button is clicked and I am working in this list adapter

答:
The documentation for EXTRA_STREAM states that the value needs to be a content URI. Technically nothing is stopping you from putting a http URI there. But 99% of receiving apps won't support that.

What you could do is write a ContentProvider that accesses the contents of a http URI and streams them to the receiving application. Kind of like FileProvider, but for http URIs instead of files.

Or, prior to sharing, you download the image, write it to a local file and expose it using FileProvider.

Body:
Hi I need to share image using intent the image is stored in server path ho to achieve it

private void shareContent(String urlpath)
{
    URL url = null; //Some instantiated URL object
    try {
        url = new URL(urlpath);
        URI uri = url.toURI();

    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    URI screenshotUri = uri;
    sharingIntent.setType("image/*");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    context.startActivity(Intent.createChooser(sharingIntent, "Share image using"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is the method that I am using when share button is clicked and I am working in this list adapter


问:
Why Java process hang?
There are many threads in my Java server.
It hangs when one thread recursive invoke a method infinitely.
After the method is invoked 54 times, the process hang, and there is no any log like "StackOverFlow" or "OutOfMemory".

However, as I know, only the thread with the problem will crash, other threads can work normally.

environment:

Linux version 2.6.31-20-server
  (buildd@crested) (gcc version 4.4.1
  (Ubuntu 4.4.1-4ubuntu8) ) java version
  "1.6.0_18" Java(TM) SE Runtime
  Environment (build 1.6.0_18-b07) Java
  HotSpot(TM) 64-Bit Server VM (build
  16.0-b13, mixed mode)

答:
Generate a thread dump which will show you a stack trace for each Java thread in the VM. This will tell you what the threads are doing when the JVM hangs.

To generate a thread dump, on UNIX platforms, you can use the command kill -QUIT process_id, where process_id is the process id of your Java program.

On Windows, you can enter the key sequence <ctrl><break> in the window where the Java program was started. Sending this signal instructs a signal handler in the JVM, to recursively print out all the information on the threads and monitors inside the JVM.

ContentLicense: CC BY-SA 2.5

Title: Why Java process hang?


问:
Angular 2 and PrimeNG chart not rendering fine
Im using the charts wrapper for chart.js provided by http://www.primefaces.org/primeng/#/chart

This works fine when i give the data attribute a static array of numbers
however when i use a function that returns a value (also array of numbers) its not rendering
This is because their implementation doesn't listen to changes automatically
in fact in their docs they state that refresh should be manual

```<code>update(chart: UIChart) {
    this.data = //reload
    chart.refresh();
}
</code>```

my question is how to reference the chart: UIChart from the controller so i can call its refresh method when i need to
here is my current implementation (not drawing since data is empty)

```<code>constructor(private stationService : StationComplianceService) { }

  ngOnInit() {
    this.getStationTypes();
  }

  // ngAfterViewInit(chart: UIChart) {
  //   this.drawGraph(this.processStationType(this.graphData)); not working
  // }

  update(chart: UIChart) {
      chart.refresh();
  }

drawGraph(graphData){
  this.data = {
    labels: ['Up Devices', 'Down Devices'],
    datasets: [
        {
            data: graphData,
            backgroundColor: [
                "#4dd0e1",
                "#4fc3f7"
            ],
            hoverBackgroundColor: [
                "#00acc1",
                "#039be5"
            ]
        }]
    };
}

  getStationTypes(){
    this.stationService.subscribeToComplianceService()
      .subscribe(
        graphData => {
          this.graphData = graphData;
          this.drawGraph(this.processStationType(graphData)); etc etc
</code>```

UPDATE
I managed to get a reference of the chart by using

```<code>@ViewChild
('upDownChart') chart: UIChart;
</code>```

So i was hoping that by calling this.chart.refresh() at the end of the drawGraph function it would work but its not
strangely i have refactored the update (invoked by a click on the ui)

```<code>update() {
      this.chart.refresh();
  }
</code>```

and it is working

答:
If you update to primeng 4.0.0-rc.1, you can handle data refreshing a lot easier, particularly if it is asychnronous.  Here is an example:

```<code>   changeData() {
            this.changedData = {
                labels: ['X','Y','Z'],
                datasets: [
                    {
                        data: [200, 200, 50],
                        backgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ],
                        hoverBackgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ]
                     }]
            }
            this.data = Object.assign({}, this.changedData);

}
</code>```

How do you get Angular 2 (or 4) PrimeNg Charts to refresh asynchronously?

https://github.com/primefaces/primeng/issues/2235

Body:
Im using the charts wrapper for chart.js provided by http://www.primefaces.org/primeng/#/chart

This works fine when i give the data attribute a static array of numbers
however when i use a function that returns a value (also array of numbers) its not rendering
This is because their implementation doesn't listen to changes automatically
in fact in their docs they state that refresh should be manual

update(chart: UIChart) {
    this.data = //reload
    chart.refresh();
}

my question is how to reference the chart: UIChart from the controller so i can call its refresh method when i need to
here is my current implementation (not drawing since data is empty)

constructor(private stationService : StationComplianceService) { }

  ngOnInit() {
    this.getStationTypes();
  }

  // ngAfterViewInit(chart: UIChart) {
  //   this.drawGraph(this.processStationType(this.graphData)); not working
  // }

  update(chart: UIChart) {
      chart.refresh();
  }

drawGraph(graphData){
  this.data = {
    labels: ['Up Devices', 'Down Devices'],
    datasets: [
        {
            data: graphData,
            backgroundColor: [
                "#4dd0e1",
                "#4fc3f7"
            ],
            hoverBackgroundColor: [
                "#00acc1",
                "#039be5"
            ]
        }]
    };
}

  getStationTypes(){
    this.stationService.subscribeToComplianceService()
      .subscribe(
        graphData => {
          this.graphData = graphData;
          this.drawGraph(this.processStationType(graphData)); etc etc

UPDATE
I managed to get a reference of the chart by using

@ViewChild
('upDownChart') chart: UIChart;

So i was hoping that by calling this.chart.refresh() at the end of the drawGraph function it would work but its not
strangely i have refactored the update (invoked by a click on the ui)

update() {
      this.chart.refresh();
  }

and it is working

Body:
If you update to primeng 4.0.0-rc.1, you can handle data refreshing a lot easier, particularly if it is asychnronous.  Here is an example:

   changeData() {
            this.changedData = {
                labels: ['X','Y','Z'],
                datasets: [
                    {
                        data: [200, 200, 50],
                        backgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ],
                        hoverBackgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ]
                     }]
            }
            this.data = Object.assign({}, this.changedData);

}

How do you get Angular 2 (or 4) PrimeNg Charts to refresh asynchronously?

https://github.com/primefaces/primeng/issues/2235


问:
is there a non brute force regex for matching 1st (x to y) characters of a word?
I have the following regex which works, in PERL, to find if the start of a word is contained in a string. I want it to be okay to find, say, divo but not dive. This is not too bad with brute force.

```<code>if ($a =~ /\b(div|divo|divor|divorc|divorce|divorces)\b/i)
{
  print "OK, I found the substring I needed.";
}
</code>```

In other words, if my program sees the start of "divorces" in a string, it flags that string as something I want to look at.

This is okay if I want to do this once, but I have a reason to do this multiple times with multiple words.

Is there a way to do this just with regexes, or would I have to do something like:

```<code>use strict;
use warnings;

while (my $str = <STDIN>)
{
  if (mymatch($str, "divorces", 3, 8))
  {
    print "Yay!\n";
  }
}

sub mymatch
{
  my $temp;
  for ($_[2]..$_[3])
  {
    $temp = substr($_[1], 0, $_);
    if ($_[0] =~ /\b$temp\b/i)
    {
      return 1;
    }
  }
  return 0;
}
</code>```

While being able to use a function like the above is acceptable to me, I have a feeling I'm missing a powerful advanced regex that might be helpful to me in the future as well.

Thanks for any and all help with this!

答:
You're aware of word boundaries in your regex. So, try splitting the text into words:

```<code>my $text = "The case took a dive when the two parties divided over division of assets in the divorce.";

my @text_words = split(/\s+/, $text);
</code>```

Now make a (set) hash of key words you are interested in:

```<code>my %key_words = map { $_ => 1 } qq(div divo divor divorc divorce divorces);
</code>```

And look for the one in the other:

```<code>foreach my $word (@text_words) {
    if (exists $key_words{$word}) {
        # Your code goes here.
        print "OK, I found the substring I needed.";
    }
}
</code>```

This has the advantage that you can merge is with other words/prefixes you might be interested in, and search for them all at the same time.

Body:
I have the following regex which works, in PERL, to find if the start of a word is contained in a string. I want it to be okay to find, say, divo but not dive. This is not too bad with brute force.

if ($a =~ /\b(div|divo|divor|divorc|divorce|divorces)\b/i)
{
  print "OK, I found the substring I needed.";
}

In other words, if my program sees the start of "divorces" in a string, it flags that string as something I want to look at.

This is okay if I want to do this once, but I have a reason to do this multiple times with multiple words.

Is there a way to do this just with regexes, or would I have to do something like:

use strict;
use warnings;

while (my $str = <STDIN>)
{
  if (mymatch($str, "divorces", 3, 8))
  {
    print "Yay!\n";
  }
}

sub mymatch
{
  my $temp;
  for ($_[2]..$_[3])
  {
    $temp = substr($_[1], 0, $_);
    if ($_[0] =~ /\b$temp\b/i)
    {
      return 1;
    }
  }
  return 0;
}

While being able to use a function like the above is acceptable to me, I have a feeling I'm missing a powerful advanced regex that might be helpful to me in the future as well.

Thanks for any and all help with this!

Body:
You're aware of word boundaries in your regex. So, try splitting the text into words:

my $text = "The case took a dive when the two parties divided over division of assets in the divorce.";

my @text_words = split(/\s+/, $text);

Now make a (set) hash of key words you are interested in:

my %key_words = map { $_ => 1 } qq(div divo divor divorc divorce divorces);

And look for the one in the other:

foreach my $word (@text_words) {
    if (exists $key_words{$word}) {
        # Your code goes here.
        print "OK, I found the substring I needed.";
    }
}

This has the advantage that you can merge is with other words/prefixes you might be interested in, and search for them all at the same time.


问:
TypeScript static classes
I wanted to move to TypeScript from traditional JS because I like the C#-like syntax.
My problem is that I can't find out how to declare static classes in TypeScript.

In C#, I often use static classes to organize variables and methods, putting them together in a named class, without needing to instatiate an object.
In vanilla JS, I used to do this with a simple JS object:

```<code>var myStaticClass = {
    property: 10,
    method: function(){}
}
</code>```

In TypeScript, I would rather go for my C-sharpy approach, but it seems that static classes don't exist in TS.
 What is the appropriate solution for this problem ?

答:
Static classes in languages like C# exist because there are no other top-level constructs to group data and functions. In JavaScript, however, they do and so it is much more natural to just declare an object like you did. To more closely mimick the class syntax, you can declare methods like so:</p>

```<code>const myStaticClass = {
    property: 10,

    method() {

    }
}
</code>```

Title: TypeScript static classes

Body:
I wanted to move to TypeScript from traditional JS because I like the C#-like syntax.
My problem is that I can't find out how to declare static classes in TypeScript.

In C#, I often use static classes to organize variables and methods, putting them together in a named class, without needing to instatiate an object.
In vanilla JS, I used to do this with a simple JS object:

var myStaticClass = {
    property: 10,
    method: function(){}
}

In TypeScript, I would rather go for my C-sharpy approach, but it seems that static classes don't exist in TS.
 What is the appropriate solution for this problem ?

Body:
Static classes in languages like C# exist because there are no other top-level constructs to group data and functions. In JavaScript, however, they do and so it is much more natural to just declare an object like you did. To more closely mimick the class syntax, you can declare methods like so:

const myStaticClass = {
    property: 10,

    method() {

    }
}


问:
How to run the Deck.gl getting started examples
I am a newbie in terms of react, js and deck.gl and would like to run the basic getting started example from deck.gl:

Where do I put this code, which extension do I use, do I need other files e.g. app.js to run this:

```<code>import DeckGL from 'deck.gl/react';
import {ArcLayer} from 'deck.gl';

const flights = new ArcLayer({
  id: 'flights',
  data: [] // Some flight points
});

<DeckGL width={1920} height={1080} layers={[flights]} />
</code>```

I am really sorry for the vague question, but I really would like the necessary steps to get this examples working on a Mac.
Do I need to install a react app? How does this work?

答:
EDIT:
Here is a good recent walkthrough of someone experimenting with deck.gl

Source: @github.NghiaTranUIT

Looking at the examples there are two things to note.

You need data within the data field

You need react and other dependences

From getting started

```<code>import DeckGL from 'deck.gl/react';
import {ArcLayer} from 'deck.gl';

const flights = new ArcLayer({
  id: 'flights',
  data: [] // data field needs to have data
});

<DeckGL width={1920} height={1080} layers={[flights]} />
</code>```

they omit how the data should be structured (hence where you might have problems).

The other thing is that the library is dependent on using react

from hello-world-webpack2

package.json

```<code>"dependencies": {
  "deck.gl": "^4.0.0-rc.3",
  "immutable": "^3.8.1",
  "luma.gl": "^3.0.0",
  "react": "^15.4.1",
  "react-dom": "^15.4.1",
  "react-map-gl": "^2.0.0"
},
</code>```

So following those examples, you'll need to have react to run your own project with deck.gl.

I'd recommend looking at the examples on github to get a better understanding on how to run a starter project.

Body:
I am a newbie in terms of react, js and deck.gl and would like to run the basic getting started example from deck.gl:

Where do I put this code, which extension do I use, do I need other files e.g. app.js to run this:

import DeckGL from 'deck.gl/react';
import {ArcLayer} from 'deck.gl';

const flights = new ArcLayer({
  id: 'flights',
  data: [] // Some flight points
});

<DeckGL width={1920} height={1080} layers={[flights]} />

I am really sorry for the vague question, but I really would like the necessary steps to get this examples working on a Mac.
Do I need to install a react app? How does this work?

Body:
EDIT:
Here is a good recent walkthrough of someone experimenting with deck.gl

Source: @github.NghiaTranUIT

Looking at the examples there are two things to note.

You need data within the data field

You need react and other dependences

From getting started

import DeckGL from 'deck.gl/react';
import {ArcLayer} from 'deck.gl';

const flights = new ArcLayer({
  id: 'flights',
  data: [] // data field needs to have data
});

<DeckGL width={1920} height={1080} layers={[flights]} />

they omit how the data should be structured (hence where you might have problems).

The other thing is that the library is dependent on using react

from hello-world-webpack2

package.json

"dependencies": {
  "deck.gl": "^4.0.0-rc.3",
  "immutable": "^3.8.1",
  "luma.gl": "^3.0.0",
  "react": "^15.4.1",
  "react-dom": "^15.4.1",
  "react-map-gl": "^2.0.0"
},

So following those examples, you'll need to have react to run your own project with deck.gl.

I'd recommend looking at the examples on github to get a better understanding on how to run a starter project.


问:
How send Email from server email in laravel 5.3
I am new laravel and i just made a small project of article posting and on user registration i just want to send successfully register email to user email. I searched every where in all tutorials they are giving demo for send mail from gmail and some another email providers. I just want to know is it possible to send the mail simply from server email id ? like cordignator framework:

```<code>$this->email->to('rahul@gmail.com')
$this->email->subject('Testing Email')
$this->email->message('hello')
$this->email->send()
</code>```

答:
set your server mail details in .env file then
run a command php artisan publish

send mail like Mail::to($user)->send(new UserRegister());

and your UserRegister class in app/Mail have one method

```<code>public function build()
{

    return $this->subject("Welcome to My site")
            ->view('`vendor.notifications.register`',compact(''));
}
</code>```

And You can set all message body in resourse/view/vendor/notifications/register

see more on laravel mail

Body:
I am new laravel and i just made a small project of article posting and on user registration i just want to send successfully register email to user email. I searched every where in all tutorials they are giving demo for send mail from gmail and some another email providers. I just want to know is it possible to send the mail simply from server email id ? like cordignator framework:

$this->email->to('rahul@gmail.com')
$this->email->subject('Testing Email')
$this->email->message('hello')
$this->email->send()

Body:
set your server mail details in .env file then
run a command php artisan publish

send mail like Mail::to($user)->send(new UserRegister());

and your UserRegister class in app/Mail have one method

public function build()
{

    return $this->subject("Welcome to My site")
            ->view('`vendor.notifications.register`',compact(''));
}

And You can set all message body in resourse/view/vendor/notifications/register

see more on laravel mail


问:
Google Analytics: Unifying Single Page Application URLs that Contain IDs
We'd like to track behavior flow in our single page application using Google Analytics. We use the hash to route in the application, and we can track the URL within the app with virtual pageviews as described in Google's documentation. However, many of the URLs in the application contain ids, and are considered distinct URLs, despite representing the same page. Thus, we're unable to get accurate behavior flow information in Google Analytics for those pageviews.

For example,

```<code>http://example.com/#/dashboards/8a86204a-7b10-4bf5-961b-be16d209f2b0
</code>```

and

```<code>http://example.com/#/dashboards/d8d6a9b5-b6f1-4159-bd6b-622e628f87b2
</code>```

would be considered distinct pages, when really, we'd like to group these two urls together to determine how users use the dashboard view, rather than how users use a particular dashboard.

Is there a way to unify URLs like this so we can view metrics and behavior flow in aggregate (either in Google Analytics, or in the SPA)?

答:
Completing the answer from @Eike. You can indeed use virtual pageviews to just set the url to '/#/dashboards' using the command
ga('set', 'page', '/#/dashboards'); and then send your pageview. But in my opinion keep the individuality in your data and use a custom dimension to achieve the aggregation you want. Meaning that you should define first a custom dimension that is named for example 'sitePageAggregate'. This dimension will take the value of your website's 'section' url for example 'dashboards' or 'search results' or anything else that might need the aggregation for the behavior flow. This can be done by code in before your pageview hit in each page like this

```<code>ga('set', 'dimensionN', 'dashboards');
</code>```

where N is the custom dimension index. More info on how you can do this here. Now you will just go to your GA interface, Under Behavior -> Site Content -> All pages and just set the secondary dimension as 'sitePageAggregate'. In that way you are retrieving the results you want.

Body:
We'd like to track behavior flow in our single page application using Google Analytics. We use the hash to route in the application, and we can track the URL within the app with virtual pageviews as described in Google's documentation. However, many of the URLs in the application contain ids, and are considered distinct URLs, despite representing the same page. Thus, we're unable to get accurate behavior flow information in Google Analytics for those pageviews.

For example,

http://example.com/#/dashboards/8a86204a-7b10-4bf5-961b-be16d209f2b0

and

http://example.com/#/dashboards/d8d6a9b5-b6f1-4159-bd6b-622e628f87b2

would be considered distinct pages, when really, we'd like to group these two urls together to determine how users use the dashboard view, rather than how users use a particular dashboard.

Is there a way to unify URLs like this so we can view metrics and behavior flow in aggregate (either in Google Analytics, or in the SPA)?

Body:
Completing the answer from @Eike. You can indeed use virtual pageviews to just set the url to '/#/dashboards' using the command
ga('set', 'page', '/#/dashboards'); and then send your pageview. But in my opinion keep the individuality in your data and use a custom dimension to achieve the aggregation you want. Meaning that you should define first a custom dimension that is named for example 'sitePageAggregate'. This dimension will take the value of your website's 'section' url for example 'dashboards' or 'search results' or anything else that might need the aggregation for the behavior flow. This can be done by code in before your pageview hit in each page like this

ga('set', 'dimensionN', 'dashboards');

where N is the custom dimension index. More info on how you can do this here. Now you will just go to your GA interface, Under Behavior -> Site Content -> All pages and just set the secondary dimension as 'sitePageAggregate'. In that way you are retrieving the results you want.


问:
How does timer_tick execute the code block?
Does timer execute the code block each tick even if the code block not completely done ? and if the answer is yes how to make timer tick completes the code block and then start over again.</p>

答:
yes you can stop and then start the timer again once you are done with your time taking logic. </p>

```<code>void myTick_Tick(object sender, EventArgs e)
{
    myTick.Stop();

    // your time taking logic here that may take upto some minutes

    myTick.Start();
}
</code>```

Body:
yes you can stop and then start the timer again once you are done with your time taking logic.

void myTick_Tick(object sender, EventArgs e)
{
    myTick.Stop();

    // your time taking logic here that may take upto some minutes

    myTick.Start();
}


问:
How to query a JSON element
Let's say I have a Postgres database (9.3) and there is a table called Resources. In the Resources table I have the fields id which is an int and data which is a JSON type.

Let's say I have the following records in said table.

1, {'firstname':'Dave', 'lastname':'Gallant'}

2, {'firstname':'John', 'lastname':'Doe'}

What I want to do is write a query that would return all the records in which the data column has a json element with the lastname equal to "Doe"

I tried to write something like this:

```<code>records = db_session.query(Resource).filter(Resources.data->>'lastname' == "Doe").all()
</code>```

Pycharm however is giving me a compile error on the "->>"

Does anyone know how I would write the filter clause to do what I need?

答:
According sqlalchemy.types.JSON, you can do it like this</p>

```<code>from sqlalchemy import JSON
from sqlalchemy import cast
records = db_session.query(Resource).filter(Resources.data["lastname"] == cast("Doe", JSON)).all()
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to query a JSON element

Body:
Let's say I have a Postgres database (9.3) and there is a table called Resources. In the Resources table I have the fields id which is an int and data which is a JSON type.

Let's say I have the following records in said table.

1, {'firstname':'Dave', 'lastname':'Gallant'}

2, {'firstname':'John', 'lastname':'Doe'}

What I want to do is write a query that would return all the records in which the data column has a json element with the lastname equal to "Doe"

I tried to write something like this:

records = db_session.query(Resource).filter(Resources.data->>'lastname' == "Doe").all()

Pycharm however is giving me a compile error on the "->>"

Does anyone know how I would write the filter clause to do what I need?

Body:
According sqlalchemy.types.JSON, you can do it like this

from sqlalchemy import JSON
from sqlalchemy import cast
records = db_session.query(Resource).filter(Resources.data["lastname"] == cast("Doe", JSON)).all()


问:
Storing JSON data as columns in Azure table storage
How do a format my json data and/or change my function so that it gets stored as columns in Azure table storage?

I am sending a json string to the IoT hub:

```<code>{"ts":"2017-03-31T02:14:36.426Z","timeToConnect":"78","batLevel":"83.52","vbat":"3.94"}
</code>```

I run the sample function (in the Azure Function App module) to transfer the data from the IoT hub into my storage account:

```<code>    'use strict';

// This function is triggered each time a message is revieved in the IoTHub.
// The message payload is persisted in an Azure Storage Table
var moment = require('moment');

module.exports = function (context, iotHubMessage) {
   context.log('Message received: ' + JSON.stringify(iotHubMessage));
   context.bindings.deviceData = {
   "partitionKey": moment.utc().format('YYYYMMDD'),
      "rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
      "message": JSON.stringify(iotHubMessage)
   };
   context.done();
};
</code>```

But in my storage table, it shows up as a single string rather than getting split into columns (as seen in the storage explorer.

How do I get it into columns for ts, timeToConnect, batLevel, and vbat?

答:
How do I get it into columns for ts, timeToConnect, batLevel, and
  vbat?

To get these attributes as separate columns in table, you would need to defalte the object and store them separately (currently you are just converting the entire object into string and storing that string).

Please try the following code:

```<code>module.exports = function (context, iotHubMessage) {
   context.log('Message received: ' + JSON.stringify(iotHubMessage));
   var deviceData = {
   "partitionKey": moment.utc().format('YYYYMMDD'),
      "rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
   };
   Object.keys(iotHubMessage).forEach(function(key) {
     deviceData[key] = iotHubMessage[key];
   });
   context.bindings.deviceData = deviceData;
   context.done();
};
</code>```

Please note that I have not tried to execute this code so it may contain some errors.

Body:
How do a format my json data and/or change my function so that it gets stored as columns in Azure table storage?

I am sending a json string to the IoT hub:

{"ts":"2017-03-31T02:14:36.426Z","timeToConnect":"78","batLevel":"83.52","vbat":"3.94"}

I run the sample function (in the Azure Function App module) to transfer the data from the IoT hub into my storage account:

    'use strict';

// This function is triggered each time a message is revieved in the IoTHub.
// The message payload is persisted in an Azure Storage Table
var moment = require('moment');

module.exports = function (context, iotHubMessage) {
   context.log('Message received: ' + JSON.stringify(iotHubMessage));
   context.bindings.deviceData = {
   "partitionKey": moment.utc().format('YYYYMMDD'),
      "rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
      "message": JSON.stringify(iotHubMessage)
   };
   context.done();
};

But in my storage table, it shows up as a single string rather than getting split into columns (as seen in the storage explorer.

How do I get it into columns for ts, timeToConnect, batLevel, and vbat?

Body:
How do I get it into columns for ts, timeToConnect, batLevel, and
  vbat?

To get these attributes as separate columns in table, you would need to defalte the object and store them separately (currently you are just converting the entire object into string and storing that string).

Please try the following code:

module.exports = function (context, iotHubMessage) {
   context.log('Message received: ' + JSON.stringify(iotHubMessage));
   var deviceData = {
   "partitionKey": moment.utc().format('YYYYMMDD'),
      "rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
   };
   Object.keys(iotHubMessage).forEach(function(key) {
     deviceData[key] = iotHubMessage[key];
   });
   context.bindings.deviceData = deviceData;
   context.done();
};

Please note that I have not tried to execute this code so it may contain some errors.


问:
Applying colors via mousedown can only be overwritten if I choose a color with an index value greater than the current color index
My simple mapping software allows for different colors to be applied to counties. I've been struggling with a rather odd bug that only allows colors with an index value greater than the current color index to overwrite the color.

The code is long, but I'm not sure if the point can be made without pasting the entire thing. I will start with the main pieces:

Here is the getColor() function that populates the array of hex colors and where I believe part of the problem lies:

```<code>function getColor(index) {
        var colorarray = [
            '550000',
            '801515',
            'aa3939',
            'd46a6a',
            'ffaaaa',
            '003333',
            '0d4d4d',
            '226666',
            '407f7f',
            '669999',
            '004400',
            '116611',
            '2d882d',
            '55aa55',
            '88cc88',
            '552700',
            '804515',
            'aa6c39',
            'd49a6a',
            'ffd1aa',
        ];
        return colorarray[index];
    }
</code>```

Here is the code in it's entirety. The bug is noticed quickly if you choose the last color in the array (bottom right, pinkish color), select some counties, and then try and overwrite. You'll see that it fails. If you choose the top right, dark red color, you can overwrite that color with any other color because all are farther down the array list.

It uses the colorsjs.js and d3.js libraries.

```<code>    <!DOCTYPE html>
<title>Heartland Remapping Tool</title>
<link rel="shortcut icon" type="image/png" href="/faviconpng.png" />
<style>
    svg {
        width: 100%;
        height: auto;
    }

    input {
        border-width: 0px;
        border: none;
        width: 30px;
        height: 30px;
        cursor: pointer;
        margin: 3px;
    }

    .c550000 {
        fill: #550000;
        stroke-width: .5px;
    }

    .c801515 {
        fill: #801515;
        stroke-width: .5px;
    }

    .caa3939 {
        fill: #aa3939;
        stroke-width: .5px;
    }

    .cd46a6a {
        fill: #d46a6a;
        stroke-width: .5px;
    }

    .cffaaaa {
        fill: #ffaaaa;
        stroke-width: .5px;
    }

    .c003333 {
        fill: #003333;
        stroke-width: .5px;
    }

    .c0d4d4d {
        fill: #0d4d4d;
        stroke-width: .5px;
    }

    .c226666 {
        fill: #226666;
        stroke-width: .5px;
    }

    .c407f7f {
        fill: #407f7f;
        stroke-width: .5px;
    }

    .c669999 {
        fill: #669999;
        stroke-width: .5px;
    }

    .c004400 {
        fill: #004400;
        stroke-width: .5px;
    }

    .c116611 {
        fill: #116611;
        stroke-width: .5px;
    }

    .c2d882d {
        fill: #2d882d;
        stroke-width: .5px;
    }

    .c55aa55 {
        fill: #55aa55;
        stroke-width: .5px;
    }

    .c88cc88 {
        fill: #88cc88;
        stroke-width: .5px;
    }

    .c552700 {
        fill: #552700;
        stroke-width: .5px;
    }

    .c804515 {
        fill: #804515;
        stroke-width: .5px;
    }

    .caa6c39 {
        fill: #aa6c39;
        stroke-width: .5px;
    }

    .cd49a6a {
        fill: #d49a6a;
        stroke-width: .5px;
    }

    .cffd1aa {
        fill: #ffd1aa;
        stroke-width: .5px;
    }

    .counties {
        fill: white;
        stroke: #7887AB;
        stroke-width: .5px;
    }

    .counties .hovered,
    .counties :hover {
        fill: #061539;
        stroke-width: .5px;
    }

    .selected {
        fill: #061539;
    }

    .erase {
        fill: none;
    }

    .deselected {
        fill: white;
        stroke-width: .5px;
    }

    .deselected :hover {
        fill: #061539;
        stroke-width: .5px;
    }

    .county-borders {
        fill: none;
        stroke: #F0F8FF;
        stroke-width: .2px;
        stroke-linejoin: round;
        stroke-linecap: round;
        pointer-events: none;
    }

    .state-borders {
        fill: none;
        stroke: #162955;
        opacity: .8;
        stroke-linejoin: round;
        stroke-linecap: round;
        pointer-events: none;
    }

    .toolTip {
        position: absolute;
        display: none;
        min-width: 80px;
        height: auto;
        background: none repeat scroll 0 0 #ffffff;
        border: 1px solid #6F257F;
        padding: 14px;
        text-align: center;
    }
</style>
<script>
    var selcolor;
    window.onload = function() {
        var defaultcolor = document.getElementById("first");
        getSeletedColor(defaultcolor);
    };

    //this may be the cause of the fact that I can only overwrite colors with a color farther down the list.
    function getColor(index) {
        var colorarray = [
            '550000',
            '801515',
            'aa3939',
            'd46a6a',
            'ffaaaa',
            '003333',
            '0d4d4d',
            '226666',
            '407f7f',
            '669999',
            '004400',
            '116611',
            '2d882d',
            '55aa55',
            '88cc88',
            '552700',
            '804515',
            'aa6c39',
            'd49a6a',
            'ffd1aa',
        ];
        return colorarray[index];
    }

    function getSeletedColor(val) {

        var coloritem = document.getElementById('selcolor');
        coloritem.value = val.value;
        var dispitem = document.getElementById('current_color');
        dispitem.style.background = val.style.backgroundColor;
        dispitem.value = val.value;
    }
</script>
<input id="selcolor" hidden="true" value="hhhhhh"></input>
<div id="option">
    <input style="width: 90px; height: 18px;" name="updateButton" type="button" value="Print Regions" onclick="dl_csv()" />
</div>
<div id="option">
    <input style="width: 90px; height: 18px;" name="updateButton" type="button" value="Reset" onclick="window.location.reload()" />
</div>
<br/>
<div>
    <form id="colorlist">
        <input id="first" style="background-color:#550000; color: #550000;" value="550000" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#801515; color: #801515;" value="801515" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#aa3939; color: #aa3939;" value="aa3939" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#d46a6a; color: #d46a6a;" value="d46a6a" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#ffaaaa; color: #ffaaaa;" value="ffaaaa" onmousedown="getSeletedColor(this)">
        <br/>
        <input spellcheck="false" style="background-color:#003333; color: #003333;" value="003333" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#0d4d4d; color: #0d4d4d;" value="0d4d4d" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#226666; color: #226666;" value="226666" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#407f7f; color: #407f7f;" value="407f7f" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#669999; color: #669999;" value="669999" onmousedown="getSeletedColor(this)">
        <br/>
        <input spellcheck="false" style="background-color:#004400; color: #004400;" value="004400" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#116611; color: #116611;" value="116611" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#2d882d; color: #2d882d;" value="2d882d" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#55aa55; color: #55aa55;" value="55aa55" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#88cc88; color: #88cc88;" value="88cc88" onmousedown="getSeletedColor(this)">
        <br/>
        <input spellcheck="false" style="background-color:#552700; color: #552700;" value="552700" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#804515; color: #804515;" value="804515" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#aa6c39; color: #aa6c39;" value="aa6c39" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#d49a6a; color: #d49a6a;" value="d49a6a" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#ffd1aa; color: #ffd1aa;" value="ffd1aa" onmousedown="getSeletedColor(this)">
    </form>
    <br/>
    <input readonly hidden="true" style="background:white; width: 50px;" id="current_color" value="550000"></input>
    <form action="">
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="tool" value="zoompan" id="zoompan"> <u>Z</u>oom/Pan
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="tool" value="select" id="select" checked> <u>S</u>elect
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="tool" value="erase" id="erase"> <u>E</u>rase
    </form>
    <form action="">
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="map" value="county" checked> County
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="map" value="state"> State
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="map" value="other"> Other
    </form>
</div>

<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.js"></script>
<!--<script src="jscolor.js"></script>-->
<script>
    var svg = d3.select("svg");
    var path = d3.geoPath();
    var tooltip = d3.select("body").append("div").attr("class", "toolTip");

    var clickDown = true;
    var color_selcounties = [];
    for (i = 0; i < 20; i++) {
        color_selcounties[getColor(i)] = [];
    }
    var selectedCounties = [];
    var uniqueCounties = [];
    var selectedCountiesNum = selectedCounties.length;
    var t = [
        ['color', 'fips']
    ];
    var csvRows = [];

    var expArray = [
        ['color', 'fips']
    ];

    var region = function() {
        //Dedupes the list of counties, this ensures no counties are double bucketed.
        uniqueCounties = selectedCounties.filter(function(elem, pos) {
            return selectedCounties.indexOf(elem) == pos;
        });
        console.log("Master: " + uniqueCounties);

        //Dedupes the list of counties by region.
        for (i = 0; i < 20; i++) {
            if (color_selcounties[getColor(i)].length >= 1) {
                var uniqueColorCounties = color_selcounties[getColor(i)].filter(function(elem, pos) {
                    return color_selcounties[getColor(i)].indexOf(elem) == pos;
                });
                console.log(getColor(i) + ": " + uniqueColorCounties);
                t.push([getColor(i), uniqueColorCounties]);
            }
        }
    }

    var tools = function() {
        if (document.getElementById("zoompan").checked) {
            alert("zoompan");
        } else if (document.getElementById("select").checked) {
            alert("select");
        } else if (document.getElementById("erase").checked) {
            document.body.style.cursor = "pointer";
        } else {

        }
    }

    function dl_csv() {
        region();
        var csvString = expArray.join("%0A");
        var a = document.createElement('a');
        a.href = 'data:attachment/csv,' + csvString;
        a.target = '_blank';
        a.download = 'myFile.csv';

        document.body.appendChild(a);
        a.click();
    }

    d3.json("https://d3js.org/us-10m.v1.json", function(error, us) {
        if (error) throw error;

        let hoverEnabled = false;
        var mousedown = function() {
            if (document.getElementById("select").checked) {
                var self = d3.select(this);
                hoverEnabled = !self.classed('hovered');

                if (hoverEnabled) {

                    selectedCounties.push(this.__data__.id);
                    var color = document.getElementById('selcolor').value;
                    self.classed("c" + color, true);

                    color_selcounties[color].push(this.__data__.id);
                    expArray.push([color, this.__data__.id]);

                } else {
                    var ix = selectedCounties.indexOf(this.__data__.id);
                    selectedCounties.splice(ix, 1);
                }

            } else if (document.getElementById("erase").checked) {
                var self = d3.select(this);

                self.classed('deselected', true);

                var ix = selectedCounties.indexOf(this.__data__.id);
                selectedCounties.splice(ix, 1);
            }
        }

        svg.append("g")
            .attr("class", "counties")
            .selectAll("path")
            .data(topojson.feature(us, us.objects.counties).features)
            .enter()
            .append("path")
            .attr("d", path);

        svg.append("g")
            .attr("class", "state-borders")
            .selectAll("path")
            .data(topojson.feature(us, us.objects.nation).features)
            .enter()
            .append("path")
            .attr("d", path);
        svg.append("path")
            .attr("class", "state-borders")
            .attr("d", path(topojson.mesh(us, us.objects.nation, function(a, b) {
                return a !== b;
            })));
        svg.append("path")
            .attr("class", "state-borders")
            .attr("d", path(topojson.mesh(us, us.objects.states, function(a, b) {
                return a !== b;
            })));
        svg.append("path")
            .attr("class", "county-borders")
            .attr("d", path(topojson.mesh(us, us.objects.counties, function(a, b) {
                return a !== b;
            })));

        svg.selectAll('.counties path')
            .on('mousedown', mousedown)
            .on('mouseup', function() {
                hoverEnabled = false;
            })
            .on('mouseover', function() {

                tooltip
                    .style("left", 500 + "px")
                    .style("top", 70 + "px")
                    .style("display", "inline-block")
                    .html(this.__data__.id);

                var color = document.getElementById('selcolor').value;
                var self = d3.select(this);

                if (hoverEnabled) {

                    self.classed("deselected", false);
                    self.classed("c" + color, true);

                    selectedCounties.push(this.__data__.id);
                    color_selcounties[color].push(this.__data__.id);
                    expArray.push([color, this.__data__.id]);
                }
            })
            .on('mouseout', function(d) {
                tooltip.style("display", "none");
            });
    });
</script>
</code>```

答:
When you do this...

```<code>self.classed("c" + color, true);
</code>```

You are simply adding classes (in the "hexadecimal order"), but not removing the existing ones.

Because of that, your elements will have several classes...

```<code>class = "foo bar baz"
</code>```

... and the prevalent color will be the color set by the last class in the style sheet, which explains the behaviour you're seeing now.

Solution: A simple solution is just changing it to:

```<code>self.attr("class", "c" + color);
</code>```

Which overwrites any previously existing class. Do the same for the other classed functions.

Here is your working code: https://jsfiddle.net/zbvxk4xv/

Body:
My simple mapping software allows for different colors to be applied to counties. I've been struggling with a rather odd bug that only allows colors with an index value greater than the current color index to overwrite the color.

The code is long, but I'm not sure if the point can be made without pasting the entire thing. I will start with the main pieces:

Here is the getColor() function that populates the array of hex colors and where I believe part of the problem lies:

function getColor(index) {
        var colorarray = [
            '550000',
            '801515',
            'aa3939',
            'd46a6a',
            'ffaaaa',
            '003333',
            '0d4d4d',
            '226666',
            '407f7f',
            '669999',
            '004400',
            '116611',
            '2d882d',
            '55aa55',
            '88cc88',
            '552700',
            '804515',
            'aa6c39',
            'd49a6a',
            'ffd1aa',
        ];
        return colorarray[index];
    }

Here is the code in it's entirety. The bug is noticed quickly if you choose the last color in the array (bottom right, pinkish color), select some counties, and then try and overwrite. You'll see that it fails. If you choose the top right, dark red color, you can overwrite that color with any other color because all are farther down the array list.

It uses the colorsjs.js and d3.js libraries.

    <!DOCTYPE html>
<title>Heartland Remapping Tool</title>
<link rel="shortcut icon" type="image/png" href="/faviconpng.png" />

<input id="selcolor" hidden="true" value="hhhhhh"></input>

    <input style="width: 90px; height: 18px;" name="updateButton" type="button" value="Print Regions" onclick="dl_csv()" />

    <input style="width: 90px; height: 18px;" name="updateButton" type="button" value="Reset" onclick="window.location.reload()" />

    <form id="colorlist">
        <input id="first" style="background-color:#550000; color: #550000;" value="550000" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#801515; color: #801515;" value="801515" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#aa3939; color: #aa3939;" value="aa3939" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#d46a6a; color: #d46a6a;" value="d46a6a" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#ffaaaa; color: #ffaaaa;" value="ffaaaa" onmousedown="getSeletedColor(this)">

        <input spellcheck="false" style="background-color:#003333; color: #003333;" value="003333" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#0d4d4d; color: #0d4d4d;" value="0d4d4d" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#226666; color: #226666;" value="226666" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#407f7f; color: #407f7f;" value="407f7f" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#669999; color: #669999;" value="669999" onmousedown="getSeletedColor(this)">

        <input spellcheck="false" style="background-color:#004400; color: #004400;" value="004400" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#116611; color: #116611;" value="116611" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#2d882d; color: #2d882d;" value="2d882d" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#55aa55; color: #55aa55;" value="55aa55" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#88cc88; color: #88cc88;" value="88cc88" onmousedown="getSeletedColor(this)">

        <input spellcheck="false" style="background-color:#552700; color: #552700;" value="552700" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#804515; color: #804515;" value="804515" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#aa6c39; color: #aa6c39;" value="aa6c39" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#d49a6a; color: #d49a6a;" value="d49a6a" onmousedown="getSeletedColor(this)">
        <input spellcheck="false" style="background-color:#ffd1aa; color: #ffd1aa;" value="ffd1aa" onmousedown="getSeletedColor(this)">
    </form>

    <input readonly hidden="true" style="background:white; width: 50px;" id="current_color" value="550000"></input>
    <form action="">
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="tool" value="zoompan" id="zoompan"> Zoom/Pan
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="tool" value="select" id="select" checked> Select
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="tool" value="erase" id="erase"> Erase
    </form>
    <form action="">
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="map" value="county" checked> County
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="map" value="state"> State
        <input style="margin: default; height: 18px; width: 15px;" type="radio" name="map" value="other"> Other
    </form>

<svg width="960" height="600"></svg>

Body:
When you do this...

self.classed("c" + color, true);

You are simply adding classes (in the "hexadecimal order"), but not removing the existing ones.

Because of that, your elements will have several classes...

class = "foo bar baz"

... and the prevalent color will be the color set by the last class in the style sheet, which explains the behaviour you're seeing now.

Solution: A simple solution is just changing it to:

self.attr("class", "c" + color);

Which overwrites any previously existing class. Do the same for the other classed functions.

Here is your working code: https://jsfiddle.net/zbvxk4xv/