问:
How to implement pause (and more) functionality?
My apologies beforehand for the length of the question, I didn't want to leave anything out.

Some background information

I'm trying to automate a data entry process by writing a Python application that uses the Windows API to simulate keystrokes, mouse movement and window/control manipulation. I have to resort to this method because I do not (yet) have the security clearance required to access the datastore/database directly (e.g. using SQL) or indirectly through a better suited API. Bureaucracy, it's a pain ;-)

The data entry process involves the correction of sales orders due to changes in article availability. The unavailable articles are either removed from the order or replaced by another suitable article.

Initially I want a human to be able to monitor the automatic data entry process to make sure everything goes right. To achieve this I slow down the actions on the one hand but also inform the user of what is currently going on through a pinned window.

The actual question

To allow the user to halt the automation process I'm registering the Pause/Break key as a hotkey and in the handler I want to pause the automation functionality. However, I'm currently struggling to figure out a way to properly pause the execution of the automation functionality. When the pause function is invoked I want the automation process to stop dead in its tracks, no matter what it is doing. I don't want it to even execute another keystroke.

UPDATE [23/01]: I actually want to do more than just pause, I want to be able to communicate with the automation process while it is running and request it to pause, skip the current sales order, give up completely and perhaps even more.

Can anybody show me The Right Way (TM) to achieve what I want?

Some more information

Here's an example of how the automation works (I'm using the pywinauto library):

```<code>from pywinauto import application
app = application.Application()
app.start_("notepad")
app.Notepad.TypeKeys("abcdef")
</code>```

UPDATE [25/01]: After a few days of working on my application I've noticed I don't really use pywinauto that much, right now I'm only using it for finding window and then I directly use SendKeysCtypes.SendKeys to simulate keyboard input and win32api functions to simulate mouse input.

What I've found out so far

Here are a few methods I've come across so far in my search for an answer:

I could separate the automation functionality and the interface + hotkey listener in two separate processes. Let's refer to the former as "automator" and the latter as "manager". The manager can then pause the execution of the automator by sending the process a SIGSTOP signal and unpause it using the SIGCONT signal (or the Windows equivalents through SuspendThread/ResumeThread).

To be able to update the user interface the automator will need to inform the manager of its progression through some sort of an IPC mechanism.

Cons:

Would using SIGSTOP not be a little harsh? Would it even work properly? Lots of people seem to be advising against it and even calling it "dangerous".

I am worried that implementing the IPC mechanism is going to be a bit complicated. On the other hand, I have worked with DBus which wouldn't be too hard to implement.

The second method and one that lots of people seem to be suggesting involves using threads and essentially boils down to the following (simplified):

```<code>while True:
    if self.pause: # pause
    # Do the work...
</code>```

However, doing it this way it seems it will only pause after there is no more work to do. The only way I see this method would work would be to divide the work (the entire automation process) into smaller work segments (i.e. tasks). Before starting on a new task the worker thread would check if it should pause and wait.

Cons:

Seems like an implementation to divide the work into smaller segments, such as the one above, would be very ugly code wise (aesthetically).

The way I imagine it, all statements would be transformed to look something like: queue.put((function, args)) (e.g. queue.put((app.Notepad.TypeKeys, "abcdef"))) and you'd have the automating process thread running through the tasks and continuously checking for the pause state before starting a task. That just can't be right...

The program would not actually stop dead in its tracks, but would first finish a task (however small) before actually pausing.

Progress made

UPDATE [23/01]: I've implemented a version of my application using the first method through the mentioned SuspendThread/ResumeThread functionality. So far this seems to work very nicely and also allows me to write the automation stuff just like you'd write any other script. The only quirk I've come across is that keyboard modifiers (CTRL, ALT, SHIFT) get "stuck" while paused. Something I can probably easily work around.

I've also written a test using the second method (threads and signals/message passing) and implemented the pause functionality. However, it looks really ugly (both checking for the pause flag and everything related to the "doing the work"). So if anybody can show me a proper example of something similar to the second method I'd appreciate it.

Related questions

Pausing a process?

Pausing a thread using threading class

Alex Martelli posted an answer saying:

There is no method for other threads to forcibly pause a thread (any more than there is for other threads to kill that thread) -- the target thread must cooperate by occasionally checking appropriate "flags" (a threading.Condition might be appropriate for the pause/unpause case).

He then referred to the multiprocessing module and SIGSTOP/SIGCONT.

Is there a way to indefinitely pause a thread?

Pausing a process in Windows

An answer to this question quotes the MSDN documentation regarding SuspendThread:

This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.

Is there any way to kill a Thread in Python?

How do I pass an exception between threads in python

答:
Separating the functionality and the interface thread/process is definately the best option imho, the second solution is quicker and easier but definately not better.

Perhaps using multiple threads and an exception would be a better idea than using multiple processes. But if you're using multiple processes than SIGSTOP might be your only way to get it to work.

Is there anything against using 2 threads for this?

1 thread for actually executing

1 thread for reading the user input

Body:
My apologies beforehand for the length of the question, I didn't want to leave anything out.

Some background information

I'm trying to automate a data entry process by writing a Python application that uses the Windows API to simulate keystrokes, mouse movement and window/control manipulation. I have to resort to this method because I do not (yet) have the security clearance required to access the datastore/database directly (e.g. using SQL) or indirectly through a better suited API. Bureaucracy, it's a pain ;-)

The data entry process involves the correction of sales orders due to changes in article availability. The unavailable articles are either removed from the order or replaced by another suitable article.

Initially I want a human to be able to monitor the automatic data entry process to make sure everything goes right. To achieve this I slow down the actions on the one hand but also inform the user of what is currently going on through a pinned window.

The actual question

To allow the user to halt the automation process I'm registering the Pause/Break key as a hotkey and in the handler I want to pause the automation functionality. However, I'm currently struggling to figure out a way to properly pause the execution of the automation functionality. When the pause function is invoked I want the automation process to stop dead in its tracks, no matter what it is doing. I don't want it to even execute another keystroke.

UPDATE [23/01]: I actually want to do more than just pause, I want to be able to communicate with the automation process while it is running and request it to pause, skip the current sales order, give up completely and perhaps even more.

Can anybody show me The Right Way (TM) to achieve what I want?

Some more information

Here's an example of how the automation works (I'm using the pywinauto library):

from pywinauto import application
app = application.Application()
app.start_("notepad")
app.Notepad.TypeKeys("abcdef")

UPDATE [25/01]: After a few days of working on my application I've noticed I don't really use pywinauto that much, right now I'm only using it for finding window and then I directly use SendKeysCtypes.SendKeys to simulate keyboard input and win32api functions to simulate mouse input.

What I've found out so far

Here are a few methods I've come across so far in my search for an answer:

I could separate the automation functionality and the interface + hotkey listener in two separate processes. Let's refer to the former as "automator" and the latter as "manager". The manager can then pause the execution of the automator by sending the process a SIGSTOP signal and unpause it using the SIGCONT signal (or the Windows equivalents through SuspendThread/ResumeThread).

To be able to update the user interface the automator will need to inform the manager of its progression through some sort of an IPC mechanism.

Cons:

Would using SIGSTOP not be a little harsh? Would it even work properly? Lots of people seem to be advising against it and even calling it "dangerous".

I am worried that implementing the IPC mechanism is going to be a bit complicated. On the other hand, I have worked with DBus which wouldn't be too hard to implement.

The second method and one that lots of people seem to be suggesting involves using threads and essentially boils down to the following (simplified):

while True:
    if self.pause: # pause
    # Do the work...

However, doing it this way it seems it will only pause after there is no more work to do. The only way I see this method would work would be to divide the work (the entire automation process) into smaller work segments (i.e. tasks). Before starting on a new task the worker thread would check if it should pause and wait.

Cons:

Seems like an implementation to divide the work into smaller segments, such as the one above, would be very ugly code wise (aesthetically).

The way I imagine it, all statements would be transformed to look something like: queue.put((function, args)) (e.g. queue.put((app.Notepad.TypeKeys, "abcdef"))) and you'd have the automating process thread running through the tasks and continuously checking for the pause state before starting a task. That just can't be right...

The program would not actually stop dead in its tracks, but would first finish a task (however small) before actually pausing.

Progress made

UPDATE [23/01]: I've implemented a version of my application using the first method through the mentioned SuspendThread/ResumeThread functionality. So far this seems to work very nicely and also allows me to write the automation stuff just like you'd write any other script. The only quirk I've come across is that keyboard modifiers (CTRL, ALT, SHIFT) get "stuck" while paused. Something I can probably easily work around.

I've also written a test using the second method (threads and signals/message passing) and implemented the pause functionality. However, it looks really ugly (both checking for the pause flag and everything related to the "doing the work"). So if anybody can show me a proper example of something similar to the second method I'd appreciate it.

Related questions

Pausing a process?

Pausing a thread using threading class

Alex Martelli posted an answer saying:

There is no method for other threads to forcibly pause a thread (any more than there is for other threads to kill that thread) -- the target thread must cooperate by occasionally checking appropriate "flags" (a threading.Condition might be appropriate for the pause/unpause case).

He then referred to the multiprocessing module and SIGSTOP/SIGCONT.

Is there a way to indefinitely pause a thread?

Pausing a process in Windows

An answer to this question quotes the MSDN documentation regarding SuspendThread:

This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.

Is there any way to kill a Thread in Python?

How do I pass an exception between threads in python


来源: stackexchange

问:
AI: Conditional Independence
Conditional Independence Example Photo

The entire pdf lesson
it's on page 8.

I've been looking at this for a long time now; can anyone explain how for the P13 we end up with <0.31,0.69>? I'm not sure how the a' gets distributed here. When I calculate 0.2(0.04+0.16+0.16) for the x column I get 0.072, so how do we end up with 0.31?

Thank you.

答:
The α is a normalization constant that is supposed to ensure that you have proper probabilities, i.e. values in [0, 1] that sum to 1. As such, it has to be 1 over the sum of all possible values. For your example, we calculate it as follows.

Let's first evaluate the single expressions in the tuple:

0.2 * (0.04 + 0.16 + 0.16) = 0.072

0.8 * (0.04 + 0.16) = 0.16

Notice that these two values do not specify a probability distribution (they don't sum to 1).
Therefore, we calculate the normalization constant α as 1 over the sum of these values:

α = 1 / (0.072 + 0.16) = 4.310345

With this, we normalize the original values as follows:

0.072 * α = 0.310345

0.16 * α = 0.689655

Notice how these values do indeed specify a probability distribution now. (They are in [0, 1] and sum to 1).

I hope this helps :)

ContentLicense: CC BY-SA 3.0

Title: AI: Conditional Independence


问:
Get columns in frame based on values in second frame
I have 2 dataframes. One has a ID column with alot of arranged IDs.
The other one has just specific rows of the first column. Those are my markers.
I need to get the sum of the of the values in a specific column based on the id values of the second column.
The first column may be

```<code>id   goals   cards   group
1      2       2       1
2      3       2       1
3      4       2       1
4      5       1       1
5      1       2       1
1      2       2       2
2      3       2       2
3      4       2       2
4      5       1       3
5      1       2       3
</code>```

the second one:

```<code> id   goals   cards   group
  2      3       2      1
  5      1       2      1
  2      3       2      2
  3      4       2      2
  5      1       2      3
</code>```

what  i need to get:

```<code> id   goals   cards   group   points
 1      2       2       1      2-(2+2)
 2      3       2       1      0 cause in second list
 3      4       2       1      4-(2+1+2)
 4      5       1       1      5-(1+2)
 5      1       2       1      0 cause in second list
 1      2       2       2      2-(2+2)
 2      3       2       2      0
 3      4       2       2      0
 4      5       1       3      5-(1+2)
 5      1       2       3      0
</code>```

Something like: ??

```<code>df1<- df1%>%
rowwise() %>%
mutate(points=
       goals
       -(sum( df1$cards[df1$id <= df2$id & df1$id>df1$id])))
</code>```

答:
```<code>df1 = read.table(text = "
id   goals   cards
1      2       2
2      3       2
3      4       2
4      5       1
5      1       2
", header=T)

df2 = read.table(text = "
id   goals   cards
2      3       2
5      1       2
", header=T)

library(dplyr)

# function that gets an id and returns the sum of cards based on df2
GetSumOfCards = function(x) {
  ids = min(df2$id[df2$id >= x])                        # for a given id of df1 find the minimum id in df2 that is bigger than this id
  ifelse(x %in% df2$id,                                 # if the given id exists in df2
         0,                                             # sum of cards is zero
         sum(df1$cards[df1$id >= x & df1$id <= ids]))   # otherwise get sum of cards in df1 from this id until the id obtained before
}

# update function to be vectorised
GetSumOfCards = Vectorize(GetSumOfCards)

df1 %>%
  mutate(sum_cards = GetSumOfCards(id),      # get sum of cards for each id using the function
         points = goals - sum_cards)         # get the points

#   id goals cards sum_cards points
# 1  1     2     2         4     -2
# 2  2     3     2         0      3
# 3  3     4     2         5     -1
# 4  4     5     1         3      2
# 5  5     1     2         0      1
</code>```

Based on your updated question, applying a similar function to every row makes the process very slow. So, this solution groups data in a way that you can just count the cards on chunks of data/rows:

```<code>df1 = read.table(text = "
id   goals   cards   group
                 1      2       2       1
                 2      3       2       1
                 3      4       2       1
                 4      5       1       1
                 5      1       2       1
                 1      2       2       2
                 2      3       2       2
                 3      4       2       2
                 4      5       1       3
                 5      1       2       3
                 ", header=T)

df2 = read.table(text = "
                 id   goals   cards   group
                 2      3       2      1
                 5      1       2      1
                 2      3       2      2
                 3      4       2      2
                 5      1       2      3
                 ", header=T)

library(dplyr)

df1 %>%
  arrange(group, desc(id)) %>%                                  # order by group and id descending (this will help with counting the cards)
  left_join(df2 %>%                                             # join specific columns of df2 and add a flag to know that this row exists in df2
              select(id, group) %>%
              mutate(flag = 1), by=c("id","group")) %>%
  mutate(flag = ifelse(is.na(flag), 0, flag),                   # replace NA with 0
         flag2 = cumsum(flag)) %>%                              # this flag will create the groups we need to count cards
  group_by(group, flag2) %>%                                    # for each new group (we need both as the card counting will change when we have a row from df2, or if group changes)
  mutate(sum_cards = ifelse(flag == 1, 0, cumsum(cards))) %>%   # get cummulative sum of cards unless the flag = 1, where we need 0 cards
  ungroup() %>%                                                 # forget the grouping
  arrange(group, id) %>%                                        # back to original order
  mutate(points = goals - sum_cards) %>%                        # calculate points
  select(-flag, -flag2)                                         # remove flags

# # A tibble: 10 x 6
#      id goals cards group sum_cards points
#   <int> <int> <int> <int>     <dbl>  <dbl>
# 1     1     2     2     1         4     -2
# 2     2     3     2     1         0      3
# 3     3     4     2     1         5     -1
# 4     4     5     1     1         3      2
# 5     5     1     2     1         0      1
# 6     1     2     2     2         4     -2
# 7     2     3     2     2         0      3
# 8     3     4     2     2         0      4
# 9     4     5     1     3         3      2
# 10    5     1     2     3         0      1
</code>```

Body:
I have 2 dataframes. One has a ID column with alot of arranged IDs.
The other one has just specific rows of the first column. Those are my markers.
I need to get the sum of the of the values in a specific column based on the id values of the second column.
The first column may be

id   goals   cards   group
1      2       2       1
2      3       2       1
3      4       2       1
4      5       1       1
5      1       2       1
1      2       2       2
2      3       2       2
3      4       2       2
4      5       1       3
5      1       2       3

the second one:

 id   goals   cards   group
  2      3       2      1
  5      1       2      1
  2      3       2      2
  3      4       2      2
  5      1       2      3

what  i need to get:

 id   goals   cards   group   points
 1      2       2       1      2-(2+2)
 2      3       2       1      0 cause in second list
 3      4       2       1      4-(2+1+2)
 4      5       1       1      5-(1+2)
 5      1       2       1      0 cause in second list
 1      2       2       2      2-(2+2)
 2      3       2       2      0
 3      4       2       2      0
 4      5       1       3      5-(1+2)
 5      1       2       3      0

Something like: ??

df1<- df1%>%
rowwise() %>%
mutate(points=
       goals
       -(sum( df1$cards[df1$id <= df2$id & df1$id>df1$id])))

Body:
df1 = read.table(text = "
id   goals   cards
1      2       2
2      3       2
3      4       2
4      5       1
5      1       2
", header=T)

df2 = read.table(text = "
id   goals   cards
2      3       2
5      1       2
", header=T)

library(dplyr)

# function that gets an id and returns the sum of cards based on df2
GetSumOfCards = function(x) {
  ids = min(df2$id[df2$id >= x])                        # for a given id of df1 find the minimum id in df2 that is bigger than this id
  ifelse(x %in% df2$id,                                 # if the given id exists in df2
         0,                                             # sum of cards is zero
         sum(df1$cards[df1$id >= x & df1$id <= ids]))   # otherwise get sum of cards in df1 from this id until the id obtained before
}

# update function to be vectorised
GetSumOfCards = Vectorize(GetSumOfCards)

df1 %>%
  mutate(sum_cards = GetSumOfCards(id),      # get sum of cards for each id using the function
         points = goals - sum_cards)         # get the points

#   id goals cards sum_cards points
# 1  1     2     2         4     -2
# 2  2     3     2         0      3
# 3  3     4     2         5     -1
# 4  4     5     1         3      2
# 5  5     1     2         0      1

Based on your updated question, applying a similar function to every row makes the process very slow. So, this solution groups data in a way that you can just count the cards on chunks of data/rows:

df1 = read.table(text = "
id   goals   cards   group
                 1      2       2       1
                 2      3       2       1
                 3      4       2       1
                 4      5       1       1
                 5      1       2       1
                 1      2       2       2
                 2      3       2       2
                 3      4       2       2
                 4      5       1       3
                 5      1       2       3
                 ", header=T)

df2 = read.table(text = "
                 id   goals   cards   group
                 2      3       2      1
                 5      1       2      1
                 2      3       2      2
                 3      4       2      2
                 5      1       2      3
                 ", header=T)

library(dplyr)

df1 %>%
  arrange(group, desc(id)) %>%                                  # order by group and id descending (this will help with counting the cards)
  left_join(df2 %>%                                             # join specific columns of df2 and add a flag to know that this row exists in df2
              select(id, group) %>%
              mutate(flag = 1), by=c("id","group")) %>%
  mutate(flag = ifelse(is.na(flag), 0, flag),                   # replace NA with 0
         flag2 = cumsum(flag)) %>%                              # this flag will create the groups we need to count cards
  group_by(group, flag2) %>%                                    # for each new group (we need both as the card counting will change when we have a row from df2, or if group changes)
  mutate(sum_cards = ifelse(flag == 1, 0, cumsum(cards))) %>%   # get cummulative sum of cards unless the flag = 1, where we need 0 cards
  ungroup() %>%                                                 # forget the grouping
  arrange(group, id) %>%                                        # back to original order
  mutate(points = goals - sum_cards) %>%                        # calculate points
  select(-flag, -flag2)                                         # remove flags

# # A tibble: 10 x 6
#      id goals cards group sum_cards points
#   <int> <int> <int> <int>     <dbl>  <dbl>
# 1     1     2     2     1         4     -2
# 2     2     3     2     1         0      3
# 3     3     4     2     1         5     -1
# 4     4     5     1     1         3      2
# 5     5     1     2     1         0      1
# 6     1     2     2     2         4     -2
# 7     2     3     2     2         0      3
# 8     3     4     2     2         0      4
# 9     4     5     1     3         3      2
# 10    5     1     2     3         0      1


问:
Excel Chart not binding while exporting from c#
I am doing a bulk excel export operation, In that excel i have a chart, the chart should bind based on exported data. But the data's inserted as string in excel. Its a dynamic exporting I have more than 10 sheets in one excel file, I am using one common method for all operation. So my entire data as been treated as string. I will not able to convert int because its dynamic.

```<code>        int rCnt;
        int cCnt;
        int rw = 0;
        int cl = 0;
                // Fill The Report Content Data Here
                rw = dtblData.Rows.Count;
                cl = dtblData.Columns.Count;
                string[,] data = new string[rw, cl];
                for (var row = 1; row <= rw; row++)
                {
                    for (var column = 1; column <= cl; column++)
                    {
                        data[row - 1, column - 1] = dtblData.Rows[row - 1][column - 1].ToString();
                    }
                }
                Excel.Range endRange = (Excel.Range)xlWorkSheet.Cells[rw + (startrange.Cells.Row - 1), cl + (startrange.Cells.Column - 1)];
                Excel.Range writeRange = xlWorkSheet.Range[startrange, endRange];
                writeRange.WrapText = true;
                writeRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                writeRange.Value2 = data;
                data = null;
                startrange = null;
                endRange = null;
                writeRange = null;
</code>```

答:
It happens because you are using array of type string and not int for the "Count" Column, one way is to use strongly typed objects (in the example it is a list of structs that represents you data object) to hold data and than populate it to the excel worksheet:

```<code>List<dataObj> data = new List<dataObj>();
for (var row = 1; row <= rw; row++)
{
    for (var column = 1; column <= cl; column++)
    {
        dataObj d = new dataObj();
        d.DeniedSourceIp = dtblData.Rows[row - 1]["YourColNameOfDeniedSourceIp"].ToString();
        d.Count = int.Parse(dtblData.Rows[row - 1]["YourColNameOfCount"].ToString());
        data.Add(d);
    }
}

struct dataObj
{
    public string DeniedSourceIp { get; set; }
    public int Count { get; set; }
}
</code>```

than loop trough the range and inject the data.

also, if your datatable is strongly typed why to use array / list of objects(?) you can inject the data directly from your datatable to excel worklsheet, you dont have to use Range you can do that:

```<code>xlWorkSheet.Cells[i, j] = "somevalue";
</code>```

Body:
I am doing a bulk excel export operation, In that excel i have a chart, the chart should bind based on exported data. But the data's inserted as string in excel. Its a dynamic exporting I have more than 10 sheets in one excel file, I am using one common method for all operation. So my entire data as been treated as string. I will not able to convert int because its dynamic.

        int rCnt;
        int cCnt;
        int rw = 0;
        int cl = 0;
                // Fill The Report Content Data Here
                rw = dtblData.Rows.Count;
                cl = dtblData.Columns.Count;
                string[,] data = new string[rw, cl];
                for (var row = 1; row <= rw; row++)
                {
                    for (var column = 1; column <= cl; column++)
                    {
                        data[row - 1, column - 1] = dtblData.Rows[row - 1][column - 1].ToString();
                    }
                }
                Excel.Range endRange = (Excel.Range)xlWorkSheet.Cells[rw + (startrange.Cells.Row - 1), cl + (startrange.Cells.Column - 1)];
                Excel.Range writeRange = xlWorkSheet.Range[startrange, endRange];
                writeRange.WrapText = true;
                writeRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                writeRange.Value2 = data;
                data = null;
                startrange = null;
                endRange = null;
                writeRange = null;

Body:
It happens because you are using array of type string and not int for the "Count" Column, one way is to use strongly typed objects (in the example it is a list of structs that represents you data object) to hold data and than populate it to the excel worksheet:

List<dataObj> data = new List<dataObj>();
for (var row = 1; row <= rw; row++)
{
    for (var column = 1; column <= cl; column++)
    {
        dataObj d = new dataObj();
        d.DeniedSourceIp = dtblData.Rows[row - 1]["YourColNameOfDeniedSourceIp"].ToString();
        d.Count = int.Parse(dtblData.Rows[row - 1]["YourColNameOfCount"].ToString());
        data.Add(d);
    }
}

struct dataObj
{
    public string DeniedSourceIp { get; set; }
    public int Count { get; set; }
}

than loop trough the range and inject the data.

also, if your datatable is strongly typed why to use array / list of objects(?) you can inject the data directly from your datatable to excel worklsheet, you dont have to use Range you can do that:

xlWorkSheet.Cells[i, j] = "somevalue";


问:
Can't seem to figure out why my index/match function does not work
I'm not an expert with Excel and I'm struggling with an index/match function with
multiple criteria and I don't know why it doesn't work.
Im created a small table to try the formula out(see picture)
The formula I entered is

```<code>=INDEX(A1:D9;MATCH(1;(A:A=C14)*(B:B=C15);0);4)
</code>```

the result is #N/A but it should be 8
Anyone knows what went wrong?

答: Because of the array argument within the MATCH function, this formula must be entered as an array formula by holding down ctrl+shift when you press enter.  Excel will then place braces {...} around the formula.

Body:
I'm not an expert with Excel and I'm struggling with an index/match function with
multiple criteria and I don't know why it doesn't work.
Im created a small table to try the formula out(see picture)
The formula I entered is

=INDEX(A1:D9;MATCH(1;(A:A=C14)*(B:B=C15);0);4)

the result is #N/A but it should be 8
Anyone knows what went wrong?


问:
What is the SVN term for deleting changes?
I made changes to a few files in SVN and I want to reverse the changes I made, i.e., have my version be the one in HEAD. What is the SVN term for that (so I can find it in tortoisesvn - I'm not sure if I should revert/clean up, etc.)?

答: svn revert should do the trick.

ContentLicense: CC BY-SA 2.5

Body: svn revert should do the trick.


问:
Css. Doesn't work text-overflow: ellipsis
I have something like this:

```<code><div>
  <span>
    text text text text text text
  </span>
</div>

div{
  width:100px;
  border: 1px solid black;
  line-height: 12px;
  height: 16px;
  position: relative;
  overflow:hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

span{
  position: absolute;
  overflow: hidden;
  text-overflow: ellipsis;
}
</code>```

And ellipsis doesn't work.
I do not necessarily need to use position: absolute, but as result I should have text, that doesn't expand div and truncated width ellipsis.

P.S. Width for div is included for sample, in reality div width is unknown.

答:
I have no idea why you need absolute position for the span tag, but it's doesn't matter here.

Span tag should have the "width" css-rule to solve your problem. For your example:

```<code>span {
   width:100%;
}
</code>```

So every time you want to use overflow:ellipsis option you have to specify the width for target element.

Body:
I have something like this:

    text text text text text text

div{
  width:100px;
  border: 1px solid black;
  line-height: 12px;
  height: 16px;
  position: relative;
  overflow:hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

span{
  position: absolute;
  overflow: hidden;
  text-overflow: ellipsis;
}

And ellipsis doesn't work.
I do not necessarily need to use position: absolute, but as result I should have text, that doesn't expand div and truncated width ellipsis.

P.S. Width for div is included for sample, in reality div width is unknown.

Body:
I have no idea why you need absolute position for the span tag, but it's doesn't matter here.

Span tag should have the "width" css-rule to solve your problem. For your example:

span {
   width:100%;
}

So every time you want to use overflow:ellipsis option you have to specify the width for target element.


问:
Hide exit and settings button for Google Cardboard Unity
We are using Unity to build a 360 video player which works on newer phones. We are experiencing a problem when building to older phones where we can see the exit and settings button in the top right and left corners. I am unable to find where GVR is calling the function to draw these buttons in order to disable to call.

Any help would be appreciated.

答:
Use 0.6 version GoogleSDK, with Unity 5.6. There are lot more options, if u build Cardboard app this is probably best sdk version for you (not for Daydream apps).

CardboardMain Setup SDK0.6


问:
How things looks a like behind Ajax calls
I just started learning Ajax, and most people as I saw working with Ajax (making Get and Post requests) like this:

```<code>$.ajax({
         method: "GET",
         url: "Customers/GetCustomerById",
         data: { customerId: Id }
        })
.done(function (response) {
//Do something here
});
</code>```

I red behind Ajax is XMLHttpRequest object, so does that means when code above is used, something like this is happening "behind the scene" :

```<code>httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function someMyFunction(){
    // Process the server response here.
};
http.open("GET", url+"?"+customerId, true);
</code>```

Is this true?

And is this second approach avoided today? Or it's still being used?
I'm just learning web and I don't know so that's reason why I'm asking..

And I'm wondering also why people are using this "first" approach, maybe they are not but I acctually saw it on many places...

Thanks a lot guys and cheers!

答:
"First" approaches uses a js library called jQuery. Not only is it easier to make ajax calls using jQuery (which is not the primary use of jQuery), but it also handles ajax calls across different browsers and mainly different versions of browsers. The XMLHTTPRequest object are supported by most browsers today. But that is not the case with older browsers.

Read this for more info.

It may be easier to code using jQuery but there are times when conflicts between files occuring because of jQuery (or some browsers may have issues with jQuery).
And in those situations developers may choose to implement and handle these and/or other scenarios themselves by coding in vanilla javascript. Choosing either approach is up to the developer.

Hope this answer helps.

Body:
I just started learning Ajax, and most people as I saw working with Ajax (making Get and Post requests) like this:

$.ajax({
         method: "GET",
         url: "Customers/GetCustomerById",
         data: { customerId: Id }
        })
.done(function (response) {
//Do something here
});

I red behind Ajax is XMLHttpRequest object, so does that means when code above is used, something like this is happening "behind the scene" :

httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function someMyFunction(){
    // Process the server response here.
};
http.open("GET", url+"?"+customerId, true);

Is this true?

And is this second approach avoided today? Or it's still being used?
I'm just learning web and I don't know so that's reason why I'm asking..

And I'm wondering also why people are using this "first" approach, maybe they are not but I acctually saw it on many places...

Thanks a lot guys and cheers!


问:
Converting hex into a string using 'sprintf'
I am trying to convert an array into hex and then put it into a string variable. In the following loop the printf works fine, but I can not use sprintf properly. How can I stuff the hex values into the array as ASCII?</p>

```<code>static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i], "%02x", digest[i]);  <--- DOES NOT WORK!
}
</code>```

答:
```<code>static unsigned char  digest[16];
static char hex_tmp[33];

for (i = 0; i < 16; i++)  {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i*2],"%02x", digest[i]);  <--- WORKS NOW
}
</code>```

Body:
I am trying to convert an array into hex and then put it into a string variable. In the following loop the printf works fine, but I can not use sprintf properly. How can I stuff the hex values into the array as ASCII?

static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i], "%02x", digest[i]);  <--- DOES NOT WORK!
}


问:
dictionary<int, guid> how to take value field that is Guid?
I was struggling a lot to get a Guid Value from Dictionary. Somebody please help me out.It is showing System.FormatException.Thank you advance.

My code:

```<code>Dictionary<int, Guid> products = productRepository.QueryNoTracking()
    .Select(x => new { x.ID, x.ProductKey })
    .ToDictionary(x => x.ProductKey, x => x.ID);
</code>```

From this I need to take productID from Position group Entity:-

```<code>var positionGroup = new Entities.PositionGroup();

positionGroup.ProductID = (Guid?)products
   .Where(s => s.Key == productKey)
   .Select(s => s.Value).ToString();
</code>```

答:
If you want help you really should post enough code that we can just copy-paste it into Visual Studio & fix it easily.

The limited info you've given makes it really time consuming to get a working sample for you.

In any case, this is more or less what the other comments are suggesting.

You will have to get it adjust for your needs because there's not enough info to give you working code.

```<code>var positionGroup = new Entities.PositionGroup()
{
    ProductID = productRepository.QueryNoTracking()
        .Where(x => x.ProductKey==productKey)
        .Select(x => x.ID})
}
</code>```

Body:
I was struggling a lot to get a Guid Value from Dictionary. Somebody please help me out.It is showing System.FormatException.Thank you advance.

My code:

Dictionary<int, Guid> products = productRepository.QueryNoTracking()
    .Select(x => new { x.ID, x.ProductKey })
    .ToDictionary(x => x.ProductKey, x => x.ID);

From this I need to take productID from Position group Entity:-

var positionGroup = new Entities.PositionGroup();

positionGroup.ProductID = (Guid?)products
   .Where(s => s.Key == productKey)
   .Select(s => s.Value).ToString();

Body:
If you want help you really should post enough code that we can just copy-paste it into Visual Studio & fix it easily.

The limited info you've given makes it really time consuming to get a working sample for you.

In any case, this is more or less what the other comments are suggesting.

You will have to get it adjust for your needs because there's not enough info to give you working code.

var positionGroup = new Entities.PositionGroup()
{
    ProductID = productRepository.QueryNoTracking()
        .Where(x => x.ProductKey==productKey)
        .Select(x => x.ID})
}


问:
Styling ng-bootstrap [ngb-tab] in Angular 4
Tried to change the background color of [ngb-tab] through the css file but it does not changed.
Perhaps different approach required?</p>

答:
You can try the nav-link and nav-link:hover properties

For example:

```<code>.nav-link{
  background-color: #333333;
  color: #fff;
}

.nav-link:hover{
  background-color: #72B626;
  color: #333333;
}
</code>```

Body:
You can try the nav-link and nav-link:hover properties

For example:

.nav-link{
  background-color: #333333;
  color: #fff;
}

.nav-link:hover{
  background-color: #72B626;
  color: #333333;
}


问:
How to compare bit mask?
I want to create function which return me true when first number (binary) contains in second number (binary):

```<code>a = '1100'
b = '0101'
</code>```

returns false but:

```<code>a = '0100'
b = '0101'
</code>```

returns true

How to do it?

答:
You can use a list comprehension like this:

```<code>a_list = '1100'
b_list = '0101'

# If a value in a_list is '1', remember if the corresponding value in b_list is '1', too
[b == '1' for a, b in zip(a_list, b_list) if a == '1']
>> [False, True]
</code>```

and then wrap it in a function whichever way you like:

```<code>def contains(a_list, b_list):
  comparison = [b == '1' for a, b in zip(a_list, b_list) if a == '1']
  return all(comparison)

contains('1100', '0101')
>> False
contains('0100', '0101')
>> True
</code>```

Title: How to compare bit mask?

Body:
I want to create function which return me true when first number (binary) contains in second number (binary):

a = '1100'
b = '0101'

returns false but:

a = '0100'
b = '0101'

returns true

How to do it?

Body:
You can use a list comprehension like this:

a_list = '1100'
b_list = '0101'

# If a value in a_list is '1', remember if the corresponding value in b_list is '1', too
[b == '1' for a, b in zip(a_list, b_list) if a == '1']
>> [False, True]

and then wrap it in a function whichever way you like:

def contains(a_list, b_list):
  comparison = [b == '1' for a, b in zip(a_list, b_list) if a == '1']
  return all(comparison)

contains('1100', '0101')
>> False
contains('0100', '0101')
>> True


问:
What is the alternative to condition form of depends_on in docker-compose Version 3?
docker-compose 2.1 offers the nice feature to specify a condition with depends_on. The current docker-compose documentation states:

Version 3 no longer supports the condition form of depends_on.

Unfortunately the documentation does not explain, why the condition form was removed and is lacking any specific recommondation on how to implement that behaviour using V3 upwards.

答: There's been a move away from specifying container dependencies in compose. They're only valid at startup time and don't work when dependent containers are restarted at run time. Instead, each container should include mechanism to retry to reconnect to dependent services when the connection is dropped. Many libraries to connect to databases or REST API services have configurable built-in retries. I'd look into that. It is needed for production code anyway.</p>


问:
Html dom add class to all elements
I'm trying to addclass to all elements at once using html dom. // No jquery

Here is what i tryed:

```<code>document.getElementsByTagName("*").classList.add('addedclassname');
</code>```

I guess i could not select(get) all elements. Because this,

```<code>document.getElementById("id").classList.add('addedclassname');
</code>```

was working.

答:
You just need to iterate each element like this    </p>

```<code>    var els = document.getElementsByTagName("*");
    for(var i = 0, all = els.length; i < all; i++){
         els[i].classList.add('addedclassname');
     }
</code>```

Title: Html dom add class to all elements

Body:
I'm trying to addclass to all elements at once using html dom. // No jquery

Here is what i tryed:

document.getElementsByTagName("*").classList.add('addedclassname');

I guess i could not select(get) all elements. Because this,

document.getElementById("id").classList.add('addedclassname');

was working.

Body:
You just need to iterate each element like this

    var els = document.getElementsByTagName("*");
    for(var i = 0, all = els.length; i < all; i++){
         els[i].classList.add('addedclassname');
     }


问:
Node.js binary to PDF
I have got a express server, which creates a pdf file.

I am trying to send this file to the client:

const fs = require('fs');

function download(req, res) {
  var filePath = '/../../myPdf.pdf';

  fs.readFile(__dirname + filePath, function(err, data) {
    if (err) throw new Error(err);
    console.log('yeyy, no errors :)');

    if (!data) throw new Error('Expected data, but got', data);
    console.log('got data', data);

    res.contentType('application/pdf');
    res.send(data);
  });
}```
</div>
</div>
</p>

<p>On the client I want to download it:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  _handleDownloadAll = async () => {
    console.log('handle download all');
    const response = await request.get(
      `http://localhost:3000/download?accessToken=${localStorage.getItem(
        'accessToken'
      )}`
    );

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

I recieve an body.text like

%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Producer (��Qt 5.5.1)↵```
</div>
</div>
</p>

<p>but I can't achieve a download. </p>

<p>How can I create a PDF from the data OR directly download it from the server?</p>

<p><strong>I've got it working:</strong>
The answer was pretty simple. I just let the browser handle the download with an html anchor tag:
server:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function download(req, res) {
  const { creditor } = req.query;
  const filePath =  `/../../${creditor}.pdf`;

  res.download(__dirname + filePath);
}</code>```

client:

Download```

答:
readFile returns a Buffer which is a wrapper around bytes. You're sending Buffer back to the client which is logging them to the console.

The body.text you see is to be expected.

You will need to write these bytes to a file using fs.writeFile or similar. Here's an example:

```<code>_handleDownloadAll = async () => {
  console.log('handle download all');
  const response = await request.get(
    `http://localhost:3000/download?accessToken=${localStorage.getItem(
      'accessToken'
    )}`
  );

  // load your response data into a Buffer
  let buffer = Buffer.from(response.body.text)

  // open the file in writing mode
  fs.open('/path/to/my/file.pdf', 'w', function(err, fd) {
    if (err) {
        throw 'could not open file: ' + err;
    }

    // write the contents of the buffer
    fs.write(fd, buffer, 0, buffer.length, null, function(err) {
      if (err) {
        throw 'error writing file: ' + err;
      }
      fs.close(fd, function() {
          console.log('file written successfully');
      });
    });
  });
};
</code>```

You may need to experiment with the buffer encoding, it defaults to utf8.

Read this!

The other option you may want to consider is generating the PDF on the server and simply sending the client a link to where it can download this.

Title: Node.js binary to PDF

Body:
I have got a express server, which creates a pdf file.

I am trying to send this file to the client:

const fs = require('fs');

function download(req, res) {
  var filePath = '/../../myPdf.pdf';

  fs.readFile(__dirname + filePath, function(err, data) {
    if (err) throw new Error(err);
    console.log('yeyy, no errors :)');

    if (!data) throw new Error('Expected data, but got', data);
    console.log('got data', data);

    res.contentType('application/pdf');
    res.send(data);
  });
}

On the client I want to download it:

  _handleDownloadAll = async () => {
    console.log('handle download all');
    const response = await request.get(
      `http://localhost:3000/download?accessToken=${localStorage.getItem(
        'accessToken'
      )}`
    );

    console.log(response);
  };

I recieve an body.text like

%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Producer (��Qt 5.5.1)↵

but I can't achieve a download.

How can I create a PDF from the data OR directly download it from the server?

I've got it working:
The answer was pretty simple. I just let the browser handle the download with an html anchor tag:
server:

function download(req, res) {
  const { creditor } = req.query;
  const filePath =  `/../../${creditor}.pdf`;

  res.download(__dirname + filePath);
}

client:

<a href{`${BASE_URL}?accessToken=${accessToken}&creditor=${creditorId}`} download>Download

Body:
readFile returns a Buffer which is a wrapper around bytes. You're sending Buffer back to the client which is logging them to the console.

The body.text you see is to be expected.

You will need to write these bytes to a file using fs.writeFile or similar. Here's an example:

_handleDownloadAll = async () => {
  console.log('handle download all');
  const response = await request.get(
    `http://localhost:3000/download?accessToken=${localStorage.getItem(
      'accessToken'
    )}`
  );

  // load your response data into a Buffer
  let buffer = Buffer.from(response.body.text)

  // open the file in writing mode
  fs.open('/path/to/my/file.pdf', 'w', function(err, fd) {
    if (err) {
        throw 'could not open file: ' + err;
    }

    // write the contents of the buffer
    fs.write(fd, buffer, 0, buffer.length, null, function(err) {
      if (err) {
        throw 'error writing file: ' + err;
      }
      fs.close(fd, function() {
          console.log('file written successfully');
      });
    });
  });
};

You may need to experiment with the buffer encoding, it defaults to utf8.

Read this!

The other option you may want to consider is generating the PDF on the server and simply sending the client a link to where it can download this.


问:
Comma is causing unwanted string split
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:

```<code>public List getAnswerStringEdit() {
        return answer_edit;
    }
</code>```

I save it as so:

```<code>editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
</code>```

Then retrieve it here:

```<code>String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
        answerString = answerString.substring(1, answerString.length() - 1).trim();
        String[] array = answerString.split(",");
</code>```

Finally, I access the array as so:

```<code>et_answer1_edit.append(array[0]);
</code>```

My problem is this - Say I add a questions which has a comma in the middle of it, like -

Question 1- "Why is this broke, I don't know?"

Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:

"Why is this broke, I don't know?"

However, instead I am getting in position 0:

Why is this broke - then position 1 as: I don't know

I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.

The retrieved JSON is as follows:

```<code>{
    "result": "success",
    "message": "Answer Has Been Selected",
    "answer": {
        "answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
    }
}
</code>```

Any help/advice that can help me to understand what is causing this, would be really appreciated.

答:
Dont split the string using ',' use this</p>

```<code>JSONObject jsonObject = new JSONObject(answerString );
            JSONArray jsonArray = jsonObject.getJSONObject("answer").getJSONArray("answer_edit");
            Log.e("Json Array elements are","First Element : "+jsonArray.get(0)+"\nSecond Element : "+jsonArray.get(1));
            String QuestionString1 = jsonArray.get(0).toString();
            String QuestionString2 = jsonArray.get(1).toString();
</code>```

Title: Comma is causing unwanted string split

Body:
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:

public List getAnswerStringEdit() {
        return answer_edit;
    }

I save it as so:

editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());

Then retrieve it here:

String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
        answerString = answerString.substring(1, answerString.length() - 1).trim();
        String[] array = answerString.split(",");

Finally, I access the array as so:

et_answer1_edit.append(array[0]);

My problem is this - Say I add a questions which has a comma in the middle of it, like -

Question 1- "Why is this broke, I don't know?"

Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:

"Why is this broke, I don't know?"

However, instead I am getting in position 0:

Why is this broke - then position 1 as: I don't know

I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.

The retrieved JSON is as follows:

{
    "result": "success",
    "message": "Answer Has Been Selected",
    "answer": {
        "answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
    }
}

Any help/advice that can help me to understand what is causing this, would be really appreciated.

Body:
Dont split the string using ',' use this

JSONObject jsonObject = new JSONObject(answerString );
            JSONArray jsonArray = jsonObject.getJSONObject("answer").getJSONArray("answer_edit");
            Log.e("Json Array elements are","First Element : "+jsonArray.get(0)+"\nSecond Element : "+jsonArray.get(1));
            String QuestionString1 = jsonArray.get(0).toString();
            String QuestionString2 = jsonArray.get(1).toString();


问:
Exclude _id attribute from mongodb result including the subdocuments in mongoose
The database has a lot of nesting. I can exclude _id for one layer but how to do that for the whole of the document? </p>

答:
You can try the $project for this type of scenarios.

For Example, consider the document:

```<code>{
  "_id" : 1,
  title: "abc123",
  isbn: "0001122223334",
  author: { last: "zzz", first: "aaa" },
  copies: 5
}
</code>```

The following query will exclude the _id from the document

```<code>db.books.aggregate( [ { $project : { _id: 0, title : 1 , author : 1 } } ] )
</code>```

You can refer the documentation here

Body:
You can try the $project for this type of scenarios.

For Example, consider the document:

{
  "_id" : 1,
  title: "abc123",
  isbn: "0001122223334",
  author: { last: "zzz", first: "aaa" },
  copies: 5
}

The following query will exclude the _id from the document

db.books.aggregate( [ { $project : { _id: 0, title : 1 , author : 1 } } ] )

You can refer the documentation here


答:
You should iterate them;</p>

```<code>var elementList = document.getElementsByTagName("*");
for(var i = 0; i < elementList.length; i++)
{
    elementList[i].classList.add('addedclassname');
}
</code>```

Title: Html dom add class to all elements

Body:
You should iterate them;

var elementList = document.getElementsByTagName("*");
for(var i = 0; i < elementList.length; i++)
{
    elementList[i].classList.add('addedclassname');
}


问:
datatable dynamic formation from javascript

I am trying to draw a table dynamically from javascript, i could able to do it successfully, but when i want to navigate to pages via "lengthMenu" and next or previous, it is not working.

As well, when i try searching also it is not working.

```<code>$('#step5ResponseTable').DataTable( {
    "lengthMenu": [[1, 2], [1, 2]],
    columnDefs: [ {
         targets:   0
    } ]
} );

$("#step5ResponseTable").empty();
                         var th = '<thead>' +
                         '<tr>'+
                         '<th> Device Name </th>'+
                         '<th> Status </th>'+
                         '<th> Reason </th>'+
                         '</tr>'+
                         '</thead>';
                         $('#step5ResponseTable').append(th);
                        for(var i=0; i < aa.length; i++){
                            var response = callAPI(JSON.stringify(aa[i]), i);
                                    var tr = '<tr>'+
                                     '<td>'+'Device'+'</td>'+
                                     '<td>'+'Success'+'</td>'+
                                     '<td>'+'HHH'+i+'</td>'+
                                     '</tr>';
                                      $('#step5ResponseTable').append(tr);
                        }

<table class="display" cellspacing="0" id="step5ResponseTable">
                                        </table>
</code>```

version of jquery.dataTables.min.js -> 1.10.13

jquery.dataTables.min.css

When i select 1 or 2 record per page, it does not work properly

答:
As per the above comment from @Jerodev, i got it working as follows

```<code>$("#step5ResponseTable").empty();
                         var th = '<thead>' +
                         '<tr>'+
                         '<th> Device Name </th>'+
                         '<th> Status </th>'+
                         '<th> Reason </th>'+
                         '</tr>'+
                         '</thead>';
                         $('#step5ResponseTable').append(th);
                        for(var i=0; i < aa.length; i++){
                            var response = callAPI(JSON.stringify(aa[i]), i);
                                    var tr = '<tr>'+
                                     '<td>'+'Device'+'</td>'+
                                     '<td>'+'Success'+'</td>'+
                                     '<td>'+'HHH'+i+'</td>'+
                                     '</tr>';
                                      $('#step5ResponseTable').append(tr);
                        }
</code>```

// after this i initialized the datatable

```<code>$('#step5ResponseTable').DataTable( {
    "lengthMenu": [[1, 2], [1, 2]],
    columnDefs: [ {
         targets:   0
    } ]
} );
</code>```

Body:
I am trying to draw a table dynamically from javascript, i could able to do it successfully, but when i want to navigate to pages via "lengthMenu" and next or previous, it is not working.

As well, when i try searching also it is not working.

$('#step5ResponseTable').DataTable( {
    "lengthMenu": [[1, 2], [1, 2]],
    columnDefs: [ {
         targets:   0
    } ]
} );

$("#step5ResponseTable").empty();
                         var th = '
' +
                         '
'+
                         ' Device Name 	'+
                         ' Status 	'+
                         ' Reason 	'+
                         '
'+
                         '
';
                         $('#step5ResponseTable').append(th);
                        for(var i=0; i < aa.length; i++){
                            var response = callAPI(JSON.stringify(aa[i]), i);
                                    var tr = '
'+
                                     ''+'Device'+'	'+
                                     ''+'Success'+'	'+
                                     ''+'HHH'+i+'	'+
                                     '
';
                                      $('#step5ResponseTable').append(tr);
                        }

version of jquery.dataTables.min.js -> 1.10.13

jquery.dataTables.min.css

When i select 1 or 2 record per page, it does not work properly

Body:
As per the above comment from @Jerodev, i got it working as follows

$("#step5ResponseTable").empty();
                         var th = '<thead>' +
                         '<tr>'+
                         '<th> Device Name </th>'+
                         '<th> Status </th>'+
                         '<th> Reason </th>'+
                         '</tr>'+
                         '</thead>';
                         $('#step5ResponseTable').append(th);
                        for(var i=0; i < aa.length; i++){
                            var response = callAPI(JSON.stringify(aa[i]), i);
                                    var tr = '<tr>'+
                                     '<td>'+'Device'+'</td>'+
                                     '<td>'+'Success'+'</td>'+
                                     '<td>'+'HHH'+i+'</td>'+
                                     '</tr>';
                                      $('#step5ResponseTable').append(tr);
                        }

// after this i initialized the datatable

$('#step5ResponseTable').DataTable( {
    "lengthMenu": [[1, 2], [1, 2]],
    columnDefs: [ {
         targets:   0
    } ]
} );


问:
Database Design - Storing n weeks data in database and update each week
I want to show last four Sundays temperature for particular city, I need to update the database weekly (on Sundays)

Database Design 1

```<code>city_id     temp_pre_sunday1   temp_pre_sunday2   temp_pre_sunday3  temp_pre_sunday4
1                  24.3              35.2           24.4             28.0
2                  4.0                2.0           6.0              7.0

 .
2000
</code>```

I can update the database each Sunday. Is this good database design?

Database Design 2

```<code> city_id      temp   date
   1          24.3    2017-12-03
   1          35.2    2017-11-26
   1          24.4    2017-11-19
   1          28.0    2017-11-12
   2          4.0     2017-12-03
   2          2.0     2017-11-26
   2          6.0     2017-11-19
   2          7.0     2017-11-12
   .
   .
</code>```

I need only four Sundays not more than that.

I think first method is better, because  that way for 2000 cities I will have 2000 rows and 5 columns, in the second method I will have 8000 rows and 3 columns,

But in first method I need to update all the four columns,but in the second method I can maybe delete and insert one row.

Which is the better database design?

答:
The way to evaluate "best" is complicated. But "number of rows" is almost never a problem in relational databases - they are specifically designed to handle huge numbers of rows.

A much more useful way to think about it is "what are the common things I want to do with the data".

I'm guessing you have a few use cases.

The first is "record new measurements". As you say, that's a little painful in design one.

The second is "find or report on measurements".

In design one, it's easy to answer questions like "what was the temperature in city x on the last Sunday?". But "what was the coldest temperature in the last 3 weeks" is harder. Or "what was the difference between the highest and lowest temperatures for city X?". If the number of weeks is passed in as a parameter, you end up constructing awkward queries. In design two, all of those queries are pretty straightforward.

That alone suggests that design 2 is better.

But as commenters have noted, requirements for databases tend to change. Most people think you have a good design if you can accommodate those changes by adding data, rather than changing your schema. So, if you need to store data for more than 4 Sundays, design 2 requires a schema change; design 1 doesn't. If you have to record data other than temperature, in design 1 you suddenly have multiple columns for each week; in design 2, you can simply add a "measurement_type" column (a much smaller change). So, it's likely that design 2 is more flexible in the face of change.

ContentLicense: CC BY-SA 4.0

Body:
I want to show last four Sundays temperature for particular city, I need to update the database weekly (on Sundays)

Database Design 1

city_id     temp_pre_sunday1   temp_pre_sunday2   temp_pre_sunday3  temp_pre_sunday4
1                  24.3              35.2           24.4             28.0
2                  4.0                2.0           6.0              7.0

 .
2000

I can update the database each Sunday. Is this good database design?

Database Design 2

 city_id      temp   date
   1          24.3    2017-12-03
   1          35.2    2017-11-26
   1          24.4    2017-11-19
   1          28.0    2017-11-12
   2          4.0     2017-12-03
   2          2.0     2017-11-26
   2          6.0     2017-11-19
   2          7.0     2017-11-12
   .
   .

I need only four Sundays not more than that.

I think first method is better, because  that way for 2000 cities I will have 2000 rows and 5 columns, in the second method I will have 8000 rows and 3 columns,

But in first method I need to update all the four columns,but in the second method I can maybe delete and insert one row.

Which is the better database design?


问:
Making (a, a) a Functor
How can I make (a, a) a Functor without resorting to a newtype?

Basically I want it to work like this:

```<code>instance Functor (a, a) where
  fmap f (x, y) = (f x, f y)
</code>```

But of course that's not a legal way to express it:

```<code>Kind mis-match
The first argument of `Functor' should have kind `* -> *',
but `(a, a)' has kind `*'
In the instance declaration for `Functor (a, a)'
</code>```

What I really want is a type-level function like this: \a -> (a, a) (invalid syntax). So a type alias, perhaps?

```<code>type V2 a = (a, a)
instance Functor V2 where
    fmap f (x, y) = (f x, f y)
</code>```

I would think this would work, but it doesn't. First I get this complaint:

```<code>Illegal instance declaration for `Functor V2'
(All instance types must be of the form (T t1 ... tn)
 where T is not a synonym.
 Use -XTypeSynonymInstances if you want to disable this.)
In the instance declaration for `Functor V2'
</code>```

If I follow the advice and add the TypeSynonymInstances extension, I get a new error:

```<code>Type synonym `V2' should have 1 argument, but has been given 0
In the instance declaration for `Functor V2'
</code>```

Well, duh, that's the point! V2 has kind * -> * which is what is required of a Functor instance. Well, ok, I can use a newtype like this:

```<code>newtype V2 a = V2 (a, a)
instance Functor V2 where
  fmap f (V2 (x, y)) = V2 (f x, f y)
</code>```

But now I've got to sprinkle V2s liberally throughout my code instead of just being able to deal with simple tuples, which kind of defeats the point of making it a Functor; at that point I might as well make my own function vmap :: (a -> b) -> (a, a) -> (b, b).

So is there any way to do this nicely, i.e. without a newtype?

答:
With singletons you can define a Functor type class for defunctionalized symbols (Type ~> Type instead of Type -> Type)

```<code>{-# Language ExplicitNamespaces, TypeApplications, TypeOperators, KindSignatures, ScopedTypeVariables, DataKinds, TypeInType, TypeFamilies, AllowAmbiguousTypes, InstanceSigs #-}

import Data.Kind (Type)
import Data.Singletons (type (~>), Apply)

class Functor' (f :: Type ~> Type) where
  fmap' :: (a -> a') -> (Apply f a -> Apply f a')

data Dup :: Type ~> Type

type instance Dup `Apply` a = (a, a)

instance Functor' Dup where
  fmap' :: (a -> a') -> ((a, a) -> (a', a'))
  fmap' f (a1, a2) = (f a1, f a2)
</code>```

This gives you a Prelude.Functor instance automatically

```<code>newtype f $ a = App (Apply f a)

instance Functor' f => Functor (($) f) where
  fmap :: (a -> a') -> (f $ a -> f $ a')
  fmap f (App fa) = App (fmap' @f f fa)
</code>```

Title: Making (a, a) a Functor

Body:
How can I make (a, a) a Functor without resorting to a newtype?

Basically I want it to work like this:

instance Functor (a, a) where
  fmap f (x, y) = (f x, f y)

But of course that's not a legal way to express it:

Kind mis-match
The first argument of `Functor' should have kind `* -> *',
but `(a, a)' has kind `*'
In the instance declaration for `Functor (a, a)'

What I really want is a type-level function like this: \a -> (a, a) (invalid syntax). So a type alias, perhaps?

type V2 a = (a, a)
instance Functor V2 where
    fmap f (x, y) = (f x, f y)

I would think this would work, but it doesn't. First I get this complaint:

Illegal instance declaration for `Functor V2'
(All instance types must be of the form (T t1 ... tn)
 where T is not a synonym.
 Use -XTypeSynonymInstances if you want to disable this.)
In the instance declaration for `Functor V2'

If I follow the advice and add the TypeSynonymInstances extension, I get a new error:

Type synonym `V2' should have 1 argument, but has been given 0
In the instance declaration for `Functor V2'

Well, duh, that's the point! V2 has kind * -> * which is what is required of a Functor instance. Well, ok, I can use a newtype like this:

newtype V2 a = V2 (a, a)
instance Functor V2 where
  fmap f (V2 (x, y)) = V2 (f x, f y)

But now I've got to sprinkle V2s liberally throughout my code instead of just being able to deal with simple tuples, which kind of defeats the point of making it a Functor; at that point I might as well make my own function vmap :: (a -> b) -> (a, a) -> (b, b).

So is there any way to do this nicely, i.e. without a newtype?

Body:
With singletons you can define a Functor type class for defunctionalized symbols (Type ~> Type instead of Type -> Type)

{-# Language ExplicitNamespaces, TypeApplications, TypeOperators, KindSignatures, ScopedTypeVariables, DataKinds, TypeInType, TypeFamilies, AllowAmbiguousTypes, InstanceSigs #-}

import Data.Kind (Type)
import Data.Singletons (type (~>), Apply)

class Functor' (f :: Type ~> Type) where
  fmap' :: (a -> a') -> (Apply f a -> Apply f a')

data Dup :: Type ~> Type

type instance Dup `Apply` a = (a, a)

instance Functor' Dup where
  fmap' :: (a -> a') -> ((a, a) -> (a', a'))
  fmap' f (a1, a2) = (f a1, f a2)

This gives you a Prelude.Functor instance automatically

newtype f $ a = App (Apply f a)

instance Functor' f => Functor (($) f) where
  fmap :: (a -> a') -> (f $ a -> f $ a')
  fmap f (App fa) = App (fmap' @f f fa)


问:
Searching in the column of mysql database table, having the encoded html along with text. I need to search only text in this column using sphinx
I have a table in the database having the column question_description. I have indexed the column in sphinx, and getting the results successfully. Now problem is that the column contains encoded html along with text, and I want from sphinx to  only search in text ignoring the encoded html. How can i configure this requirement.  Thanks!

答:
Not totally sure what you mean by 'encoded' html, does that mean gziped or something?

But do see html_strip:
http://sphinxsearch.com/docs/current.html#conf-html-strip

HTML tags are removed, their contents (i.e., everything between
 and
) are left intact by default.

Edited to add (too long for a comment!):

Eek, yes, ok you do have 'encoded' HTML (in this case using html entities) - sphinx DOESN'T have explicit support for decoding that.

It can 'strip' down plain html, not encoded html. Frankly encoding it like that seems to add lots of extra overhead (your real html entities, will then be DOUBLE encoded) and means you always need to decode it when 'using' the HTML (be that outputting it in a webpage, or to sphinx etc).

This would have to use XMLPipe2 index (or other pipe index) to decode the text for indexing, (will be quite complicated as will have to decode the htmlspecialchars, but then re-encode it as XML)

or maybe find a MySQL function to decode it is there a mysql function to decode html entities? - during the sql_query

Second Edit to add:

Actuilly checking http://php.net/manual/en/function.htmlspecialchars.php - it seems the htmlspecialchars only really does 5 transformations.

That might be preactical to fix with regexp_filter - you could replace the entities back with their unencoded version.

the Regexp filters are applied BEFORE html processing...
http://sphinxsearch.com/blog/2014/11/26/sphinx-text-processing-pipeline/

http://sphinxsearch.com/docs/current.html#conf-regexp-filter

```<code>regexp_filter = " => "
</code>```

... etc

```<code>regexp_filter = & => &
</code>```

Body:
Not totally sure what you mean by 'encoded' html, does that mean gziped or something?

But do see html_strip:
http://sphinxsearch.com/docs/current.html#conf-html-strip

HTML tags are removed, their contents (i.e., everything between <P> and </P>) are left intact by default.

Edited to add (too long for a comment!):

Eek, yes, ok you do have 'encoded' HTML (in this case using html entities) - sphinx DOESN'T have explicit support for decoding that.

It can 'strip' down plain html, not encoded html. Frankly encoding it like that seems to add lots of extra overhead (your real html entities, will then be DOUBLE encoded) and means you always need to decode it when 'using' the HTML (be that outputting it in a webpage, or to sphinx etc).

This would have to use XMLPipe2 index (or other pipe index) to decode the text for indexing, (will be quite complicated as will have to decode the htmlspecialchars, but then re-encode it as XML)

or maybe find a MySQL function to decode it is there a mysql function to decode html entities? - during the sql_query

Second Edit to add:

Actuilly checking http://php.net/manual/en/function.htmlspecialchars.php - it seems the htmlspecialchars only really does 5 transformations.

That might be preactical to fix with regexp_filter - you could replace the entities back with their unencoded version.

the Regexp filters are applied BEFORE html processing...
http://sphinxsearch.com/blog/2014/11/26/sphinx-text-processing-pipeline/

http://sphinxsearch.com/docs/current.html#conf-regexp-filter

regexp_filter = &quot; => "

... etc

regexp_filter = &amp; => &


问:
What is the SVN term for deleting changes?
I made changes to a few files in SVN and I want to reverse the changes I made, i.e., have my version be the one in HEAD. What is the SVN term for that (so I can find it in tortoisesvn - I'm not sure if I should revert/clean up, etc.)?

答:
i believe it's </p>

```<code>svn revert filename
</code>```

Body:
i believe it's

svn revert filename


问:
get value from key in sessionStorage javascript
Is it possible to check if a specific value exists in a key in sessionStorage?

Let's say that I have a key that is named "item" and I got digits in that key. I want to check if the digit "5" exists in item.

I have tested to write like this:

```<code>  if(sessionStorage.getItem("item") == "5");
</code>```

but It doesn't respond as i want.

Is there another way I can check if the digit 5 exists in item?

答:
sessionStorage is returning the value as a string and not as an object array. So you can first use split to get the array you set in initially.

So whether you do this:

```<code>sessionStorage.setItem("item", [1,2,3])
</code>```

or this:

```<code>sessionStorage.setItem("item", ["1","2","3"])
</code>```

sessionStorage.getItem("item") will return this: "1,2,3" (string)

After splitting your string,

You can use indexOf,

if(sessionStorage.getItem("item").split(",").indexOf("5") > -1){
  //do your computation
}
```

<ul>
<li>You can also use includes</li>
</ul>

<pre class="lang-js prettyprint-override"><code>if(sessionStorage.getItem("item").split(",").includes("5")){
  //do your computation
}
</code>```

Body:
Is it possible to check if a specific value exists in a key in sessionStorage?

Let's say that I have a key that is named "item" and I got digits in that key. I want to check if the digit "5" exists in item.

I have tested to write like this:

  if(sessionStorage.getItem("item") == "5");

but It doesn't respond as i want.

Is there another way I can check if the digit 5 exists in item?

Body:
sessionStorage is returning the value as a string and not as an object array. So you can first use split to get the array you set in initially.

So whether you do this:

sessionStorage.setItem("item", [1,2,3])

or this:

sessionStorage.setItem("item", ["1","2","3"])

sessionStorage.getItem("item") will return this: "1,2,3" (string)

After splitting your string,

You can use indexOf,

if(sessionStorage.getItem("item").split(",").indexOf("5") > -1){
  //do your computation
}

You can also use includes

if(sessionStorage.getItem("item").split(",").includes("5")){
  //do your computation
}


问:
Can not give 100% height to transformed image?
I am unable to apply the height of a transformed element to it's parent.
I have a bootstrap modal in which I am rendering an image that may be very large in size or may be small the size of the image is dynamic. So what I want is that whatever the size of image is the modal's size should also be same as the transformed Image.

I tried giving it a max-height: 100% but it does not works.
If I give it max-height in px then modal height will always cut if the height of my image is greater than my max-height so suggest me what to do.

Following is JSFiddle which is demonstrating my problem.

https://jsfiddle.net/harish_soni/6r9p07sg/

When you will open the modal the height of the modal is very large and the image inside it it much smaller after tranformation.

Any help would be appreciated.

HTML::

  Bootstrap Example

```<code><body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <img class="modal-image" src="http://canacopegdl.com/images/example/example-1.jpg" />
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</code>```

CSS:

```<code>.modal-image{
    transform: scale(0.3) translateX(-50%);
    transform-origin: left top;
    position: relative;
    left: 50%;
}
</code>```

答:
try this, just remove css from your code, and add img-responsive to the image tag, then it works fine. any size of the image works fine here.

I added three types images to show height as u mentioned.

<!DOCTYPE html>
  <title>Bootstrap Example</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>

Modal Example

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal2">Open Modal 2</button>
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal3">Open Modal 3</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

```

Body:
I am unable to apply the height of a transformed element to it's parent.
I have a bootstrap modal in which I am rendering an image that may be very large in size or may be small the size of the image is dynamic. So what I want is that whatever the size of image is the modal's size should also be same as the transformed Image.

I tried giving it a max-height: 100% but it does not works.
If I give it max-height in px then modal height will always cut if the height of my image is greater than my max-height so suggest me what to do.

Following is JSFiddle which is demonstrating my problem.

https://jsfiddle.net/harish_soni/6r9p07sg/

When you will open the modal the height of the modal is very large and the image inside it it much smaller after tranformation.

Any help would be appreciated.

HTML::

  Bootstrap Example

Modal Example

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

CSS:

.modal-image{
    transform: scale(0.3) translateX(-50%);
    transform-origin: left top;
    position: relative;
    left: 50%;
}

Body:
try this, just remove css from your code, and add img-responsive to the image tag, then it works fine. any size of the image works fine here.

I added three types images to show height as u mentioned.

<!DOCTYPE html>
  <title>Bootstrap Example</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal2">Open Modal 2</button>
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal3">Open Modal 3</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body" style="text-align:center;">
          <img class="modal-image center-block img-responsive" src="http://canacopegdl.com/images/example/example-1.jpg" />
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

  <!-- Modal -->
  <div class="modal fade" id="myModal2" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body" style="text-align:center;">
          <img class="modal-image center-block img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/8/85/Codero_Hosting_Logo_%28100px%29.png" />
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

  <!-- Modal -->
  <div class="modal fade" id="myModal3" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body" style="text-align:center;">
          <img class="modal-image center-block img-responsive" src="https://i.pinimg.com/736x/13/4f/d3/134fd3ea8c942b853f0735fc84f0297b--pink-flamingos-beautiful-creatures.jpg" />
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>


问:
React 16 input type=checkbox not rendered correctly if nested in html a-tag
I have a peculiar problem with using a html a-tag with input type=checkbox  from React. The thing is that if I click directly on the checkbox and not the a-tag the checkbox will not re-render correctly but my state has updated.

Example: Given the code below I render the component and click directly on the checkbox. In this case showMap will be set to false since we set it to true in the constructor but the checkbox will still be checked in the html view. If I however click on the a-tag but not directly on the checkbox both the state showMap is updated correctly as well as the view.

I can make it work by not calling event.preventDefault(); in toggleCheckbox but if I do that the app will scroll to the top of the page if I click on the a-tag.

Example:

https://codesandbox.io/s/w2x8vqq8xl

Code:

```<code>import React from "react";
import { render } from "react-dom";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center",
  //marginTop: "1000px"
};

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMap: true
    };
  }

  toggleCheckbox = event => {
    this.setState({ showMap: !this.state.showMap });
    event.preventDefault();
  };

  render() {
    return (
      <div>
        <h1>{this.state.showMap ? "Show" : "hide"}</h1>
        <a href="#" role="button" onClick={this.toggleCheckbox}>
          <input
            type="checkbox"
            title="test"
            name="showMap"
            checked={this.state.showMap}
            readOnly
          />
          Show map
        </a>
      </div>

    );
  }
}

const App = () => (
    <div style={styles}>
      <Menu />
    </div>
);

render(<App />, document.getElementById("root"));
</code>```

Update:

Created an issue with React.

https://github.com/facebook/react/issues/11539

答:
This appears to be browser native behavior:

HTML:

```<code><a href="#" role="button" id="anchor">
  <input id="input" type="checkbox" title="test" name="showMap" readonly /> Clicking this text toggles the checkbox
</a>

<hr />
<label><input id="prevent" type="checkbox" /> Prevent Default</label>

<p>With prevent default on, clicking the checkbox does not toggle it. Only clicking the text</p>
</code>```

CSS:

```<code>body {
  font-size: 15px;
  line-height: 1.5;
  padding: 20px;
}
</code>```

JS:

```<code>var anchor = document.getElementById('anchor')
var prevent = document.getElementById('prevent')
var input = document.getElementById('input')
var toggled = false

anchor.addEventListener('click', function (event) {
  if (prevent.checked) {
    event.preventDefault()
  }

  toggled = !toggled

  input.checked = toggled
})
</code>```

https://codepen.io/nhunzaker/pen/WXONQK

https://github.com/facebook/react/issues/11539#issuecomment-343914330

Body:
I have a peculiar problem with using a html a-tag with input type=checkbox  from React. The thing is that if I click directly on the checkbox and not the a-tag the checkbox will not re-render correctly but my state has updated.

Example: Given the code below I render the component and click directly on the checkbox. In this case showMap will be set to false since we set it to true in the constructor but the checkbox will still be checked in the html view. If I however click on the a-tag but not directly on the checkbox both the state showMap is updated correctly as well as the view.

I can make it work by not calling event.preventDefault(); in toggleCheckbox but if I do that the app will scroll to the top of the page if I click on the a-tag.

Example:

https://codesandbox.io/s/w2x8vqq8xl

Code:

import React from "react";
import { render } from "react-dom";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center",
  //marginTop: "1000px"
};

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMap: true
    };
  }

  toggleCheckbox = event => {
    this.setState({ showMap: !this.state.showMap });
    event.preventDefault();
  };

  render() {
    return (

{this.state.showMap ? "Show" : "hide"}

          <input
            type="checkbox"
            title="test"
            name="showMap"
            checked={this.state.showMap}
            readOnly
          />
          Show map

    );
  }
}

const App = () => (

      <Menu />

);

render(<App />, document.getElementById("root"));

Update:

Created an issue with React.

https://github.com/facebook/react/issues/11539

Body:
This appears to be browser native behavior:

HTML:

<a href="#" role="button" id="anchor">
  <input id="input" type="checkbox" title="test" name="showMap" readonly /> Clicking this text toggles the checkbox
</a>

<hr />
<label><input id="prevent" type="checkbox" /> Prevent Default</label>

<p>With prevent default on, clicking the checkbox does not toggle it. Only clicking the text</p>

CSS:

body {
  font-size: 15px;
  line-height: 1.5;
  padding: 20px;
}

JS:

var anchor = document.getElementById('anchor')
var prevent = document.getElementById('prevent')
var input = document.getElementById('input')
var toggled = false

anchor.addEventListener('click', function (event) {
  if (prevent.checked) {
    event.preventDefault()
  }

  toggled = !toggled

  input.checked = toggled
})

https://codepen.io/nhunzaker/pen/WXONQK

https://github.com/facebook/react/issues/11539#issuecomment-343914330


问:
how to open a tab (tabpane) and scroll to it?
I want to click on a link and open a tab in the current page ( review) and scroll to it. I don't want to use the hash in url.....

This is my code for click on link:

```<code>$('#openReview').on('click', function() {
    $('.nav-tabs a[href="#review"]').tab('show');
    document.getElementById("review").scrollIntoView();
});
</code>```

The problem is : I have to click twice!!!

First: it make the tab active ( the second tab) -> then second click scroll to it.

How can I make it to work only with one click? :)

答:
Try to use this code:

```<code>$('#openReview').on('click', function() {
    $('.nav-tabs a[href="#review"]').tab('show');
    $('html, body').animate({
        scrollTop: $(".tabs-widget").offset().top
    }, 2000);
});
</code>```

If you have more elements with class tabs-widget i suggest you add an id to this element instead and reference it in the scrollTop. You can change the scroll animation duration in the code (my example is 2 sec)

EDIT

In fact, your code will work if you use an id on the wrapping section of the tabs instead of using #reviews. The reason being is that it takes some miliseconds for tab("show") to execute and meanwhile the element #reviews is not in the view, so can't be immediately scrolled to.

```<code>$('#openReview').on('click', function () {
    $('.nav-tabs a[href="#review"]').tab('show');
    document.getElementById("tabs_widget").scrollIntoView();
});

...
<!-- in you HTML -->
<section class="tabs-widget" id="tabs_widget">
</code>```

Body:
I want to click on a link and open a tab in the current page ( review) and scroll to it. I don't want to use the hash in url.....

This is my code for click on link:

$('#openReview').on('click', function() {
    $('.nav-tabs a[href="#review"]').tab('show');
    document.getElementById("review").scrollIntoView();
});

The problem is : I have to click twice!!!

First: it make the tab active ( the second tab) -> then second click scroll to it.

How can I make it to work only with one click? :)

Body:
Try to use this code:

$('#openReview').on('click', function() {
    $('.nav-tabs a[href="#review"]').tab('show');
    $('html, body').animate({
        scrollTop: $(".tabs-widget").offset().top
    }, 2000);
});

If you have more elements with class tabs-widget i suggest you add an id to this element instead and reference it in the scrollTop. You can change the scroll animation duration in the code (my example is 2 sec)

EDIT

In fact, your code will work if you use an id on the wrapping section of the tabs instead of using #reviews. The reason being is that it takes some miliseconds for tab("show") to execute and meanwhile the element #reviews is not in the view, so can't be immediately scrolled to.

$('#openReview').on('click', function () {
    $('.nav-tabs a[href="#review"]').tab('show');
    document.getElementById("tabs_widget").scrollIntoView();
});

...
<!-- in you HTML -->
<section class="tabs-widget" id="tabs_widget">


问:
Prevent body scrolling when Overlay is shown in AMP
Is there any way I can disable scroll on  in AMP when an overlay is shown?

This is what I've tried:

.noscroll {
  overflow: hidden;
}
.overlay {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.4);
  transition: opacity 200ms ease-in-out;
  visibility: hidden;
  opacity: 0;
  z-index: 1;
}
.overlay.show {
    visibility: visible;
    opacity: 1;
}
.taptoclose {
  position: absolute;
  top: 100px;
  background: #fff;
  padding 30px;
  color: #000;
  margin: auto;
  font-size: 18px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html amp>
<head>
  <script async src="https://cdn.ampproject.org/v0.js"></script>
  <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
  <script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
</head>
<body [class]="noscrollBody ? 'noscroll' : ''" on="tap:AMP.setState({
    showOverlay: true,
    noscrollBody: true
  })">

<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>
<h4>Dummy data to show scroll. Tap anywhere to show Overlay.</h4>

<div class="overlay" [class]="showOverlay ? 'overlay show' : 'overlay'" on="tap:AMP.setState({
    showOverlay: false,
    noscrollBody: false
  })">
</div>
</body></code>```

However, following is visible in console which means AMP is forcing to always show overflow for  and

```<code>html.i-amphtml-singledoc>body {
    overflow: visible!important;
    position: relative!important;
}
</code>```

I've looked into documentation and HTML Specs of AMP but unable to find anything.

答: You can use amp-lightbox (https://ampbyexample.com/components/amp-lightbox/) to create an overlay that disables scrolling the background. This could be a good option if there's not a reason you've avoided using it.</p>

Body:
Is there any way I can disable scroll on  in AMP when an overlay is shown?

This is what I've tried:

.noscroll {
  overflow: hidden;
}
.overlay {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.4);
  transition: opacity 200ms ease-in-out;
  visibility: hidden;
  opacity: 0;
  z-index: 1;
}
.overlay.show {
    visibility: visible;
    opacity: 1;
}
.taptoclose {
  position: absolute;
  top: 100px;
  background: #fff;
  padding 30px;
  color: #000;
  margin: auto;
  font-size: 18px;
}

<!DOCTYPE html>

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

Dummy data to show scroll. Tap anywhere to show Overlay.

However, following is visible in console which means AMP is forcing to always show overflow for  and

html.i-amphtml-singledoc>body {
    overflow: visible!important;
    position: relative!important;
}

I've looked into documentation and HTML Specs of AMP but unable to find anything.