问:
Enable other event while dragging an object
I'm developing a console where I want to drag a button to a grid:

To drag the button, I use the following procedure:

```<code>Public drag As Boolean = False
Public ptX As Integer = 0
Public ptY As Integer = 0
Public btn As Button

Private Sub MoveButton_MouseDown(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseDown
    drag = True
    btn = CType(sender, Button)
    ptX = e.X : ptY = e.Y
End Sub

Private Sub MoveButton_MouseMove(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseMove
    If drag Then
        btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)
        Me.Refresh()
    End If
End Sub

Private Sub MoveButton_MouseUp(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseUp
    drag = False
End Sub
</code>```

So far, so good! This works fine for that matter.
However, I'm trying to highlight the cell while hoovering the button on it like this:

To do so, I tried to do the following:

```<code>Private Sub CellA1_MouseHover(sender As Object, e As EventArgs) Handles CellA1.MouseHover
    If drag Then
        CellA1.BackColor = Color.Red
    End If
End Sub
</code>```

Of course I can't do that, unless I, somehow, enable the CellA1.MouseHover event while dragging the MoveButton.

Can anyone help me with this?

If, however, you're having a struggling will to help me further, my last goal is to place the MoveButton on the red cell place:

But feel free to don't help me at all with this part of the procedure since I have no code to perform this yet.
Any help will be very appreciated. And, as always, thank you all in advance.

答:
Since your mouse is not actually on the PictureBox when you drag the button it will never raise any mouse events. What you can do instead is to call the GetChildAtPoint() method of your form to get the control behind the button. Once you have that just verify that the name starts with "Cell" and change the back color.

To snap to the cell's location you'll need to indicate to MouseUp which cell we're currently at. Simply store the cell control in a variable and you can then just set yourButton.Location = currentCell.Location

Here are the changes I've made to your code, commented for clarity:

```<code>Public drag As Boolean = False
Public ptX As Integer = 0
Public ptY As Integer = 0
Public btn As Button
Public prevCtrl As Control = Nothing 'Store the previous Cell the button was dragged over.
'                                     We need this to be able to reset the BackColor of the Cell,
'                                     and also so that you can snap to its location once you drop the button.

Private Sub MoveButton_MouseDown(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseDown
    'No changes made here.
    drag = True
    btn = CType(sender, Button)
    ptX = e.X : ptY = e.Y
End Sub

Private Sub MoveButton_MouseMove(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseMove
    If drag Then
        btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)

        'Go 1 pixel up, or else GetChildAtPoint() will return the button instead of the control behind it.
        Dim LookPoint As Point = Point.Subtract(btn.Location, New Size(0, 1))

        'Get the control located below/behind the button.
        Dim ControlBelow As Control = Me.GetChildAtPoint(LookPoint, GetChildAtPointSkip.Invisible Or GetChildAtPointSkip.Disabled) 'Ignore invisible or disabled controls.

        'Check so that the previous cell is not also the current cell. If they're the same then we won't change anything.
        If prevCtrl IsNot ControlBelow Then

            'Ok, the current cell and the previous cell are not the same.
            'Now check if there was any previous cell at all.
            If prevCtrl IsNot Nothing Then
                'There was a previous cell, but since the button
                'is no longer hovering over it we reset its BackColor.
                prevCtrl.BackColor = Color.White
                prevCtrl = Nothing
            End If

            'Check that there infact is a control behind the button,
            'and also check that its name starts with "Cell".
            If ControlBelow IsNot Nothing AndAlso ControlBelow.Name.StartsWith("Cell", StringComparison.OrdinalIgnoreCase) Then
                'The control behind the button is a valid Cell. Change its BackColor.
                ControlBelow.BackColor = Color.Red
                prevCtrl = ControlBelow 'The previous cell is now the current cell.
            End If

        End If

        'Me.Refresh() - this is a very unnecessary call, it will just eat CPU. The form does not need to be redrawn at this point.
    End If
End Sub

Private Sub MoveButton_MouseUp(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseUp
    'Check if we dragged the button. At this point prevCtrl is the current cell (if it's not Nothing).
    If drag = True AndAlso prevCtrl IsNot Nothing Then
        btn.Location = prevCtrl.Location 'Snap to the cell's location.
        prevCtrl.BackColor = Color.White 'Reset the cell's BackColor.
        prevCtrl = Nothing 'Reset this since we're no longer dragging the button.
    End If

    drag = False
End Sub
</code>```

And it works like a charm!

Body:
I'm developing a console where I want to drag a button to a grid:

To drag the button, I use the following procedure:

Public drag As Boolean = False
Public ptX As Integer = 0
Public ptY As Integer = 0
Public btn As Button

Private Sub MoveButton_MouseDown(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseDown
    drag = True
    btn = CType(sender, Button)
    ptX = e.X : ptY = e.Y
End Sub

Private Sub MoveButton_MouseMove(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseMove
    If drag Then
        btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)
        Me.Refresh()
    End If
End Sub

Private Sub MoveButton_MouseUp(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseUp
    drag = False
End Sub

So far, so good! This works fine for that matter.
However, I'm trying to highlight the cell while hoovering the button on it like this:

To do so, I tried to do the following:

Private Sub CellA1_MouseHover(sender As Object, e As EventArgs) Handles CellA1.MouseHover
    If drag Then
        CellA1.BackColor = Color.Red
    End If
End Sub

Of course I can't do that, unless I, somehow, enable the CellA1.MouseHover event while dragging the MoveButton.

Can anyone help me with this?

If, however, you're having a struggling will to help me further, my last goal is to place the MoveButton on the red cell place:

But feel free to don't help me at all with this part of the procedure since I have no code to perform this yet.
Any help will be very appreciated. And, as always, thank you all in advance.

Body:
Since your mouse is not actually on the PictureBox when you drag the button it will never raise any mouse events. What you can do instead is to call the GetChildAtPoint() method of your form to get the control behind the button. Once you have that just verify that the name starts with "Cell" and change the back color.

To snap to the cell's location you'll need to indicate to MouseUp which cell we're currently at. Simply store the cell control in a variable and you can then just set yourButton.Location = currentCell.Location

Here are the changes I've made to your code, commented for clarity:

Public drag As Boolean = False
Public ptX As Integer = 0
Public ptY As Integer = 0
Public btn As Button
Public prevCtrl As Control = Nothing 'Store the previous Cell the button was dragged over.
'                                     We need this to be able to reset the BackColor of the Cell,
'                                     and also so that you can snap to its location once you drop the button.

Private Sub MoveButton_MouseDown(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseDown
    'No changes made here.
    drag = True
    btn = CType(sender, Button)
    ptX = e.X : ptY = e.Y
End Sub

Private Sub MoveButton_MouseMove(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseMove
    If drag Then
        btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)

        'Go 1 pixel up, or else GetChildAtPoint() will return the button instead of the control behind it.
        Dim LookPoint As Point = Point.Subtract(btn.Location, New Size(0, 1))

        'Get the control located below/behind the button.
        Dim ControlBelow As Control = Me.GetChildAtPoint(LookPoint, GetChildAtPointSkip.Invisible Or GetChildAtPointSkip.Disabled) 'Ignore invisible or disabled controls.

        'Check so that the previous cell is not also the current cell. If they're the same then we won't change anything.
        If prevCtrl IsNot ControlBelow Then

            'Ok, the current cell and the previous cell are not the same.
            'Now check if there was any previous cell at all.
            If prevCtrl IsNot Nothing Then
                'There was a previous cell, but since the button
                'is no longer hovering over it we reset its BackColor.
                prevCtrl.BackColor = Color.White
                prevCtrl = Nothing
            End If

            'Check that there infact is a control behind the button,
            'and also check that its name starts with "Cell".
            If ControlBelow IsNot Nothing AndAlso ControlBelow.Name.StartsWith("Cell", StringComparison.OrdinalIgnoreCase) Then
                'The control behind the button is a valid Cell. Change its BackColor.
                ControlBelow.BackColor = Color.Red
                prevCtrl = ControlBelow 'The previous cell is now the current cell.
            End If

        End If

        'Me.Refresh() - this is a very unnecessary call, it will just eat CPU. The form does not need to be redrawn at this point.
    End If
End Sub

Private Sub MoveButton_MouseUp(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseUp
    'Check if we dragged the button. At this point prevCtrl is the current cell (if it's not Nothing).
    If drag = True AndAlso prevCtrl IsNot Nothing Then
        btn.Location = prevCtrl.Location 'Snap to the cell's location.
        prevCtrl.BackColor = Color.White 'Reset the cell's BackColor.
        prevCtrl = Nothing 'Reset this since we're no longer dragging the button.
    End If

    drag = False
End Sub

And it works like a charm!


来源: stackexchange

问:
Username in HTTP Header for SSO
I am looking to add single sign on (SSO) to one of my web applications. I don't want anything heavy at the moment, I just want to know the userId of the logged in user, without the need for them to enter a username.

The web app is an internal application, so I can guarantee they are coming from a Windows PC etc.

I have looked at jCIFS, but this doesn't seem to be supported any more, and recommends a commercial product.

I have also looked at WAFFLE, but I am building SSO for a playframework application, which does not use a Servlet stack, so I can't make use of the SecurityFilter. I have tried to make sense of the WindowsLoginModule, but couldn't really understand what I had to do to implement it.

Is it possible to just get the username from the HTTP header, or does it require some negotiation first before it will post the header?

答: You can always get any header from filter. See javadoc for HttpServletRequest.</p>

ContentLicense: CC BY-SA 2.5

Title: Username in HTTP Header for SSO


答:
You're definitely not going anywhere, as you've made no reference at all to a dictionary.

I'll outline a process for you here; can you fill in the details?

```<code>my_dict = {}

while not EOF:
    # read the "Origin" line
    line = f.readline()

    # extract the number on the right
    origin_num = int( line.split()[-1] )

    # Read the data lines
    for _ in range(5):    # each data chunk has 5 lines
        data_line = readline()
        entries = data_line.split(';')    # split at semicolons

        for field in entries:
            y_key, value = field.split(:)
            # Now, you need to convert both of those to integers,
            #    combine v_key with the origin_num,
            #    and insert that value into my_dict.
</code>```

Does that get you moving?
Note that you also need to handle blank lines, detect end of file, etc.

ContentLicense: CC BY-SA 3.0

Title: Converting a text file into a dictionary

Body:
I have the following text file for demand in a network.

Origin  1
    1 :      0.0;     2 :    100.0;     3 :    100.0;     4 :    500.0;     5 :    200.0;
    6 :    300.0;     7 :    500.0;     8 :    800.0;     9 :    500.0;    10 :   1300.0;
   11 :    500.0;    12 :    200.0;    13 :    500.0;    14 :    300.0;    15 :    500.0;
   16 :    500.0;    17 :    400.0;    18 :    100.0;    19 :    300.0;    20 :    300.0;
   21 :    100.0;    22 :    400.0;    23 :    300.0;    24 :    100.0;

Origin  2
    1 :    100.0;     2 :      0.0;     3 :    100.0;     4 :    200.0;     5 :    100.0;
    6 :    400.0;     7 :    200.0;     8 :    400.0;     9 :    200.0;    10 :    600.0;
   11 :    200.0;    12 :    100.0;    13 :    300.0;    14 :    100.0;    15 :    100.0;
   16 :    400.0;    17 :    200.0;    18 :      0.0;    19 :    100.0;    20 :    100.0;
   21 :      0.0;    22 :    100.0;    23 :      0.0;    24 :      0.0;

Origin  3
    1 :    100.0;     2 :    100.0;     3 :      0.0;     4 :    200.0;     5 :    100.0;
    6 :    300.0;     7 :    100.0;     8 :    200.0;     9 :    100.0;    10 :    300.0;
   11 :    300.0;    12 :    200.0;    13 :    100.0;    14 :    100.0;    15 :    100.0;
   16 :    200.0;    17 :    100.0;    18 :      0.0;    19 :      0.0;    20 :      0.0;
   21 :      0.0;    22 :    100.0;    23 :    100.0;    24 :      0.0;

... records 4-23 elided ...

Origin  24
    1 :    100.0;     2 :      0.0;     3 :      0.0;     4 :    200.0;     5 :      0.0;
    6 :    100.0;     7 :    100.0;     8 :    200.0;     9 :    200.0;    10 :    800.0;
   11 :    600.0;    12 :    500.0;    13 :    700.0;    14 :    400.0;    15 :    400.0;
   16 :    300.0;    17 :    300.0;    18 :      0.0;    19 :    100.0;    20 :    400.0;
   21 :    500.0;    22 :   1100.0;    23 :    700.0;    24 :      0.0;

Now I need to create a dictionary, which should look something like:

{(1,1):0.0, (1,2):100.0, (1, 3):100.0, .......
 (2, 1):100.0, (2,2):0, ......}

Where the tuple elements e.g. (1, 2) represent the origin and destination, and the value represents the demand (which is 100.0 for the (1, 2) key).

I tried the following:

with open("trips.txt", "r") as f:
     line = f.readline()
     line = f.readline()
     ind = 0
     while len(line):
         line = line.strip(';')
         l = line.split()
         print l

         ind = ind + 1
         if(ind == 5):
             line = f.readline()
             line = f.readline()
             line = f.readline()
             ind = 0
             node = node + 1
         else:
             line = f.readline()

But I don't think I am going anywhere with this...

Body:
You're definitely not going anywhere, as you've made no reference at all to a dictionary.

I'll outline a process for you here; can you fill in the details?

my_dict = {}

while not EOF:
    # read the "Origin" line
    line = f.readline()

    # extract the number on the right
    origin_num = int( line.split()[-1] )

    # Read the data lines
    for _ in range(5):    # each data chunk has 5 lines
        data_line = readline()
        entries = data_line.split(';')    # split at semicolons

        for field in entries:
            y_key, value = field.split(:)
            # Now, you need to convert both of those to integers,
            #    combine v_key with the origin_num,
            #    and insert that value into my_dict.

Does that get you moving?
Note that you also need to handle blank lines, detect end of file, etc.


问:
How can I transpose my dataframe so that the rows and columns switch in r?
I have a dataframe (simplified) that looks like this:

```<code>Age, Kodiak, Banana, Banff, Montreal, Fairfax
Age_1, 5, 6 , 7, 9, 2
Age_2, 7, 6, 4, 3, 2
Age_3, 5, 3, 8, 5, 9
</code>```

I would like my dataframe to look more like this:

```<code>Location, Age_1, Age_2, Age_3
Kodiak, 5, 7, 5
Banana, 6, 6, 3
Banff, 7, 4, 8
Montreal, 9, 3, 5
Fairfax, 2, 2, 9
</code>```

I've looked at the transpose function but I'm a bit confused on how to switch both the columns and rows. I'm very new to R.

答:
There are two ways you can do this. The first one is using t to just transpose the dataframe as if it would be a matrix (indeed the result of t is a matrix, not a dataframe).

The other option is to take the tidy data approach and use tidyr::spread along with tidyr::gather. Both have similar results although the second one is more versatile as it can be applied partially. Also notice that when using t the first column (which has type chr) will become the first row in the new matrix and therefore the entire matrix will be converted into a chr matrix, while gather+spread keeps the columns numeric.

library(tidyr)

df <- read.table(text = "Age Kodiak Banana Banff Montreal Fairfax
Age_1 5 6 7 9 2
Age_2 7 6 4 3 2
Age_3 5 3 8 5 9", header = T)

t(df)
#>          [,1]    [,2]    [,3]
#> Age      "Age_1" "Age_2" "Age_3"
#> Kodiak   "5"     "7"     "5"
#> Banana   "6"     "6"     "3"
#> Banff    "7"     "4"     "8"
#> Montreal "9"     "3"     "5"
#> Fairfax  "2"     "2"     "9"

df %>%
  gather("location", "value", 2:ncol(df)) %>%
  spread(Age, value)
#>   location Age_1 Age_2 Age_3
#> 1   Banana     6     6     3
#> 2    Banff     7     4     8
#> 3  Fairfax     2     2     9
#> 4   Kodiak     5     7     5
#> 5 Montreal     9     3     5
```

Body:
I have a dataframe (simplified) that looks like this:

Age, Kodiak, Banana, Banff, Montreal, Fairfax
Age_1, 5, 6 , 7, 9, 2
Age_2, 7, 6, 4, 3, 2
Age_3, 5, 3, 8, 5, 9

I would like my dataframe to look more like this:

Location, Age_1, Age_2, Age_3
Kodiak, 5, 7, 5
Banana, 6, 6, 3
Banff, 7, 4, 8
Montreal, 9, 3, 5
Fairfax, 2, 2, 9

I've looked at the transpose function but I'm a bit confused on how to switch both the columns and rows. I'm very new to R.


问:
Count the number of likert scale results from multiple column questions in pandas
I have the following dataframe:

```<code>       Question1        Question2         Question3          Question4
User1  Agree            Agree          Disagree         Strongly Disagree
User2  Disagree         Agree          Agree            Disagree
User3  Agree            Agree          Agree            Agree
</code>```

Is there a way to convert the dataframe listed above to the following?

```<code>              Agree         Disagree         Strongly Disagree
 Question1    2               1                  0

 Question2    2               1                  0

 Question3    2               1                  0
 Question4    1               1                  1
</code>```

This is similar to my previous question: Make a dataframe with grouped questions from three columns

I tried looking at previous questions with stack/pivot but could not figure it out.  The actual dataframe has 20+ questions and a likert scale from strongly agree, agree, neutral, disagree, strongly disagree.

答:
With pd.get_dummies

```<code>pd.get_dummies(df.stack()).groupby(level=1).sum()

           Agree  Disagree  Strongly Disagree
Question1      2         1                  0
Question2      3         0                  0
Question3      2         1                  0
Question4      1         1                  1
</code>```

Taking it to another level

We can use numpy.bincount to speed things.  But we have to pay attention to dimensions

```<code>v = df.values
f, u = pd.factorize(v.ravel())
n, m = u.size, v.shape[1]
r = np.tile(np.arange(m), n)
b0 = np.bincount(r * n + f)
pad = np.zeros(n * m - b0.size, dtype=int)
b = np.append(b0, pad)

pd.DataFrame(b.reshape(m, n), df.columns, u)

           Agree  Disagree  Strongly Disagree
Question1      2         1                  0
Question2      3         0                  0
Question3      2         1                  0
Question4      1         1                  1
</code>```

Another numpy option

```<code>v = df.values
n, m = v.shape
f, u = pd.factorize(v.ravel())

pd.DataFrame(
    np.eye(u.size, dtype=int)[f].reshape(n, m, -1).sum(0),
    df.columns, u
)

           Agree  Disagree  Strongly Disagree
Question1      2         1                  0
Question2      3         0                  0
Question3      2         1                  0
Question4      1         1                  1
</code>```

Speed Difference

```<code>%%timeit
v = df.values
f, u = pd.factorize(v.ravel())
n, m = u.size, v.shape[1]
r = np.tile(np.arange(m), n)
b0 = np.bincount(r * n + f)
pad = np.zeros(n * m - b0.size, dtype=int)
b = np.append(b0, pad)

pd.DataFrame(b.reshape(m, n), df.columns, u)
1000 loops, best of 3: 194 µs per loop

%%timeit
v = df.values
n, m = v.shape
f, u = pd.factorize(v.ravel())

pd.DataFrame(
    np.eye(u.size, dtype=int)[f].reshape(n, m, -1).sum(0),
    df.columns, u
)
1000 loops, best of 3: 195 µs per loop

%timeit pd.get_dummies(df.stack()).groupby(level=1).sum()
1000 loops, best of 3: 1.2 ms per loop
</code>```

Body:
I have the following dataframe:

       Question1        Question2         Question3          Question4
User1  Agree            Agree          Disagree         Strongly Disagree
User2  Disagree         Agree          Agree            Disagree
User3  Agree            Agree          Agree            Agree

Is there a way to convert the dataframe listed above to the following?

              Agree         Disagree         Strongly Disagree
 Question1    2               1                  0

 Question2    2               1                  0

 Question3    2               1                  0
 Question4    1               1                  1

This is similar to my previous question: Make a dataframe with grouped questions from three columns

I tried looking at previous questions with stack/pivot but could not figure it out.  The actual dataframe has 20+ questions and a likert scale from strongly agree, agree, neutral, disagree, strongly disagree.

Body:
With pd.get_dummies

pd.get_dummies(df.stack()).groupby(level=1).sum()

           Agree  Disagree  Strongly Disagree
Question1      2         1                  0
Question2      3         0                  0
Question3      2         1                  0
Question4      1         1                  1

Taking it to another level

We can use numpy.bincount to speed things.  But we have to pay attention to dimensions

v = df.values
f, u = pd.factorize(v.ravel())
n, m = u.size, v.shape[1]
r = np.tile(np.arange(m), n)
b0 = np.bincount(r * n + f)
pad = np.zeros(n * m - b0.size, dtype=int)
b = np.append(b0, pad)

pd.DataFrame(b.reshape(m, n), df.columns, u)

           Agree  Disagree  Strongly Disagree
Question1      2         1                  0
Question2      3         0                  0
Question3      2         1                  0
Question4      1         1                  1

Another numpy option

v = df.values
n, m = v.shape
f, u = pd.factorize(v.ravel())

pd.DataFrame(
    np.eye(u.size, dtype=int)[f].reshape(n, m, -1).sum(0),
    df.columns, u
)

           Agree  Disagree  Strongly Disagree
Question1      2         1                  0
Question2      3         0                  0
Question3      2         1                  0
Question4      1         1                  1

Speed Difference

%%timeit
v = df.values
f, u = pd.factorize(v.ravel())
n, m = u.size, v.shape[1]
r = np.tile(np.arange(m), n)
b0 = np.bincount(r * n + f)
pad = np.zeros(n * m - b0.size, dtype=int)
b = np.append(b0, pad)

pd.DataFrame(b.reshape(m, n), df.columns, u)
1000 loops, best of 3: 194 µs per loop

%%timeit
v = df.values
n, m = v.shape
f, u = pd.factorize(v.ravel())

pd.DataFrame(
    np.eye(u.size, dtype=int)[f].reshape(n, m, -1).sum(0),
    df.columns, u
)
1000 loops, best of 3: 195 µs per loop

%timeit pd.get_dummies(df.stack()).groupby(level=1).sum()
1000 loops, best of 3: 1.2 ms per loop


问:
indexOf to find all occurrences of a word in a String
I'm trying to use indexOf to find all occurrences of the characters 'the' in a sentence. For example, if the sentence were "The other day I went over there", it should return 3.

I am able to do this up to the point where it finds the first index, but I'm unsure of how to write the loop. I originally had a for loop that searched the entire string, but it was returning the full string character length, instead of the occurrences of my specified character. How can I write a loop that will find all of the occurrences of the word? Thank you.

```<code>import java.util.Scanner;

public class TheFinder
{
    public static void main (String[] args)
    {
        String theString = "";
        Scanner enter = new Scanner(System.in);

        System.out.println("Please enter a sentence: ");
        theString = enter.nextLine();
        int counter2 = 0;
        theString.indexOf("the");

        if (theString.indexOf("the")!= -1)
        counter2++;

        System.out.printf("The characters 'the' were found %d times", counter2);
        System.out.println();

        System.out.println("This was programmed by -----");
</code>```

答:
Maybe you can do something like this, you can use indexOf(String str)</p>

```<code>String word = "We are students of the Department of Informatics. All students should know how to program in Java and C.";

    int findit = word.indexOf("students");
    int count = 0;

    for(int i=0; i<=findit; i++)
    {

        findit = word.indexOf("students" , findit + 1);

        count = count + 1;

    }

    System.out.print(count);
</code>```

Body:
I'm trying to use indexOf to find all occurrences of the characters 'the' in a sentence. For example, if the sentence were "The other day I went over there", it should return 3.

I am able to do this up to the point where it finds the first index, but I'm unsure of how to write the loop. I originally had a for loop that searched the entire string, but it was returning the full string character length, instead of the occurrences of my specified character. How can I write a loop that will find all of the occurrences of the word? Thank you.

import java.util.Scanner;

public class TheFinder
{
    public static void main (String[] args)
    {
        String theString = "";
        Scanner enter = new Scanner(System.in);

        System.out.println("Please enter a sentence: ");
        theString = enter.nextLine();
        int counter2 = 0;
        theString.indexOf("the");

        if (theString.indexOf("the")!= -1)
        counter2++;

        System.out.printf("The characters 'the' were found %d times", counter2);
        System.out.println();

        System.out.println("This was programmed by -----");

Body:
Maybe you can do something like this, you can use indexOf(String str)

String word = "We are students of the Department of Informatics. All students should know how to program in Java and C.";

    int findit = word.indexOf("students");
    int count = 0;

    for(int i=0; i<=findit; i++)
    {

        findit = word.indexOf("students" , findit + 1);

        count = count + 1;

    }

    System.out.print(count);


问:
How to speed up large numbers of UIImages in Swift 3
I am making a Swift 3 app that generates thousands of motionless UIImages to make a pattern. The pattern is created by iteration. The dots are 4x4 low-resolution images, located randomly. My app runs at one hundred dots per second using a clock until about 3000, where the lag becomes visible, and in next twenty thousand, it gets to forty-fifty seconds per thousand, versus ten. The gist of my generation is this:

```<code>    @IBAction func AddPoint(_ sender: UIButton) {

        let newdot = UIImageView(image: UIImage(named: "redDot"))

        self.view.addSubview(newdot)

        // lastx and lasty are edited here, before the dot is plotted.

        newdot.frame = CGRect(x: lastx - newdotsize / 2.0, y: lasty - newdotsize / 2.0, width: newdotsize, height:newdotsize)

    }
</code>```

The code is fully functional, but the images are left on the view (as far as I know) untouchable. What can I do to speed it up? Should I merge them every thousand? If I am going to merge them, then I need flexible code (How to merge two UIImages? has only two images) and I need to be able to control them, which I don't know how to do.

答:
Don't use UIImageViews to draw pixels.  Use drawrect in UIView and core graphics

iOS draw filled Circles

Body:
I am making a Swift 3 app that generates thousands of motionless UIImages to make a pattern. The pattern is created by iteration. The dots are 4x4 low-resolution images, located randomly. My app runs at one hundred dots per second using a clock until about 3000, where the lag becomes visible, and in next twenty thousand, it gets to forty-fifty seconds per thousand, versus ten. The gist of my generation is this:

    @IBAction func AddPoint(_ sender: UIButton) {

        let newdot = UIImageView(image: UIImage(named: "redDot"))

        self.view.addSubview(newdot)

        // lastx and lasty are edited here, before the dot is plotted.

        newdot.frame = CGRect(x: lastx - newdotsize / 2.0, y: lasty - newdotsize / 2.0, width: newdotsize, height:newdotsize)

    }

The code is fully functional, but the images are left on the view (as far as I know) untouchable. What can I do to speed it up? Should I merge them every thousand? If I am going to merge them, then I need flexible code (How to merge two UIImages? has only two images) and I need to be able to control them, which I don't know how to do.


问:
Finding the greatest amount of consecutive values in an array (JS)
I'm trying to solve a problem that I can't seem to wrap my head around and was hoping I could get a little bit of insight from someone more experienced than I am. Basically, I have an array that has anywhere from 10 to 500 values. These values are all either true or false, but they are in a random order. I need to know the greatest amount of times that false appears in a row. For example:

```<code>[false, false, true, false, true, false, true, false, false, false]
</code>```

Should return 3, since it appears 3 times in a row at the most. This seems like a potentially common problem to solve but I couldn't find a solution through searching. Any help would be greatly appreciated!

答:
You could simply use the forEach function, and then have an internal counter, for example:

console.log( countConsecutive([false, false, true, false, true, false, true, false, false, false]) );

function countConsecutive( arr )
{
   var c = 0;

   arr.forEach(function(e) {
     (e == false) ? c++ : c = 0;
  });

  return c;
}```

Body:
I'm trying to solve a problem that I can't seem to wrap my head around and was hoping I could get a little bit of insight from someone more experienced than I am. Basically, I have an array that has anywhere from 10 to 500 values. These values are all either true or false, but they are in a random order. I need to know the greatest amount of times that false appears in a row. For example:

[false, false, true, false, true, false, true, false, false, false]

Should return 3, since it appears 3 times in a row at the most. This seems like a potentially common problem to solve but I couldn't find a solution through searching. Any help would be greatly appreciated!


问:
Convert VB.NET Group By expression to C#
I have to convert the following expression from VB.NET to C#:

```<code>Dim z = From d In db.GPSdevice
    Where d.CompanyId = currentuser.CompanyId And d.Type = "Trailer"
    Order By d.ListOrder Descending
    Group d By Geofence = d.GeofenceLocation Into g = Group, Count()
    Order By Count Descending
</code>```

I'm confused with Group By section...

答:
A literal translation would be

```<code>var z = from d in db.GPSdevice
        where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
        orderby d.ListOrder descending
        group d by d.GeofenceLocation into g
        orderby g.Count() descending
        select new { Geofence = g.Key, g = (from g2 in g select g2), Count = g.Count() };
</code>```

but this doesn't result in the exact same types as the original VB query.

Here is a more (prematurely?) optimized version that does result in the same types:

```<code>var z2 = (from d in db.GPSdevice
         where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
         group d by d.GeofenceLocation into g
         select new { Geofence = g.Key, g = (from g2 in g orderby g2.ListOrder descending select g2).ToArray(), Count = g.Count() }).OrderByDescending(g => g.Count);
</code>```

Body:
I have to convert the following expression from VB.NET to C#:

Dim z = From d In db.GPSdevice
    Where d.CompanyId = currentuser.CompanyId And d.Type = "Trailer"
    Order By d.ListOrder Descending
    Group d By Geofence = d.GeofenceLocation Into g = Group, Count()
    Order By Count Descending

I'm confused with Group By section...

Body:
A literal translation would be

var z = from d in db.GPSdevice
        where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
        orderby d.ListOrder descending
        group d by d.GeofenceLocation into g
        orderby g.Count() descending
        select new { Geofence = g.Key, g = (from g2 in g select g2), Count = g.Count() };

but this doesn't result in the exact same types as the original VB query.

Here is a more (prematurely?) optimized version that does result in the same types:

var z2 = (from d in db.GPSdevice
         where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
         group d by d.GeofenceLocation into g
         select new { Geofence = g.Key, g = (from g2 in g orderby g2.ListOrder descending select g2).ToArray(), Count = g.Count() }).OrderByDescending(g => g.Count);


问:
Relocate .vs folder from solution folder
I am trying to clean up my solution folder.  So far I have relocated the packages folder, which is generated by Nuget as described here: C# visual studio how to relocate nuget package folder?

I notice there is also a .vs folder, which is generated by the C# compiler (Rosyln) and is described here: .vs folder to source control in visual studio 2015?.  Is it possible/advisable to relocate this folder?

答:
I do not believe there is any way to relocate the .vs folder, but the better question is why would you need to?  Since it is simply a temp file cache specific to only that solution moving it out of the scope of that folder to a different folder effectively does nothing.  If there is no advantage, then why move it?

For example: When moving the NuGet folder it allows you to share the locally downloaded package cache with multiple solutions, saving disk space, network resources, and time.  This has a clear advantage

If you simply need to remove that folder for cleanup purposes only (for instance to share it with someone) you can delete it at any time without any concern.  It will be auto generated again the next time you build your solution, but it is not required if you just want to share your codebase.


问:
Loop an array - Cannot invoke append
This is the array's I have:

```<code>var tblID = [String]()
var tblUser = [String]()
var tblEmployee = [String]()
</code>```

I am trying to append them to a csv file, like this:

```<code>    let fileName = "Tasks.csv"
    let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

    var csvText = "ID,USER,EMPLOYEE\n"

    for content in [tblID, tblUser, tblEmployee] {
        csvText.append(content) // Error here
    }
</code>```

But in the link csvText.append(content) I get error message: Cannot invoke 'append' with an argument list of type '([String])'

Any suggestions what I can do here?

答:
You are trying to add an array of strings to a single string using the append method but that just takes a single string.

Assuming that tblID, tblUser & tblEmployee always contain the same number of items (otherwise this will crash) you can do this:

```<code>for content in [tblID, tblUser, tblEmployee] {
    for loop in 0..<tblID.count {
        csvText.append("\(tblID[loop]),\(tblUser[loop]),\(tblEmployee[loop]))\n")
    }
}
</code>```

That will add a line will add a line consisting of comma separated ID, User, Employee with a new line at the end.

Edit:

To handle the situation where the array sizes do not match you can do this:

```<code>it tblID.count != tblUser.count || tblID.count != tblEmployee.count {
    print ("error")
} else {
    // Do the above here
}
</code>```

The best you can do is either add the content of the arrays or print error.  You can't add some and then print error because if tblID had 5 entries and tblUser had 4 you don't know if the it's the first entry of tblUser that's missing or the last.

Title: Loop an array - Cannot invoke append

Body:
This is the array's I have:

var tblID = [String]()
var tblUser = [String]()
var tblEmployee = [String]()

I am trying to append them to a csv file, like this:

    let fileName = "Tasks.csv"
    let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

    var csvText = "ID,USER,EMPLOYEE\n"

    for content in [tblID, tblUser, tblEmployee] {
        csvText.append(content) // Error here
    }

But in the link csvText.append(content) I get error message: Cannot invoke 'append' with an argument list of type '([String])'

Any suggestions what I can do here?

Body:
You are trying to add an array of strings to a single string using the append method but that just takes a single string.

Assuming that tblID, tblUser & tblEmployee always contain the same number of items (otherwise this will crash) you can do this:

for content in [tblID, tblUser, tblEmployee] {
    for loop in 0..<tblID.count {
        csvText.append("\(tblID[loop]),\(tblUser[loop]),\(tblEmployee[loop]))\n")
    }
}

That will add a line will add a line consisting of comma separated ID, User, Employee with a new line at the end.

Edit:

To handle the situation where the array sizes do not match you can do this:

it tblID.count != tblUser.count || tblID.count != tblEmployee.count {
    print ("error")
} else {
    // Do the above here
}

The best you can do is either add the content of the arrays or print error.  You can't add some and then print error because if tblID had 5 entries and tblUser had 4 you don't know if the it's the first entry of tblUser that's missing or the last.


问:
"java.net.SocketException: Connection reset" when running a simpleSSL client
I am attempting to create a client/server using the SSL communication. I followed the instructions listed here  (https://www.rabbitmq.com/ssl.html).

I am greeted with this error:

while running the server :

```<code>java.net.SocketException: Connection reset
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    at java.io.DataOutputStream.flush(DataOutputStream.java:123)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:129)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:134)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:277)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:678)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
</code>```

while using the client :

```<code>Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.security.ssl.InputRecord.readFully(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.waitForClose(Unknown Source)
    at sun.security.ssl.HandshakeOutStream.flush(Unknown Source)
    at sun.security.ssl.Handshaker.kickstart(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.kickstartHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
    at sun.security.ssl.AppOutputStream.write(Unknown Source)
    at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
    at java.io.BufferedOutputStream.flush(Unknown Source)
    at java.io.DataOutputStream.flush(Unknown Source)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:129)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:134)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:277)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:678)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
    at rmqClient.simpleSSL.main(simpleSSL.java:23)
</code>```

here's my rabbit.config file :

```<code>[
    {ssl, [{versions, ['tlsv1.2', 'tlsv1.1']}]},
    {
    rabbit,
    [
          {ssl_listeners, [5675]},
      {ssl_options, [{cacertfile,"sslConn/ca_certificate.pem"},
                          {certfile,  "sslConn/server_certificate.pem"},
                          {keyfile,   "sslConn/server_key.pem"},
                          {versions, ['tlsv1.2', 'tlsv1.1']},
                          {ciphers,  [{ecdhe_ecdsa,aes_128_cbc,sha256},
                                      {ecdhe_ecdsa,aes_256_cbc,sha}]}
                         ]},
          {tcp_listeners, [5672]},
          {loopback_users, []}
        ]
    }
].
</code>```

here's also my client code :

```<code>    factory.setHost("10.3.9.139");
    factory.setPort(5673);
    factory.setUsername("User1");
    factory.setPassword("User1");
    factory.useSslProtocol();
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();
    channel.queueDeclare("rabbitmq-java-test", false, true, true, null);
    channel.basicPublish("", "rabbitmq-java-test", null, "Hello, World".getBytes());
</code>```

答:
I was able to fix this in Java 1.7 by specifying:
  SSLContext sc = SSLContext.getInstance("TLSv1.2");</p>

Body:
I am attempting to create a client/server using the SSL communication. I followed the instructions listed here  (https://www.rabbitmq.com/ssl.html).

I am greeted with this error:

while running the server :

java.net.SocketException: Connection reset
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    at java.io.DataOutputStream.flush(DataOutputStream.java:123)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:129)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:134)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:277)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:678)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)

while using the client :

Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.security.ssl.InputRecord.readFully(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.waitForClose(Unknown Source)
    at sun.security.ssl.HandshakeOutStream.flush(Unknown Source)
    at sun.security.ssl.Handshaker.kickstart(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.kickstartHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
    at sun.security.ssl.AppOutputStream.write(Unknown Source)
    at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
    at java.io.BufferedOutputStream.flush(Unknown Source)
    at java.io.DataOutputStream.flush(Unknown Source)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:129)
    at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:134)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:277)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:678)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:722)
    at rmqClient.simpleSSL.main(simpleSSL.java:23)

here's my rabbit.config file :

[
    {ssl, [{versions, ['tlsv1.2', 'tlsv1.1']}]},
    {
    rabbit,
    [
          {ssl_listeners, [5675]},
      {ssl_options, [{cacertfile,"sslConn/ca_certificate.pem"},
                          {certfile,  "sslConn/server_certificate.pem"},
                          {keyfile,   "sslConn/server_key.pem"},
                          {versions, ['tlsv1.2', 'tlsv1.1']},
                          {ciphers,  [{ecdhe_ecdsa,aes_128_cbc,sha256},
                                      {ecdhe_ecdsa,aes_256_cbc,sha}]}
                         ]},
          {tcp_listeners, [5672]},
          {loopback_users, []}
        ]
    }
].

here's also my client code :

    factory.setHost("10.3.9.139");
    factory.setPort(5673);
    factory.setUsername("User1");
    factory.setPassword("User1");
    factory.useSslProtocol();
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();
    channel.queueDeclare("rabbitmq-java-test", false, true, true, null);
    channel.basicPublish("", "rabbitmq-java-test", null, "Hello, World".getBytes());


问:
Puppet creates same package on every run on Windows agent
I use following code to install MS Office 2013 Proofing tools with Puppet. To target computers have Windows 7 as their OS and their language is English. Puppet server runs on Ubuntu 14.04.

```<code> package {'Microsoft Officen tarkistustyökalut 2013 - suomi':
                    ensure          => '15.0.xxx...',
                    source          => '\\source\proofingtools_fi-fi-x86.exe',
                    install_options => [ '/quiet' ],
                    require => Package['Microsoft Office Professional Plus 2013'],
            }
</code>```

If package is not installed on target all goes well. After it is installed on every Puppet run I get:

```<code>Notice: /Stage[main]/Officeinstaller/Package[Microsoft Officen tarkistustyökalut 20
13 - suomi]/ensure: created
</code>```

This slows down the Puppet run by about 10 seconds. Its not much but still annoying.

Proofing tools get installed correctly and work.
Changing ensure => to present or installed does not solve problem.
The Package name is written exactly as it appears in Windows Add or Remove Programs.
Other programs (including MS Office 2013) don't have this problem when installed with similar code.

What could be causing this problem?

答:
I would open an admin command prompt and type puppet resource package > c:\SomewhereICanFindThis\packages.txt
In the text file find your resource for the proofing tools. That is exactly what Puppet sees installed, so if you copy it out and paste it into your resource it should stop trying to reinstall it as the resource name should match.

Body:
I use following code to install MS Office 2013 Proofing tools with Puppet. To target computers have Windows 7 as their OS and their language is English. Puppet server runs on Ubuntu 14.04.

 package {'Microsoft Officen tarkistustyökalut 2013 - suomi':
                    ensure          => '15.0.xxx...',
                    source          => '\\source\proofingtools_fi-fi-x86.exe',
                    install_options => [ '/quiet' ],
                    require => Package['Microsoft Office Professional Plus 2013'],
            }

If package is not installed on target all goes well. After it is installed on every Puppet run I get:

Notice: /Stage[main]/Officeinstaller/Package[Microsoft Officen tarkistustyökalut 20
13 - suomi]/ensure: created

This slows down the Puppet run by about 10 seconds. Its not much but still annoying.

Proofing tools get installed correctly and work.
Changing ensure => to present or installed does not solve problem.
The Package name is written exactly as it appears in Windows Add or Remove Programs.
Other programs (including MS Office 2013) don't have this problem when installed with similar code.

What could be causing this problem?


问:
How do I get a particular (older) version of a file from git repository without wiping out later versions?
I should think that getting a previous version is one of source control's premier features, and should be simple, yet it seems like a treasure hunt finding git solution.

I came across stackoverflow question How can I check out a particular version of one file in Git?.  To paraphrase the key thing:

```<code>git checkout <commit hash from git log output>
</code>```

As I expected it to happen, the file in the working directory was replaced/updated with the requested older version, but I lost the later versions in the repository, got a message like "... detached head...".

Any guiding principles here would be appreciated.  Thanks.

答:
If you have a special commit like abc123456 and in that commit the file was good, you just need to ...

```<code>git checkout abc123456 path/to/file
</code>```

with this command you will find in stage that version of the file.

You can also use branches:

```<code>git checkout old-branch-name path/to/file
</code>```

Body:
I should think that getting a previous version is one of source control's premier features, and should be simple, yet it seems like a treasure hunt finding git solution.

I came across stackoverflow question How can I check out a particular version of one file in Git?.  To paraphrase the key thing:

git checkout <commit hash from git log output>

As I expected it to happen, the file in the working directory was replaced/updated with the requested older version, but I lost the later versions in the repository, got a message like "... detached head...".

Any guiding principles here would be appreciated.  Thanks.

Body:
If you have a special commit like abc123456 and in that commit the file was good, you just need to ...

git checkout abc123456 path/to/file

with this command you will find in stage that version of the file.

You can also use branches:

git checkout old-branch-name path/to/file


答:
It's hard to tell without a data sample, but I think this is what you want to do:

```<code>// might want to verify that all three arrays are the same size before doing this
for i in 0..<tblID.length {
    csvText.append("\(tblID[i]),\(tblUser[i]),\(tblEmployee[i])\n")
}
</code>```

Currently you're just trying to append the entire array to the string (which isn't even allowed), one after another, when I think you want to access the contents of each array.

Title: Loop an array - Cannot invoke append

Body:
It's hard to tell without a data sample, but I think this is what you want to do:

// might want to verify that all three arrays are the same size before doing this
for i in 0..<tblID.length {
    csvText.append("\(tblID[i]),\(tblUser[i]),\(tblEmployee[i])\n")
}

Currently you're just trying to append the entire array to the string (which isn't even allowed), one after another, when I think you want to access the contents of each array.


问:
Vert.x verticals approach
Wanted to understand the approach we should follow if we have to build multiple (three in my case) APIs in Vert.x

Should we have separate verticals running for each API i.e. Have a master verticle, and three verticles for each of these. Master verticle sends message to each verticle and that verticle takes care of formulating message and send it back

OR

Have a single verticle, just route it to separate methods with method calls

Please suggest how we should decide on the approach.

答:
Your 1st option is not so good, because usually you don't need master verticle for load balancing inside VM. Read Scaling - sharing TCP servers section.

You can run all APIs in one verticle or one API per one verticle. 1st option is easy to scale inside 1 VM (read URL above), but 2nd option is more flexible for scalability across multiple servers and development, however it requires load balancer (you can use nginx or HAProxy).

Title: Vert.x verticals approach

ContentLicense: CC BY-SA 4.0


问:
Android CAMERA 2 API captures 0kb images & gives a full white preview. Shows no errors or warnings on logcat
I use Android CAMERA 2 API for the camera2 supporting phones on my app. Works great, but some times it captures 0kb images & gives a full white preview. Shows no errors or warnings on logcat. Below is my camera image capture & save code:

```<code>protected void takePictureViaCamera2() {
    if (null == cameraDevice) {
        Log.e(TAG, "cameraDevice is null");
        return;
    }
    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
        Size[] jpegSizes = null;
        if (characteristics != null) {
            jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
        }
        int width = 640;
        int height = 480;
        if (jpegSizes != null && 0 < jpegSizes.length) {
            width = jpegSizes[0].getWidth();
            height = jpegSizes[0].getHeight();
        }
        ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
        List<Surface> outputSurfaces = new ArrayList<Surface>(2);
        outputSurfaces.add(reader.getSurface());
        outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
        final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(reader.getSurface());
        captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        // Orientation
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
        //final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
        final File file = createImageFile();
        final String checkPath = file.getParent();
        Log.e("checkPath", checkPath);
        //photoFile = createImageFile();
        //photoFilePath  = photoFile.getParent();
        //Log.e("photoFilePath", photoFilePath);
        ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);
                    save(bytes);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Log.e("readerListenerFNF_EX", e + "");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("readerListenerIO_EX", e + "");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("readerListener_EX", e + "");
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }

            private void save(byte[] bytes) throws IOException {
                OutputStream output = null;
                try {
                    output = new FileOutputStream(file);
                    //output = new FileOutputStream(photoFile);
                    output.write(bytes);
                } finally {
                    if (null != output) {
                        output.close();
                    }
                }
            }
        };
        reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
        final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
                Toast.makeText(TravelChargesCamera2Activity.this, "Saved***:" + file, Toast.LENGTH_SHORT).show();
                createCameraPreview();
                closeCamera();

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            synchronized (this) {
                                wait(5000);

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        toolbar.setVisibility(View.VISIBLE);
                                        header.setVisibility(View.VISIBLE);
                                        assessorTraveldetails_scroll.setVisibility(View.VISIBLE);
                                        camera2Layout.setVisibility(View.GONE);

                                        try {

                                            if (!file.getParentFile().isDirectory()) {

                                                travelDirectory = new File(checkPath);
                                                Log.e("travelDir==created==", travelDirectory + "");
                                            } else {

                                                travelDirectory = file.getParentFile();
                                                Log.e("travelDir==exists==", travelDirectory + "");
                                            }

                                            files = travelDirectory.listFiles();
                                            Log.e("files", files + "");

                                            // removes old images from view
                                            // prevents  display duplication
                                            travelGallery.removeAllViews();

                                            // loop displays the photos captured on Horizontal ScrollView
                                            for (File picFile : files) {
                                                travelGallery.addView(insertPhoto(picFile.getAbsolutePath()));

                                                byte[] byteArray = ImageUtils.fileToByteArray(file);
                                                Log.e("byteArray", byteArray + "");
                                            }

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            Log.e("file", e + "");
                                        }
                                    }
                                });

                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Log.e("InterruptedException", e + "");
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e("Exception", e + "");
                        }
                    }
                };
                thread.start();

            }
        };
        cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(CameraCaptureSession session) {
                try {
                    session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {
            }
        }, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
        Log.e("CameraAccessException", e + "");
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("takePictureViaCamera2", e + "");
    }
}

private File createImageFile() throws IOException {
    // Create an image file name

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String uniqueId = UUID.randomUUID().toString();
    String imageFileName = "CAP_" + timeStamp + "_" + uniqueId;

    String bCode = "";

    masterMap = (LinkedTreeMap) gson.fromJson(batchMasterObject.getMasterJson(), Object.class);
    auditMap = (LinkedTreeMap) masterMap.get("2001");
    if ((auditMap.get("batchCode") != null && !auditMap.get("batchCode").equals(""))) {
        bCode = auditMap.get("batchCode").toString();
    } else if (auditMap.get("cbc") != null && !auditMap.get("cbc").equals("")) {
        bCode = auditMap.get("cbc").toString();
    }

    File storageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "/" + bCode + "/Travel/");

    if (!storageDir.exists()) {
        storageDir.mkdirs();
    }
    String checkPath = storageDir.getPath();
    Log.e("checkPath", checkPath);

    Toast.makeText(getApplicationContext(), checkPath, Toast.LENGTH_LONG).show();

    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = storageDir.getAbsolutePath();
    return image;
}
</code>```

Could any one help on this?

NOTE: The camera, captures and stores an image file as intended, but the file size is 0kb. When the image file is opened on phone or pc, it says "Unsupported format"

答:
It looks like you're taking your final JPEG capture as the very first frame.

This means the camera's auto-exposure routines have not had any time to work (since you're grabbing the first frame), so the image will be captured with the initial settings hardcoded into the camera driver.  This may work for some scenes, but in others, the image will be far too bright or far too dark.

For best results, you should first let the camera meter for a while, until auto-exposure and auto-focus are converged.

Generally, this can be done by setting up a low-resolution preview output (use a SurfaceTexture for example), and running it for a second or two (or wait until a CaptureResult has an AE_STATE of CONVERGED).  Then issue the JPEG capture.

Body:
I use Android CAMERA 2 API for the camera2 supporting phones on my app. Works great, but some times it captures 0kb images & gives a full white preview. Shows no errors or warnings on logcat. Below is my camera image capture & save code:

protected void takePictureViaCamera2() {
    if (null == cameraDevice) {
        Log.e(TAG, "cameraDevice is null");
        return;
    }
    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
        Size[] jpegSizes = null;
        if (characteristics != null) {
            jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
        }
        int width = 640;
        int height = 480;
        if (jpegSizes != null && 0 < jpegSizes.length) {
            width = jpegSizes[0].getWidth();
            height = jpegSizes[0].getHeight();
        }
        ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
        List<Surface> outputSurfaces = new ArrayList<Surface>(2);
        outputSurfaces.add(reader.getSurface());
        outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
        final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(reader.getSurface());
        captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        // Orientation
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
        //final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg");
        final File file = createImageFile();
        final String checkPath = file.getParent();
        Log.e("checkPath", checkPath);
        //photoFile = createImageFile();
        //photoFilePath  = photoFile.getParent();
        //Log.e("photoFilePath", photoFilePath);
        ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);
                    save(bytes);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Log.e("readerListenerFNF_EX", e + "");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("readerListenerIO_EX", e + "");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("readerListener_EX", e + "");
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }

            private void save(byte[] bytes) throws IOException {
                OutputStream output = null;
                try {
                    output = new FileOutputStream(file);
                    //output = new FileOutputStream(photoFile);
                    output.write(bytes);
                } finally {
                    if (null != output) {
                        output.close();
                    }
                }
            }
        };
        reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
        final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
                Toast.makeText(TravelChargesCamera2Activity.this, "Saved***:" + file, Toast.LENGTH_SHORT).show();
                createCameraPreview();
                closeCamera();

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            synchronized (this) {
                                wait(5000);

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        toolbar.setVisibility(View.VISIBLE);
                                        header.setVisibility(View.VISIBLE);
                                        assessorTraveldetails_scroll.setVisibility(View.VISIBLE);
                                        camera2Layout.setVisibility(View.GONE);

                                        try {

                                            if (!file.getParentFile().isDirectory()) {

                                                travelDirectory = new File(checkPath);
                                                Log.e("travelDir==created==", travelDirectory + "");
                                            } else {

                                                travelDirectory = file.getParentFile();
                                                Log.e("travelDir==exists==", travelDirectory + "");
                                            }

                                            files = travelDirectory.listFiles();
                                            Log.e("files", files + "");

                                            // removes old images from view
                                            // prevents  display duplication
                                            travelGallery.removeAllViews();

                                            // loop displays the photos captured on Horizontal ScrollView
                                            for (File picFile : files) {
                                                travelGallery.addView(insertPhoto(picFile.getAbsolutePath()));

                                                byte[] byteArray = ImageUtils.fileToByteArray(file);
                                                Log.e("byteArray", byteArray + "");
                                            }

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            Log.e("file", e + "");
                                        }
                                    }
                                });

                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Log.e("InterruptedException", e + "");
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e("Exception", e + "");
                        }
                    }
                };
                thread.start();

            }
        };
        cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(CameraCaptureSession session) {
                try {
                    session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {
            }
        }, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
        Log.e("CameraAccessException", e + "");
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("takePictureViaCamera2", e + "");
    }
}

private File createImageFile() throws IOException {
    // Create an image file name

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String uniqueId = UUID.randomUUID().toString();
    String imageFileName = "CAP_" + timeStamp + "_" + uniqueId;

    String bCode = "";

    masterMap = (LinkedTreeMap) gson.fromJson(batchMasterObject.getMasterJson(), Object.class);
    auditMap = (LinkedTreeMap) masterMap.get("2001");
    if ((auditMap.get("batchCode") != null && !auditMap.get("batchCode").equals(""))) {
        bCode = auditMap.get("batchCode").toString();
    } else if (auditMap.get("cbc") != null && !auditMap.get("cbc").equals("")) {
        bCode = auditMap.get("cbc").toString();
    }

    File storageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "/" + bCode + "/Travel/");

    if (!storageDir.exists()) {
        storageDir.mkdirs();
    }
    String checkPath = storageDir.getPath();
    Log.e("checkPath", checkPath);

    Toast.makeText(getApplicationContext(), checkPath, Toast.LENGTH_LONG).show();

    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = storageDir.getAbsolutePath();
    return image;
}

Could any one help on this?

NOTE: The camera, captures and stores an image file as intended, but the file size is 0kb. When the image file is opened on phone or pc, it says "Unsupported format"


问:
How to recursively build a list using a callback and iterating through the children?
I'm unsure on how to build this list (which is a string) and then returning as one complete string.
I've worked past my last issue but I think this one is realy bugging me. buildItem() should iterate through item, and then recursively build a list while getting the totalCost from another callback. I know it works asynchronously...

```<code>buildItem(data, function(html){
    $('#nestable ol').append(html);
});
</code>```

Should append the 'final' html string that's created from being appended throughout the file.

```<code>function buildItem(item, callback) {
    getTotalCost(item, function(totalCost) {
        var html = "<li class='dd-item' data-id='" + item.id + "' data-email='" + item.email + "' data-title='" + item.corporateTitle + "' data-name='" + item.firstName + " " + item.lastName + "' id='" + item.id + "'>";
        if (item.children && item.children.length > 0) {
            html += "<ol class='dd-list'>";
            $.each(item.children, function (index, sub) {
                buildItem(item, function(subHtml){
                    html += subHtml;
                })
            })
            html += "</ol>";
        }
        html += "</li>";
        callback(html);
    });
}
</code>```

I know that

```<code>buildItem(item, function(subHtml){
    html += subHtml;
})
</code>```

shouldn't work since javascript is asynchronous. I'm just not sure on how to return from a recursive function? If I were to do something like

```<code>buildItem(item, function(subHtml){
    callback(subHtml);
})
</code>```

You'll get duplicate values because you'll have the starting value and it's children, but since you're also calling it back you'll get the children outside of the starting value. So it'll look like

```<code>1
     a
     b
     c
     d
     e
a
b
c
d
e
</code>```

So what's the best way to approach a solution? I was thinking of making another function, hypothetically a buildChild(sub) that returned html, but the same issue with asynchronous is going to come up where the return will be undefined. I've read some of the threads where you can handle asynchronous values with callbacks, but I'm not sure on how to do it with recursion here.

getTotalCost is another callback function that shouldn't mean much, I removed the line by accident but I just need the totalCost from a database.

```<code>function getTotalCost(item, callback) {
    $.ajax({
        dataType: "json",
        url: "/retrieveData.do?item=" + item.email,
        success: function(data) {
            var totalCost = 0;
            for (var i = 0; i < data.length; i++) {
                totalCost += parseFloat(data[i].cost);
            }
            callback(totalCost);
        }
    });
}
</code>```

答:
You can mix slow ajax requests with logic and recursion if you execute your code via synchronous executor nsynjs.

Step 1. Write your logic as if it was synchronous, and place it into function:

```<code>function process(item) {
    function getTotalCost(item) {
        var data = jQueryGetJSON(nsynjsCtx, "/retrieveData.do?item=" + item.email).data;
        var totalCost = 0;
        for (var i = 0; i < data.length; i++) {
            totalCost += parseFloat(data[i].cost);
        }
        return totalCost;
    };

    function buildItem(item) {
        const totalCost = getTotalCost(item);
        var html = "<li class='dd-item' data-id='" + item.id + "' data-email='" + item.email + "' data-title='" + item.corporateTitle + "' data-name='" + item.firstName + " " + item.lastName + "' id='" + item.id + "'>";

        if (item.children && item.children.length > 0) {
            html += '<ol class="dd-list">';
            for (var i=0; i<item.children.length; i++)
                html += buildItem(item.children[i]);
            html += "</ol>";
        }
        html += "</li>";
        return html;
    };

    return buildItem(item);
};
</code>```

Step 2: run it via nsynjs:

```<code>nsynjs.run(process,{},item,function (itemHTML) {
    console.log("all done",itemHTML);
});
</code>```

Please see more examples here: https://github.com/amaksr/nsynjs/tree/master/examples

Body:
I'm unsure on how to build this list (which is a string) and then returning as one complete string.
I've worked past my last issue but I think this one is realy bugging me. buildItem() should iterate through item, and then recursively build a list while getting the totalCost from another callback. I know it works asynchronously...

buildItem(data, function(html){
    $('#nestable ol').append(html);
});

Should append the 'final' html string that's created from being appended throughout the file.

function buildItem(item, callback) {
    getTotalCost(item, function(totalCost) {
        var html = "
";
        if (item.children && item.children.length > 0) {
            html += "
";
            $.each(item.children, function (index, sub) {
                buildItem(item, function(subHtml){
                    html += subHtml;
                })
            })
            html += "
";
        }
        html += "
";
        callback(html);
    });
}

I know that

buildItem(item, function(subHtml){
    html += subHtml;
})

shouldn't work since javascript is asynchronous. I'm just not sure on how to return from a recursive function? If I were to do something like

buildItem(item, function(subHtml){
    callback(subHtml);
})

You'll get duplicate values because you'll have the starting value and it's children, but since you're also calling it back you'll get the children outside of the starting value. So it'll look like

1
     a
     b
     c
     d
     e
a
b
c
d
e

So what's the best way to approach a solution? I was thinking of making another function, hypothetically a buildChild(sub) that returned html, but the same issue with asynchronous is going to come up where the return will be undefined. I've read some of the threads where you can handle asynchronous values with callbacks, but I'm not sure on how to do it with recursion here.

getTotalCost is another callback function that shouldn't mean much, I removed the line by accident but I just need the totalCost from a database.

function getTotalCost(item, callback) {
    $.ajax({
        dataType: "json",
        url: "/retrieveData.do?item=" + item.email,
        success: function(data) {
            var totalCost = 0;
            for (var i = 0; i < data.length; i++) {
                totalCost += parseFloat(data[i].cost);
            }
            callback(totalCost);
        }
    });
}

Body:
You can mix slow ajax requests with logic and recursion if you execute your code via synchronous executor nsynjs.

Step 1. Write your logic as if it was synchronous, and place it into function:

function process(item) {
    function getTotalCost(item) {
        var data = jQueryGetJSON(nsynjsCtx, "/retrieveData.do?item=" + item.email).data;
        var totalCost = 0;
        for (var i = 0; i < data.length; i++) {
            totalCost += parseFloat(data[i].cost);
        }
        return totalCost;
    };

    function buildItem(item) {
        const totalCost = getTotalCost(item);
        var html = "<li class='dd-item' data-id='" + item.id + "' data-email='" + item.email + "' data-title='" + item.corporateTitle + "' data-name='" + item.firstName + " " + item.lastName + "' id='" + item.id + "'>";

        if (item.children && item.children.length > 0) {
            html += '<ol class="dd-list">';
            for (var i=0; i<item.children.length; i++)
                html += buildItem(item.children[i]);
            html += "</ol>";
        }
        html += "</li>";
        return html;
    };

    return buildItem(item);
};

Step 2: run it via nsynjs:

nsynjs.run(process,{},item,function (itemHTML) {
    console.log("all done",itemHTML);
});

Please see more examples here: https://github.com/amaksr/nsynjs/tree/master/examples


问:
how would you give name to bluetooth service in android things?
I created one simple service in android things to use Bluetooth BLE.when I try to test it with NRF connect app it's visible as "unknown service".I want to give name something like "Speed Service".how would I do it?</p>

答:
This is a factor controlled by the scanning app you are using, not necessarily your Android Things device. Bluetooth LE doesn't send metadata like a "service name" over the air. Services are identified by their UUID alone. If your device implements one of the standard service UUIDs, a scanner app like NRF Connect will probably recognize and display the service type.

As another example, our Bluetooth GATT Server sample implements the standard Current Time Service by using the UUID adopted by the Bluetooth SIG for that service.


问:
Send HTTP Request and properly ignore the Response in Javascript
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

```<code>function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}
</code>```

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?

答:
```<code>req.onreadystatechange=function() {
    if (req.readyState===4 && req.status===200) {
        var response=req.responseText;
    }
};
</code>```

This will capture the response into the "response" variable once the request has been completed

Body:
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?

Body:
req.onreadystatechange=function() {
    if (req.readyState===4 && req.status===200) {
        var response=req.responseText;
    }
};

This will capture the response into the "response" variable once the request has been completed


答:
When you just use git checkout <somehash>, then you will get into a detached HEAD. This happens because git checkout by default just switches branches, and specifying a commit instead of a branch gets you into a “branchless mode” (that’s what detached HEAD means).

If you want to get a single file from a different version, you also need to specify the path, i.e. git checkout <somehash> -- path/to/file. This will keep everything as it is and just replace the file at path/to/file with its version from <somehash>.

So this does overwrite the file. If you want to keep the current version as well, you should rename it first. Otherwise, you can also use a special syntax of git show for this

```<code>git show <somehash>:path/to/file > new_filename.ext
</code>```

This will essentially get the contents of the file from <somehash> and print it, so if you pipe it to file, you can extract a file from a different version into a different filename.

Title: How do I get a particular (older) version of a file from git repository without wiping out later versions?

Body:
When you just use git checkout <somehash>, then you will get into a detached HEAD. This happens because git checkout by default just switches branches, and specifying a commit instead of a branch gets you into a “branchless mode” (that’s what detached HEAD means).

If you want to get a single file from a different version, you also need to specify the path, i.e. git checkout <somehash> -- path/to/file. This will keep everything as it is and just replace the file at path/to/file with its version from <somehash>.

So this does overwrite the file. If you want to keep the current version as well, you should rename it first. Otherwise, you can also use a special syntax of git show for this

git show <somehash>:path/to/file > new_filename.ext

This will essentially get the contents of the file from <somehash> and print it, so if you pipe it to file, you can extract a file from a different version into a different filename.


问:
Automapper: Mapping a property value of an object to a string
Using Automapper, how do you handle the mapping of a property value on an object to an instance of a string.  Basically I have a list of Role objects and I want to use Automapper to map the content of each "name" property to a corresponding list of string (so I just end up with a list of strings).  I'm sure it has an obvious answer, but I can't find the mapping that I need to add to "CreateMap" to get it to work.

An example of the relevant code is shown below:

```<code>public class Role
{
   public Guid Id{get;set;}
   public string Name{get;set;}
   ...
   ...
}

// What goes in here?
Mapper.CreateMap<Role, string>().ForMember(....);

var allRoles = Mapper.Map<IList<Role>, IList<string>>(roles);
</code>```

答:
I love Automapper (and use it in a number of projects), but wouldn't this be easier with a simple LINQ statement?

```<code>var allRoles = from r in roles select r.Name
</code>```

The AutoMapper way of accomplishing this:

```<code>Mapper.CreateMap<Role, String>().ConvertUsing(r => r.Name);
</code>```

Body:
Using Automapper, how do you handle the mapping of a property value on an object to an instance of a string.  Basically I have a list of Role objects and I want to use Automapper to map the content of each "name" property to a corresponding list of string (so I just end up with a list of strings).  I'm sure it has an obvious answer, but I can't find the mapping that I need to add to "CreateMap" to get it to work.

An example of the relevant code is shown below:

public class Role
{
   public Guid Id{get;set;}
   public string Name{get;set;}
   ...
   ...
}

// What goes in here?
Mapper.CreateMap<Role, string>().ForMember(....);

var allRoles = Mapper.Map<IList<Role>, IList<string>>(roles);

Body:
I love Automapper (and use it in a number of projects), but wouldn't this be easier with a simple LINQ statement?

var allRoles = from r in roles select r.Name

The AutoMapper way of accomplishing this:

Mapper.CreateMap<Role, String>().ConvertUsing(r => r.Name);


问:
ArrayList updated inserting one row but Jtable still not refresh
I've to create a java swing app that allows the user to menage some Oracle tables.

I've implemented the JTable in this way:

```<code>public class TableModel extends AbstractTableModel{
        .
        .
        .

  public List <List <String> > result = null;
        .
        .
        .
  public void createTable(ResultSet r) throws SQLException {
    rs = r;
    numcols = getColumnCount();
    result = new ArrayList();
    while (rs.next()) {
      List <String> row = new ArrayList<>(numcols);
      for (int i=1; i<= numcols; i++)
          row.add(rs.getString(i).replace("00:00:00.0", "")); //just managing stuffs .. nothing important. Don't care of this replace.
      result.add(row);
     }
     fireTableStructureChanged();
   }

  public void addRow(){
    List <String> row = new ArrayList<>();
    for(int i=1;i<=getColumnCount();i++)
        row.add("");
    result.add(row);
    fireTableStructureChanged();
  }

  public Object getValueAt(int row, int col) {
    return result.get(row).get(col);
  }

  public int getColumnCount() {
  if (rs == null) {
     return 0;
  }
  try {
     return rs.getMetaData().getColumnCount();
  } catch (SQLException e) {
     System.err.println("error in colcount");
     return 0;
  }
 }

  public int getRowCount() {
  int totalRows = 0;
  try {
    rs.last();
    totalRows = rs.getRow();
    rs.beforeFirst();
  } catch(Exception ex)  {
        return 0;
  }
    return totalRows ;
  }
}
</code>```

so, I store database data into the arraylist and then I print the table using the arraylist.
Now in the addRow() function I add to that arraylist an empty record (in my mind an empty record is a record composed of all null ("") strings).
Finally using the fireTableStructureChanged() method I expect the table to refresh itself.. but this will never occur and I don't understand why.

I've already checked that the new row is successfully loaded into the arraylist:
I got all the data stored in the table of the Database into the arraylist and the new row is successfully loaded in the arraylist.
so I swear the problem is about that fireTableStructureChanged() method.

Thanks :3

答:
Try using fireTableRowsInserted(int firstRow, int lastRow) instead of fireTableStructureChanged()

Here's the javadoc for the structure changed ...

Notifies all listeners that the table's structure has changed. The number of columns in the table, and the names and types of the new columns may be different from the previous state. If the JTable receives this event and its autoCreateColumnsFromModel flag is set it discards any table columns that it had and reallocates default columns in the order they appear in the model. This is the same as calling setModel(TableModel) on the JTable.

So that one will only work if the columns types changed ...

If you are lazy go for this one: fireTableDataChanged()

Body:
I've to create a java swing app that allows the user to menage some Oracle tables.

I've implemented the JTable in this way:

public class TableModel extends AbstractTableModel{
        .
        .
        .

  public List <List <String> > result = null;
        .
        .
        .
  public void createTable(ResultSet r) throws SQLException {
    rs = r;
    numcols = getColumnCount();
    result = new ArrayList();
    while (rs.next()) {
      List <String> row = new ArrayList<>(numcols);
      for (int i=1; i<= numcols; i++)
          row.add(rs.getString(i).replace("00:00:00.0", "")); //just managing stuffs .. nothing important. Don't care of this replace.
      result.add(row);
     }
     fireTableStructureChanged();
   }

  public void addRow(){
    List <String> row = new ArrayList<>();
    for(int i=1;i<=getColumnCount();i++)
        row.add("");
    result.add(row);
    fireTableStructureChanged();
  }

  public Object getValueAt(int row, int col) {
    return result.get(row).get(col);
  }

  public int getColumnCount() {
  if (rs == null) {
     return 0;
  }
  try {
     return rs.getMetaData().getColumnCount();
  } catch (SQLException e) {
     System.err.println("error in colcount");
     return 0;
  }
 }

  public int getRowCount() {
  int totalRows = 0;
  try {
    rs.last();
    totalRows = rs.getRow();
    rs.beforeFirst();
  } catch(Exception ex)  {
        return 0;
  }
    return totalRows ;
  }
}

so, I store database data into the arraylist and then I print the table using the arraylist.
Now in the addRow() function I add to that arraylist an empty record (in my mind an empty record is a record composed of all null ("") strings).
Finally using the fireTableStructureChanged() method I expect the table to refresh itself.. but this will never occur and I don't understand why.

I've already checked that the new row is successfully loaded into the arraylist:
I got all the data stored in the table of the Database into the arraylist and the new row is successfully loaded in the arraylist.
so I swear the problem is about that fireTableStructureChanged() method.

Thanks :3


问:
Is it good practice having separate database for different pages in a website?
I have a website xyz.com that is going to be launched in an online server. I have three pages x, y and z (suppose x is for image gallery, y is for video gallery, and z is for another gallery). I need to have a comment section for each of the pages, and user input is going to be stored in database. There need not be any relation between the comments in different pages, or in another words, comment from one page doesn't have to relate with the comments in another pages. I want to deal them separately.

Now my question is:

Should I use one database and create just three different tables for each pages or should I create three completely different database each of them having one table? Which one is good practice?

答:
You do not need to create the different databases and why would you?

Create single database

Create 2 tables "galleries" and "comments"

```<code>galleries (id|title|name|type|date etc....)
</code>```

Gallery type can be "image" or "video" or etc...

when you load data for image(s) page do

```<code>select * from galleries where type='image'
</code>```

and when for video

```<code>select * from galleries where type='video'
</code>```

so on...

For comments:

create table

```<code>comments (id|comment_text|gallery_type...)
</code>```

where gallery_type is the foreign key

If your gallery types are lots you can always create a sperate table for gallery_types and give reference accordingly.

Body:
You do not need to create the different databases and why would you?

Create single database

Create 2 tables "galleries" and "comments"

galleries (id|title|name|type|date etc....)

Gallery type can be "image" or "video" or etc...

when you load data for image(s) page do

select * from galleries where type='image'

and when for video

select * from galleries where type='video'

so on...

For comments:

create table

comments (id|comment_text|gallery_type...)

where gallery_type is the foreign key

If your gallery types are lots you can always create a sperate table for gallery_types and give reference accordingly.


问:
What's the theoretically fastest access to member of nullable type in C#?
I have a field of a nullable type with a value other than null.
Which of the methods below is the fastest, in theory:

Null conditional member access

```<code>ThisCantBeNull?.SomeMember
</code>```

Cast to non-nullable

```<code>((MyType)ThisCantBeNull).SomeMember
</code>```

Use of the Value member of nullable types

```<code>ThisCantBeNull.Value.SomeMember
</code>```

Note that this is only a theoretical question, such minor differences do not matter, I'm only interested in how the language works and what goes on in the background.

答:
Just for curiosity:

```<code>public struct MyType
{
    public int SomeMember { get; set; }
}
</code>```

Some very raw tests, disabling compiler optimizations:

```<code>MyType? thisCantBeNull = new MyType();
MyType someDefaultValue = new MyType();

var t1 = new Action(() => { var r = (thisCantBeNull ?? someDefaultValue).SomeMember; });
var t2 = new Action(() => { var r = ((MyType)thisCantBeNull).SomeMember; });
var t3 = new Action(() => { var r = thisCantBeNull.Value.SomeMember; });
var t4 = new Action(() => { var r = thisCantBeNull.GetValueOrDefault().SomeMember; });

const int times = 1000 * 1000 * 1000;

var r1 = t1.RunNTimes(times);
// Elapsed Timespan = 00:00:14.45115

var r2 = t2.RunNTimes(times);
// Elapsed Timespan = 00:00:07.9415388

var r3 = t3.RunNTimes(times);
// Elapsed Timespan = 00:00:08.0096765

var r4 = t4.RunNTimes(times);
// Elapsed Timespan = 00:00:07.4732878
</code>```

The same tests, enabling compiler optimizations:

```<code>var r1 = t1.RunNTimes(times);
// Elapsed Timespan = 00:00:02.9142143

var r2 = t2.RunNTimes(times);
// Elapsed Timespan = 00:00:02.4417182

var r3 = t3.RunNTimes(times);
// Elapsed Timespan = 00:00:02.6278304

var r4 = t4.RunNTimes(times);
// Elapsed Timespan = 00:00:02.1725020
</code>```

Where RunNTimes is:

```<code>public static TimeSpan RunNTimes(this Action a, int nTimes = 1)
{
    if (nTimes == 0)
        throw new ArgumentException("0 times not allowed", nameof(nTimes));

    var stopwatch = new Stopwatch();

    stopwatch.Start();
    for (int i = 0; i < nTimes; ++i)
        a();
    stopwatch.Stop();

    return stopwatch.Elapsed;;
}
</code>```

Body:
I have a field of a nullable type with a value other than null.
Which of the methods below is the fastest, in theory:

Null conditional member access

ThisCantBeNull?.SomeMember

Cast to non-nullable

((MyType)ThisCantBeNull).SomeMember

Use of the Value member of nullable types

ThisCantBeNull.Value.SomeMember

Note that this is only a theoretical question, such minor differences do not matter, I'm only interested in how the language works and what goes on in the background.

Body:
Just for curiosity:

public struct MyType
{
    public int SomeMember { get; set; }
}

Some very raw tests, disabling compiler optimizations:

MyType? thisCantBeNull = new MyType();
MyType someDefaultValue = new MyType();

var t1 = new Action(() => { var r = (thisCantBeNull ?? someDefaultValue).SomeMember; });
var t2 = new Action(() => { var r = ((MyType)thisCantBeNull).SomeMember; });
var t3 = new Action(() => { var r = thisCantBeNull.Value.SomeMember; });
var t4 = new Action(() => { var r = thisCantBeNull.GetValueOrDefault().SomeMember; });

const int times = 1000 * 1000 * 1000;

var r1 = t1.RunNTimes(times);
// Elapsed Timespan = 00:00:14.45115

var r2 = t2.RunNTimes(times);
// Elapsed Timespan = 00:00:07.9415388

var r3 = t3.RunNTimes(times);
// Elapsed Timespan = 00:00:08.0096765

var r4 = t4.RunNTimes(times);
// Elapsed Timespan = 00:00:07.4732878

The same tests, enabling compiler optimizations:

var r1 = t1.RunNTimes(times);
// Elapsed Timespan = 00:00:02.9142143

var r2 = t2.RunNTimes(times);
// Elapsed Timespan = 00:00:02.4417182

var r3 = t3.RunNTimes(times);
// Elapsed Timespan = 00:00:02.6278304

var r4 = t4.RunNTimes(times);
// Elapsed Timespan = 00:00:02.1725020

Where RunNTimes is:

public static TimeSpan RunNTimes(this Action a, int nTimes = 1)
{
    if (nTimes == 0)
        throw new ArgumentException("0 times not allowed", nameof(nTimes));

    var stopwatch = new Stopwatch();

    stopwatch.Start();
    for (int i = 0; i < nTimes; ++i)
        a();
    stopwatch.Stop();

    return stopwatch.Elapsed;;
}