问:
Bootstrap datetimepicker without default initial value
I am using bootstrap datetimepicker I wanted to remove default selected date.

$("#datetimepicker1").datetimepicker({ format: 'MM/DD/YYYY', minDate:new Date() });

答:
You can set useCurrent:false for your datetimepicer like

```<code>  $(document).ready(function () {
     var date = new Date();

     // subtract a day
     date.setDate(date.getDate() - 1);
     $('#datetimepicker1').datetimepicker({
          useCurrent: false, format: 'MM/DD/YYYY', minDate:date
     });
  });
</code>```

JSFIDDLE

Body:
You can set useCurrent:false for your datetimepicer like

  $(document).ready(function () {
     var date = new Date();

     // subtract a day
     date.setDate(date.getDate() - 1);
     $('#datetimepicker1').datetimepicker({
          useCurrent: false, format: 'MM/DD/YYYY', minDate:date
     });
  });

JSFIDDLE


来源: stackexchange

问:
Best way to read/parse a untyped binary file in Delphi
I would like to know what is the best way to parse an untyped binary file. For example, a EBML file. (http://ebml.sourceforge.net/). EBML is basically a binary xml file. It can store basically anything, but its predominate use right now are MKV video files (matroska).

To read a EBML file at the byte level, reading the header making sure it is a EBML file and retrieving information on the file. MKV files can be huge, 1-30gb in size.

The binary file could be anything, jpeg, bmp, avi etc ...
I just want to learn how to read them.

答:
Just use a TFileStream, like so ...</p>

```<code>var MyFile: TStream;
begin
MyFile := TFileStream.Create( fmOpenRead, FileName);
try
  // Read stuff
  MyFile.ReadBuffer( MyVariable, SizeOf( MyVariable));
  // etc.
finally
  MyFile.Free
  end;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Just use a TFileStream, like so ...

var MyFile: TStream;
begin
MyFile := TFileStream.Create( fmOpenRead, FileName);
try
  // Read stuff
  MyFile.ReadBuffer( MyVariable, SizeOf( MyVariable));
  // etc.
finally
  MyFile.Free
  end;


问:
ExpressJS Redirect to Get Function Once Finished
I'd like to find a way to not repeat myself.

Most of my /post/ commands should update something then display the same contents as the /get/ command.

At present I am repeating myself like:

```<code>.get(function(req, res) {
  act({
    role: 'earnings',
    cmd: 'get',
    wc: req.params.wc,
    earner_id: req.params.earner_id,
  })
  .then(function(earnings) {
    return act({
      role: 'earnings',
      cmd: 'format',
      earnings: earnings,
      date: true,
      time: true,
      note: true,
      total: true
    })
  })
  .then(function(formatted_earnings) {
    if (formatted_earnings.length > 0)
      res.render( 'earnings-wc-earner', {
        formatted_earnings: formatted_earnings
      })
    else
      res.render('error', {
        message: "No earnings found."
      })
  })
  .catch(function (err) {
    res.send(err);
  })
})

.post(function(req, res) {
  act({
    role: 'earnings',
    cmd: 'add',
    wc: req.body.wc,
    earner_id: req.body.earner_id,
    datetime: req.body.datetime,
    earnings: req.body.earnings
  })
  .then(function(earnings) {
    return act({
      role: 'earnings',
      cmd: 'get',
      wc: req.params.wc,
      earner_id: req.params.earner_id,
    })
  .then(function(earnings) {
    // would love to redirect to get right about now
    // especially with a success message
    return act({
      role: 'earnings',
      cmd: 'format',
      earnings: earnings,
      date: true,
      time: true,
      note: true,
      total: true
    })
  })
  .then(function(formatted_earnings) {
    if (formatted_earnings.length > 0)
      res.render( 'earnings-wc-earner', {
        message: "Successfully added manual payment.",
        formatted_earnings: formatted_earnings
      })
    else
      res.render('error', {
        message: "No earnings found."
      })
  })
  .catch(function (err) {
    res.send(err);
  })
})
</code>```

Is there anyway I can do something like redirect to get in the first .then chain of the post function?

答:
If its Express you can use .all() instead of .get() and .post().

In general you can just put that code in a separate module also.
And I would switch to async/await and use other new JS features to make your code a bit cleaner.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to find a way to not repeat myself.

Most of my /post/ commands should update something then display the same contents as the /get/ command.

At present I am repeating myself like:

.get(function(req, res) {
  act({
    role: 'earnings',
    cmd: 'get',
    wc: req.params.wc,
    earner_id: req.params.earner_id,
  })
  .then(function(earnings) {
    return act({
      role: 'earnings',
      cmd: 'format',
      earnings: earnings,
      date: true,
      time: true,
      note: true,
      total: true
    })
  })
  .then(function(formatted_earnings) {
    if (formatted_earnings.length > 0)
      res.render( 'earnings-wc-earner', {
        formatted_earnings: formatted_earnings
      })
    else
      res.render('error', {
        message: "No earnings found."
      })
  })
  .catch(function (err) {
    res.send(err);
  })
})

.post(function(req, res) {
  act({
    role: 'earnings',
    cmd: 'add',
    wc: req.body.wc,
    earner_id: req.body.earner_id,
    datetime: req.body.datetime,
    earnings: req.body.earnings
  })
  .then(function(earnings) {
    return act({
      role: 'earnings',
      cmd: 'get',
      wc: req.params.wc,
      earner_id: req.params.earner_id,
    })
  .then(function(earnings) {
    // would love to redirect to get right about now
    // especially with a success message
    return act({
      role: 'earnings',
      cmd: 'format',
      earnings: earnings,
      date: true,
      time: true,
      note: true,
      total: true
    })
  })
  .then(function(formatted_earnings) {
    if (formatted_earnings.length > 0)
      res.render( 'earnings-wc-earner', {
        message: "Successfully added manual payment.",
        formatted_earnings: formatted_earnings
      })
    else
      res.render('error', {
        message: "No earnings found."
      })
  })
  .catch(function (err) {
    res.send(err);
  })
})

Is there anyway I can do something like redirect to get in the first .then chain of the post function?


问:
Copy a list using Non blank and Blank rows as a head and tail loop
HI so I have a set of data that I would like to copy. Basically I would like to create an if function. If we search for a blank row in column B and it is blank, loop to the next row, and continue until the first non blank row. If we hit a non blank copy all the cells from all the blank rows in column c.

```<code>    Sub NotReadys()

 ' NotReadys Macro'
Dim Z As Integer 'Supplier Beginning Row'
Dim X As Integer 'Next Non Blank row'
Dim Q As Integer '# of suppliers'
Dim Y As Integer 'Paste Row'
Y = 6
'For T = 1 To 195

ActiveWindow.SmallScroll Down:=-33

Range("B" & Y).Select
Selection.Copy

Range("E" & Y).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("F" & Y).Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=TEXTJOIN(CHAR(10),FALSE,RC[-3]:R[30]C[-3])"
Range("F" & Y).Select
ActiveWindow.SmallScroll Down:=-30
Range("F" & Y).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Y = Y + 1
    Next T

    End Sub
</code>```

http://imgur.com/XGwB4XR

答:
I'm having difficulty understanding the structure of your data, but using For Each x In Selection might help you. I'm assuming that your data at least similar the below, where the supplier names are in column A, and POs are in column B

```
     |   A   |   B   |   C   |   D   |
-----|-------|-------|-------|-------|
  1  |   s1  |  PO1  |       |       |
-----|-------|-------|-------|-------|
  2  |   s2  |  PO2  |       |       |
-----|-------|-------|-------|-------|
  3  |   s3  |       |       |       |
-----|-------|-------|-------|-------|
  4  |   s4  |  PO3  |       |       |
-----|-------|-------|-------|-------|
```

This code will copy any supplier and PO (where PO isn't blank) to columns C and D:

```<code>outRow = 1  ' Set this to the index of the first row you want to output to

' Run through each cell in Selection, left to right, top to bottom
For Each selCell In Selection
  ' Check for non-blank, but only if we're looking at column 2 (B)
  If selCell.Column = 2 & selCell <> "" then
    ' Store the selected Row and Column
    sRow = selCell.Row
    sCol = selCell.Column

    ' Has the effect of prefixing ActiveSheet to any values that start with "."
    With ActiveSheet
      ' Copy value from cols 1 and 2 (A & B) to col 3 and 4 (C & D)
      .Cells(outRow, 3).Value = .Cells(sRow, sCol - 1).Value
      .Cells(outRow, 4).Value = selCell.Value
    End With

    outRow = outRow +1  ' Moves to next output row
  End If
Next
</code>```

In my example, assuming you selected A1:B4 before running the function, you will get the below output.

```
     |   A   |   B   |   C   |   D   |
-----|-------|-------|-------|-------|
  1  |   s1  |  PO1  |   s1  |  PO1  |
-----|-------|-------|-------|-------|
  2  |   s2  |  PO2  |   s2  |  PO2  |
-----|-------|-------|-------|-------|
  3  |   s3  |       |   s4  |  PO3  |
-----|-------|-------|-------|-------|
  4  |   s4  |  PO3  |       |       |
-----|-------|-------|-------|-------|
```

I'm guessing that you're using the Macro recording option to produce the code you have; this is a great way to learn how VBA works (most of us have done this at some point), but doesn't produce nice code. The built in documentation in Excel is actually really good and is worth looking at when you hit the limitations of the recorder.

Edit: The more I look at your question, the less sure I am about what you're asking, but hopefully the above at least pushes you in the right direction.

Body:
HI so I have a set of data that I would like to copy. Basically I would like to create an if function. If we search for a blank row in column B and it is blank, loop to the next row, and continue until the first non blank row. If we hit a non blank copy all the cells from all the blank rows in column c.

    Sub NotReadys()

 ' NotReadys Macro'
Dim Z As Integer 'Supplier Beginning Row'
Dim X As Integer 'Next Non Blank row'
Dim Q As Integer '# of suppliers'
Dim Y As Integer 'Paste Row'
Y = 6
'For T = 1 To 195

ActiveWindow.SmallScroll Down:=-33

Range("B" & Y).Select
Selection.Copy

Range("E" & Y).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("F" & Y).Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=TEXTJOIN(CHAR(10),FALSE,RC[-3]:R[30]C[-3])"
Range("F" & Y).Select
ActiveWindow.SmallScroll Down:=-30
Range("F" & Y).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Y = Y + 1
    Next T

    End Sub

http://imgur.com/XGwB4XR

Body:
I'm having difficulty understanding the structure of your data, but using For Each x In Selection might help you. I'm assuming that your data at least similar the below, where the supplier names are in column A, and POs are in column B

     |   A   |   B   |   C   |   D   |
-----|-------|-------|-------|-------|
  1  |   s1  |  PO1  |       |       |
-----|-------|-------|-------|-------|
  2  |   s2  |  PO2  |       |       |
-----|-------|-------|-------|-------|
  3  |   s3  |       |       |       |
-----|-------|-------|-------|-------|
  4  |   s4  |  PO3  |       |       |
-----|-------|-------|-------|-------|

This code will copy any supplier and PO (where PO isn't blank) to columns C and D:

outRow = 1  ' Set this to the index of the first row you want to output to

' Run through each cell in Selection, left to right, top to bottom
For Each selCell In Selection
  ' Check for non-blank, but only if we're looking at column 2 (B)
  If selCell.Column = 2 & selCell <> "" then
    ' Store the selected Row and Column
    sRow = selCell.Row
    sCol = selCell.Column

    ' Has the effect of prefixing ActiveSheet to any values that start with "."
    With ActiveSheet
      ' Copy value from cols 1 and 2 (A & B) to col 3 and 4 (C & D)
      .Cells(outRow, 3).Value = .Cells(sRow, sCol - 1).Value
      .Cells(outRow, 4).Value = selCell.Value
    End With

    outRow = outRow +1  ' Moves to next output row
  End If
Next

In my example, assuming you selected A1:B4 before running the function, you will get the below output.

     |   A   |   B   |   C   |   D   |
-----|-------|-------|-------|-------|
  1  |   s1  |  PO1  |   s1  |  PO1  |
-----|-------|-------|-------|-------|
  2  |   s2  |  PO2  |   s2  |  PO2  |
-----|-------|-------|-------|-------|
  3  |   s3  |       |   s4  |  PO3  |
-----|-------|-------|-------|-------|
  4  |   s4  |  PO3  |       |       |
-----|-------|-------|-------|-------|

I'm guessing that you're using the Macro recording option to produce the code you have; this is a great way to learn how VBA works (most of us have done this at some point), but doesn't produce nice code. The built in documentation in Excel is actually really good and is worth looking at when you hit the limitations of the recorder.

Edit: The more I look at your question, the less sure I am about what you're asking, but hopefully the above at least pushes you in the right direction.


问:
RegEx to get section of URL after string in Javascript
I have the following URL:

```<code>http://data.test.com/api/v1/entity/1231
</code>```

And I need to get the text that is after v1/ and before / (between the slashes), in this case the word entity. I'm using the following regex, but what I get back is entity/1231 on group 1:

```<code>/^[^\#\?]+\/v1\/([^\?]+).*$/
</code>```

Any idea on how to get rid of 1231 or anything that comes after entity?

答:
You may capture the value you need into a capturing group with new RegExp("/v1/([^/]+)":

var str = "http://data.test.com/api/v1/entity/1231";
var res = str.match(new RegExp("/v1/([^/]+)"));
if (res)
    console.log(res[1]);```
</div>
</div>
</p>
<p>The <code>/v1/([^/]+)</code> matches:</p>
<ul>
<li><code>/v1/</code> - a literal string <code>/v1/</code></li>
<li><code>([^/]+)</code> - capturing group 1 matching one or more chars other than <code>/</code>.</li>
</ul>
<p>Thanks to the constructor notation in the RegExp definition, there is no need to escape forward slashes in the regex pattern.</p>
<p>Alternatively, since ECMAScript 2018 enabled lookbehind usage in the JavaScript <em>RegExp</em> patterns, you can also use a <strong>lookbehind-based approach</strong> to get the value you need directly as a whole match:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const str = "http://data.test.com/api/v1/entity/1231";
const res = str.match(/(?<=\/v1\/)[^\/]+/);
if (res) {
    console.log(res[0]);
}</code>```

Details:

(?<=\/v1\/) - a positive lookbehind that matches a location that is immediately preceded with /v1/ text

[^\/]+ - one or more chars other than a / char.

Body:
I have the following URL:

http://data.test.com/api/v1/entity/1231

And I need to get the text that is after v1/ and before / (between the slashes), in this case the word entity. I'm using the following regex, but what I get back is entity/1231 on group 1:

/^[^\#\?]+\/v1\/([^\?]+).*$/

Any idea on how to get rid of 1231 or anything that comes after entity?

Body:
You may capture the value you need into a capturing group with new RegExp("/v1/([^/]+)":

var str = "http://data.test.com/api/v1/entity/1231";
var res = str.match(new RegExp("/v1/([^/]+)"));
if (res)
    console.log(res[1]);

The /v1/([^/]+) matches:

/v1/ - a literal string /v1/

([^/]+) - capturing group 1 matching one or more chars other than /.

Thanks to the constructor notation in the RegExp definition, there is no need to escape forward slashes in the regex pattern.

Alternatively, since ECMAScript 2018 enabled lookbehind usage in the JavaScript RegExp patterns, you can also use a lookbehind-based approach to get the value you need directly as a whole match:

const str = "http://data.test.com/api/v1/entity/1231";
const res = str.match(/(?<=\/v1\/)[^\/]+/);
if (res) {
    console.log(res[0]);
}

Details:

(?<=\/v1\/) - a positive lookbehind that matches a location that is immediately preceded with /v1/ text

[^\/]+ - one or more chars other than a / char.

ContentLicense: CC BY-SA 4.0


问:
Ruby - converting a string into hash with each character as key and index as value?
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

```<code>def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

```<code>map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

答:
Another option you can use is zipping two enumerations together.

```<code>s = "hello"
s.chars.zip(0..s.size)
</code>```

This yields: [["h", 0], ["e", 1], ["l", 2], ["l", 3], ["o", 4]]

Body:
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

Body:
Another option you can use is zipping two enumerations together.

s = "hello"
s.chars.zip(0..s.size)

This yields: [["h", 0], ["e", 1], ["l", 2], ["l", 3], ["o", 4]]


问:
Python : easy way to do geometric mean in python?
I wonder is there any easy way to do geometric mean using python but without using python package. If there is not, is there any simple package to do geometric mean?</p>

答:
just do this:</p>

```<code>numbers = [1, 3, 5, 7, 10]

print reduce(lambda x, y: x*y, numbers)**(1.0/len(numbers))
</code>```

Body:
just do this:

numbers = [1, 3, 5, 7, 10]

print reduce(lambda x, y: x*y, numbers)**(1.0/len(numbers))


问:
How do I fix Error MSB4018 in Visual Studio 2010?

error MSB4018: The "VCMessage" task failed unexpectedly.
  System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
     at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
     at System.String.Format(IFormatProvider provider, String format, Object[] args)
     at Microsoft.Build.Shared.ResourceUtilities.FormatString(String unformatted, Object[] args)
     at Microsoft.Build.Utilities.TaskLoggingHelper.FormatString(String unformatted, Object[] args)
     at Microsoft.Build.Utilities.TaskLoggingHelper.FormatResourceString(String resourceName, Object[] args)
     at Microsoft.Build.Utilities.TaskLoggingHelper.LogWarningWithCodeFromResources(String messageResourceName, Object[] messageArgs)
     at Microsoft.Build.CPPTasks.VCMessage.Execute()
     at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
     at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask, Boolean& taskResult)   C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppBuild.targets    990 6   vtk_minimal

答:
I could not figure out what was wrong. The only thing that fixed this error for me was to remove the configuration and create a new one.
So in Configuration Manager I removed the one that would not build, and I recreated it from a similar one.</p>


问:
Decompress Gzip file and store in variable
I have searched a lot for conversion from byte to string but my query is a little different, please read ahead.

Currently i have a gzip file which i can decompress using the code from http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/.
This code helps me store my decompressed output in a file, but how do i store it in a variable? I am using this code currently:

```<code>public String unGunzipFile(String compressedFile, String decompressedFile) {

        byte[] buffer = new byte[1024];

        try {

            FileInputStream fileIn = new FileInputStream(compressedFile);

            GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);

            FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);
            StringBuffer str = new StringBuffer();
            int bytes_read;
            while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {

                String s = new String(buffer);
                str.append(s);
                fileOutputStream.write(buffer, 0, bytes_read);
            }

            gZIPInputStream.close();
            fileOutputStream.close();

            System.out.println("The file was decompressed successfully!");
            System.out.println(str);
            String final_string = str.toString();
            return final_string;

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }
</code>```

Since i am converting bytes to string near the end when bytes_read is not 1024 in length i end up getting some weird data in my StringBuffer, but in the file there is no such data since fileOutputStream.write(buffer, 0, bytes_read); limits it to writing the updated part.
How do i fix this?

Thanks in advance.

答:
Use the String(byte[] bytes, int offset, int length) constructor that lets you specify the length to be converted. i.e.

```<code>String s = new String(buffer, 0, bytes_read)
</code>```

Body:
I have searched a lot for conversion from byte to string but my query is a little different, please read ahead.

Currently i have a gzip file which i can decompress using the code from http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/.
This code helps me store my decompressed output in a file, but how do i store it in a variable? I am using this code currently:

public String unGunzipFile(String compressedFile, String decompressedFile) {

        byte[] buffer = new byte[1024];

        try {

            FileInputStream fileIn = new FileInputStream(compressedFile);

            GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);

            FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);
            StringBuffer str = new StringBuffer();
            int bytes_read;
            while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {

                String s = new String(buffer);
                str.append(s);
                fileOutputStream.write(buffer, 0, bytes_read);
            }

            gZIPInputStream.close();
            fileOutputStream.close();

            System.out.println("The file was decompressed successfully!");
            System.out.println(str);
            String final_string = str.toString();
            return final_string;

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }

Since i am converting bytes to string near the end when bytes_read is not 1024 in length i end up getting some weird data in my StringBuffer, but in the file there is no such data since fileOutputStream.write(buffer, 0, bytes_read); limits it to writing the updated part.
How do i fix this?

Thanks in advance.

Body:
Use the String(byte[] bytes, int offset, int length) constructor that lets you specify the length to be converted. i.e.

String s = new String(buffer, 0, bytes_read)


问:
Combining ifelse and any to create new column - R 3.3.2 Windows 7
I have a data.table and I'm trying to create a new column by checking to see if a row has particular values in any of a given set of columns.

```<code>head(d1)

   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA
</code>```

What I want to happen is if any of the "drug" columns == "Macrolides" AND any of the same columns == "Cephalosporins" then my new column, "correct" == 1 otherwise "correct" == 0 (or it could be logical), like so:

```<code>head(d1)
   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12 correct
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA   1
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA   0
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA   1
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA   0
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
</code>```

I've tried both of these (but am still learning how to decipher warning messages so those don't help much, especially as I am new to data.table):

```<code>> d1$correct<-ifelse(d1[,c(3:14)]=="Macrolides" | d1[,c(3:14)]=="Cephalosporins", 1, 0)
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  12 column matrix RHS of := will be treated as one vector
2: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 56868 items to be assigned to 4739 items of column 'correct' (52129 unused)
>
>
> selected_cols<-c("drug1", "drug2", "drug3", "drug4", "drug5", "drug6", "drug7", "drug8", "drug9", "drug10", "drug11", "drug12")
> d1$correct<-ifelse(d1 %in% selected_cols=="Macrolides" | d1 %in% selected_cols=="Cephalosporins", 1, 0)
Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 16 items to be assigned to 4739 items of column 'correct' (recycled leaving remainder of 3 items).
</code>```

The closest I've gotten is this:

```<code>d1$correct<-apply(d1, 1, function(r) any(r %in% c("Macrolides", "Cephalosporins")))
</code>```

Which will give TRUE if either of those is true across columns, but I can't figure out how to do it if both of those is true across columns. I'd prefer to not have to use a stunningly massive ifelse statement, since I have 12 columns and more combinations I'll need to make, and the NA's throw it off anyway.

I'd love a dplyr or data.table solution since those are so elegant, but at this point I'm desperate.

答:
Here's an idea:</p>

```<code>library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -MEDREC_KEY, -pat_key) %>%
  group_by(MEDREC_KEY, pat_key) %>%
  mutate(correct = +all(c("Macrolides", "Cephalosporins") %in% value)) %>%
  spread(key, value)
</code>```

Body:
I have a data.table and I'm trying to create a new column by checking to see if a row has particular values in any of a given set of columns.

head(d1)

   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA

What I want to happen is if any of the "drug" columns == "Macrolides" AND any of the same columns == "Cephalosporins" then my new column, "correct" == 1 otherwise "correct" == 0 (or it could be logical), like so:

head(d1)
   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12 correct
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA   1
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA   0
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA   1
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA   0
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA   0

I've tried both of these (but am still learning how to decipher warning messages so those don't help much, especially as I am new to data.table):

> d1$correct<-ifelse(d1[,c(3:14)]=="Macrolides" | d1[,c(3:14)]=="Cephalosporins", 1, 0)
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  12 column matrix RHS of := will be treated as one vector
2: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 56868 items to be assigned to 4739 items of column 'correct' (52129 unused)
>
>
> selected_cols<-c("drug1", "drug2", "drug3", "drug4", "drug5", "drug6", "drug7", "drug8", "drug9", "drug10", "drug11", "drug12")
> d1$correct<-ifelse(d1 %in% selected_cols=="Macrolides" | d1 %in% selected_cols=="Cephalosporins", 1, 0)
Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 16 items to be assigned to 4739 items of column 'correct' (recycled leaving remainder of 3 items).

The closest I've gotten is this:

d1$correct<-apply(d1, 1, function(r) any(r %in% c("Macrolides", "Cephalosporins")))

Which will give TRUE if either of those is true across columns, but I can't figure out how to do it if both of those is true across columns. I'd prefer to not have to use a stunningly massive ifelse statement, since I have 12 columns and more combinations I'll need to make, and the NA's throw it off anyway.

I'd love a dplyr or data.table solution since those are so elegant, but at this point I'm desperate.

Body:
Here's an idea:

library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -MEDREC_KEY, -pat_key) %>%
  group_by(MEDREC_KEY, pat_key) %>%
  mutate(correct = +all(c("Macrolides", "Cephalosporins") %in% value)) %>%
  spread(key, value)


问:
Click other element same as click this element
Sorry for the title may seem confusing.

i have 2 element. with no relation like parent or child.

```<code><div class="alpha"></div>
<div class="beta"></div>
</code>```

The class=alpha have event, if we click it's, there is will be a fade in or fade out element (which is done by jQuery).

now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

more details is like if we click beta the alpha will show it's fadein fadeout effect :)

how we can make it?

many thanks

答:
In jQuery, you can call the .click() function directly or make use of .trigger() and pass it "click". So either:

```<code>$(".beta").click();
</code>```

Or

```<code>$(".beta").trigger("click");
</code>```

Either one of these methods will call your click handler for .beta

If you meant to ask, if I click .alpha, I want to simulate a click on .beta, then this is what you want:

```<code>$("body").delegate(".alpha", "click", function() {
    $(".beta").click();
});
</code>```

Body:
Sorry for the title may seem confusing.

i have 2 element. with no relation like parent or child.

The class=alpha have event, if we click it's, there is will be a fade in or fade out element (which is done by jQuery).

now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

more details is like if we click beta the alpha will show it's fadein fadeout effect :)

how we can make it?

many thanks

Body:
In jQuery, you can call the .click() function directly or make use of .trigger() and pass it "click". So either:

$(".beta").click();

Or

$(".beta").trigger("click");

Either one of these methods will call your click handler for .beta

If you meant to ask, if I click .alpha, I want to simulate a click on .beta, then this is what you want:

$("body").delegate(".alpha", "click", function() {
    $(".beta").click();
});


问:
Implement ResultCallback to MainActivity from GeofenceTransitionsIntentService
I am new to android development and am trying to learn about geofences.  I believe I have my intent service working properly where I am able to register my geofence and in theory receive transitions to the service; however, I am interested in taking the data from the intent service and sending it back to MainActivity.class so that it can be utilized to perform some tasks.  I see lots of examples where a notification is created, but I don't want a notification but instead to simply pass the type of transition and the triggering geofence back to the MainActivity class.

My GeofenceTransitionsIntentService.class is below which is where I assume I will need to implement some way to send a result back to the main class and I am assuming the main class will require some sort of listener to receive these results as they post.

```<code>public class GeofenceTransitionsIntentService extends IntentService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
    private GoogleApiClient myGoogleApiClient;

public GeofenceTransitionsIntentService(){
    super(GeofenceTransitionsIntentService.class.getSimpleName());
}

@Override
public void onCreate(){
    super.onCreate();
    myGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geoFenceEvent = GeofencingEvent.fromIntent(intent);
    if (geoFenceEvent.hasError()){
        int errorcode = geoFenceEvent.getErrorCode();
        Log.e("GeofencingApp", "ERROR: " + errorcode);
    } else {
        int transitionType = geoFenceEvent.getGeofenceTransition();

        if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType){
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();

        } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();
            Toast.makeText(getApplicationContext(), "EXIT: " + triggeredGeofenceID, Toast.LENGTH_LONG).show();
        }
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}
</code>```

答:
I think you can use Intent with putExtra

```<code>startService(new Intent(this,MainActivity.class).putExtra("Key","Data));
</code>```

or CallBack pattern check out this answer

What is callback in Android?

Body:
I am new to android development and am trying to learn about geofences.  I believe I have my intent service working properly where I am able to register my geofence and in theory receive transitions to the service; however, I am interested in taking the data from the intent service and sending it back to MainActivity.class so that it can be utilized to perform some tasks.  I see lots of examples where a notification is created, but I don't want a notification but instead to simply pass the type of transition and the triggering geofence back to the MainActivity class.

My GeofenceTransitionsIntentService.class is below which is where I assume I will need to implement some way to send a result back to the main class and I am assuming the main class will require some sort of listener to receive these results as they post.

public class GeofenceTransitionsIntentService extends IntentService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
    private GoogleApiClient myGoogleApiClient;

public GeofenceTransitionsIntentService(){
    super(GeofenceTransitionsIntentService.class.getSimpleName());
}

@Override
public void onCreate(){
    super.onCreate();
    myGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geoFenceEvent = GeofencingEvent.fromIntent(intent);
    if (geoFenceEvent.hasError()){
        int errorcode = geoFenceEvent.getErrorCode();
        Log.e("GeofencingApp", "ERROR: " + errorcode);
    } else {
        int transitionType = geoFenceEvent.getGeofenceTransition();

        if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType){
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();

        } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
            myGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
            String triggeredGeofenceID = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();
            Toast.makeText(getApplicationContext(), "EXIT: " + triggeredGeofenceID, Toast.LENGTH_LONG).show();
        }
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

Body:
I think you can use Intent with putExtra

startService(new Intent(this,MainActivity.class).putExtra("Key","Data));

or CallBack pattern check out this answer

What is callback in Android?


问:
Flow layout animation glitch when inserting multiple custom supplementary views
When inserting multiple custom supplementary views in a collection view with existing supplementary views, using a subclass of UICollectionViewFlowLayout, the collection view appears to create glitched animations or otherwise not handle the insertions correctly.

Inserting one supplementary view behaves as expected, but inserting two supplementary views at once results in an obvious visual glitch, and inserting many supplementary views at once (e.g. 4+) worsens the glitch. (iOS 10.2, iOS 9.3, Swift 3, Xcode 8.2.1)

Here's a demonstration:

You can reproduce the problem using this sample project. In this simplified example, there is one supplementary view for each item, and two items (with two supplementary views) are inserted during each batch update. In my real project I have fewer supplementary views than items and I utilise other flow layout features.

My best guess is that something is causing the collection view to confuse the index paths or layout attributes corresponding to existing/inserted supplementary views.  If this turns out to be a bug in one of Apple's classes, I would be very grateful for your most elegant workaround.

Attempted solutions

I've tried and double-checked each of the following:

Implementing indexPathsToInsertForSupplementaryView(ofKind:)—so far as I can tell, this is straightforward and my implementation returns the correct index paths. The views are always inserted. For supplementary header and footer views, UICollectionViewFlowLayout seems to return a sorted array of index paths, but sorting the array hasn't made any difference for me.

Providing initial and final layout attributes—calling super for these methods appears to return the correct frames, so it is not obvious what adjustments (if any) could be made to the initial or final layout attributes to solve the problem. But see the third curiosity noted below.

Invalidating the layout—it seems to make no difference at all whether the layout is manually invalidated in whole or in part before, during, or after performBatchUpdates(), or at all.

Custom index paths—although index paths for supplementary elements do not need to correspond to item index paths, so far as I can tell, and despite documentation to the contrary, UICollectionViewFlowLayout will crash (by requesting layout attributes for non-existent index paths) unless supplementary elements of the same kind are numbered sequentially from 0. I assume this is how the collection view and/or the layout object is able to compute new index paths when elements are inserted or deleted (i.e. by incrementing or decrementing the item property of the index path). So constructing arbitrary index paths is not an option.

Curiosities noticed while debugging

The visual glitches are specific to supplementary views and do not occur for inserted items, even when the index paths and frames are the same for both.

Debugging the view hierarchy reveals that, although the frames of the inserted supplementary views are correct, the frames of some existing supplementary views are not correct. That is so despite the fact that the frames returned by the layout object for the existing views at those index paths appear to be correct.

When inserting multiple supplementary views, the calls made by the collection view for initial and final layout attributes appear to be unbalanced. That is, initial layout attributes are requested multiple times for the same index path (and, naturally, the same attributes are returned each time), and there are fewer requests for final layout attributes. Further, for some existing supplementary views, initial and final layout attributes are never requested at all. I find this suspicious. It leads me to believe that the collection view is somehow confusing supplementary views and/or index paths before and after the update.

The memory addresses for instances of IndexPath created by my Swift code are strikingly different to the instances of NSIndexPath created internally by UICollectionView and UICollectionViewFlowLayout. The former are always different (as expected), while the latter appear to be identical between launches (e.g. [0, 0], [0, 1] and [0, 2] are always at 0xc000000000000016, 0xc000000000200016 and 0xc000000000400016). In Swift, IndexPath is bridged to NSIndexPath, but the former is a value type whereas the latter is a reference type. NSIndexPath also uses tagged pointers. There is a remote possibility that the two have been imperfectly bridged and/or that the collection view classes rely internally on NSIndexPath behaviour in some way that gives rise to the index path confusion apparent here. I don't know how to test this or take this further.

Similar questions

The following questions may be related, although none of the answers worked for me:

How can UICollectionView supplementary views be inserted or deleted correctly

layoutAttributesForSupplementaryViewOfKind:atIndexPath: passes in incorrect indexPath

UICollectionView supplementary views won't animate “in” or “out”

UICollectionView Decoration and Supplementary views can not be moved

The problem may also be related to this bug report on Open Radar. The sample project accompanying that report is a bit too complicated to be of much use though.

Apple Technical Support

After posting this question, I submitted a Technical Support Incident to Apple.  Apple Developer Support replied as follows:

Our engineers have reviewed your request and have determined that this would be best handled as a bug report.

Please submit a complete bug report regarding this issue using the Bug Reporting tool at https://developer.apple.com/bug-reporting/.

...

We’ve spent some time investigating the possibility of a workaround and unfortunately have come up empty handed. Please follow up with your bug. If we find the possibility of some kind of workaround in the future, we will reach out. Sorry I don’t have better news.

If you experience this problem, please duplicate rdar://30510010.

答:
I'm not sure if I have a correct solution for the initial issue but I had a same problem like in the answer from @agent_stack.

If you have a custom collection view layout (subclass of UICollectionViewLayout or subclass of UICollectionViewFlowLayout) and you add your own supplementary view then you have to override an additional method: indexPathsToInsertForSupplementaryView(ofKind elementKind: String)

The collection view calls this method whenever you add cells or sections to the collection view. Implementing this method gives your layout object an opportunity to add new supplementary views to complement the additions.

I did my own CollectionViewFlowLayout and only after adding this methods in combination everything is animating as it should!

```<code>    override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
    super.prepare(forCollectionViewUpdates: updateItems)

    // Prepare update by storing index path to insert
    // ────────────────────────────────────────────────────────────

    // IMPORTANT: Item vs. Section Update
    //
    // An instance of UICollectionViewUpdateItem can represent either an item or a section update,
    // and the only way to tell which is that update items which represent section updates contain
    // index paths with a valid section index and NSNotFound for the item index, while update items
    // that represent item updates contain index paths with valid item indexes.
    //
    // This appears to be completely undocumented by Apple, but it is absolutely consistent behavior.

    // https://www.raizlabs.com/blog/2013/10/animating_items_uicollectionview/

    var indexPaths = [IndexPath]()

    for updateItem in updateItems {

        switch updateItem.updateAction {

        case .insert:

            // If it is a section update then convert NSNotFound to zero.
            // In our case a section update always has only the first item.

            if var indexPath = updateItem.indexPathAfterUpdate {
                if indexPath.item == NSNotFound { indexPath.item = 0 }
                indexPaths.append(indexPath)
            }

        default:
            break
        }
    }

    indexPathsToInsert = indexPaths
}

override func indexPathsToInsertForSupplementaryView(ofKind elementKind: String) -> [IndexPath] {

    // Extra add supplementary index paths
    // ────────────────────────────────────────────────────────────

    // The collection view calls this method whenever you add cells or sections to the collection view.
    // Implementing this method gives your layout object an opportunity to add new supplementary views
    // to complement the additions.

    // http://stackoverflow.com/a/38289843/7441991

    switch elementKind {

    case UICollectionElementKindDateSeparator:
        return indexPathsToInsert

    case UICollectionElementKindAvatar:
        return indexPathsToInsert

    default:
        // If it is not a custom supplementary view, return attributes from flow layout
        return super.indexPathsToInsertForSupplementaryView(ofKind: elementKind)
    }
}
</code>```

Feel free to contact me, if you have any questions! :)

Body:
I'm not sure if I have a correct solution for the initial issue but I had a same problem like in the answer from @agent_stack.

If you have a custom collection view layout (subclass of UICollectionViewLayout or subclass of UICollectionViewFlowLayout) and you add your own supplementary view then you have to override an additional method: indexPathsToInsertForSupplementaryView(ofKind elementKind: String)

The collection view calls this method whenever you add cells or sections to the collection view. Implementing this method gives your layout object an opportunity to add new supplementary views to complement the additions.

I did my own CollectionViewFlowLayout and only after adding this methods in combination everything is animating as it should!

    override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
    super.prepare(forCollectionViewUpdates: updateItems)

    // Prepare update by storing index path to insert
    // ────────────────────────────────────────────────────────────

    // IMPORTANT: Item vs. Section Update
    //
    // An instance of UICollectionViewUpdateItem can represent either an item or a section update,
    // and the only way to tell which is that update items which represent section updates contain
    // index paths with a valid section index and NSNotFound for the item index, while update items
    // that represent item updates contain index paths with valid item indexes.
    //
    // This appears to be completely undocumented by Apple, but it is absolutely consistent behavior.

    // https://www.raizlabs.com/blog/2013/10/animating_items_uicollectionview/

    var indexPaths = [IndexPath]()

    for updateItem in updateItems {

        switch updateItem.updateAction {

        case .insert:

            // If it is a section update then convert NSNotFound to zero.
            // In our case a section update always has only the first item.

            if var indexPath = updateItem.indexPathAfterUpdate {
                if indexPath.item == NSNotFound { indexPath.item = 0 }
                indexPaths.append(indexPath)
            }

        default:
            break
        }
    }

    indexPathsToInsert = indexPaths
}

override func indexPathsToInsertForSupplementaryView(ofKind elementKind: String) -> [IndexPath] {

    // Extra add supplementary index paths
    // ────────────────────────────────────────────────────────────

    // The collection view calls this method whenever you add cells or sections to the collection view.
    // Implementing this method gives your layout object an opportunity to add new supplementary views
    // to complement the additions.

    // http://stackoverflow.com/a/38289843/7441991

    switch elementKind {

    case UICollectionElementKindDateSeparator:
        return indexPathsToInsert

    case UICollectionElementKindAvatar:
        return indexPathsToInsert

    default:
        // If it is not a custom supplementary view, return attributes from flow layout
        return super.indexPathsToInsertForSupplementaryView(ofKind: elementKind)
    }
}

Feel free to contact me, if you have any questions! :)


问:
Javascript Float32Array file
I want to read a binary file of float32 with javascript (written by python).
I get the wrong values:

```<code>0,-428443616,-6.332091191811711e-23,-429492128,4.600602988224807e-41,0,0,0,4.618539608568165e-41,1.793662034335766e-43,-428443616,4.17232...
</code>```

instead of right values:

```<code>0.00000000 0.80000001 -0.6000000 0.10000000...
</code>```

code:

```<code>var mRequest = new XMLHttpRequest();
var url="https://storage.googleapis.com/crackling-torch-8396.appspot.com/ac395516-96d0-4533-8e0e-efbc681902ee/studies/-KgPah7nxgHsVB26Nlaf/meshes/-KgPayhUOPYlMx12mn7m/shapes/GEOMFACE1_n.bin";

mRequest.open('GET', url);
mRequest.responseType = 'arraybuffer';

mRequest.onreadystatechange = function () {
    if (mRequest.readyState === 4) {
        // Get bytes
        var buffer = mRequest.response;
        var dataview = new DataView(buffer);
        // Create buffer (4 bytes / float)
        var mFloatArray = new Float32Array(buffer.byteLength / 4);
        // Copy floats
        for (var i = 0; i < mFloatArray.length; i++)
        {
            mFloatArray[i] = dataview.getFloat32(i * 4); // At every 4th byte
        }
        console.log("mFloatArray "+mFloatArray);
        // Do something with mFloatArray
    }
};

mRequest.send();
</code>```

答:
Just tested, it is a matter of little-endian order of the bytes. it works for me, with a little modification, parameter true for little-endian:</p>

```<code>mFloatArray[i] = dataview.getFloat32(i * 4, true); // At every 4th byte
</code>```

Title: Javascript Float32Array file

Body:
I want to read a binary file of float32 with javascript (written by python).
I get the wrong values:

0,-428443616,-6.332091191811711e-23,-429492128,4.600602988224807e-41,0,0,0,4.618539608568165e-41,1.793662034335766e-43,-428443616,4.17232...

instead of right values:

0.00000000 0.80000001 -0.6000000 0.10000000...

code:

var mRequest = new XMLHttpRequest();
var url="https://storage.googleapis.com/crackling-torch-8396.appspot.com/ac395516-96d0-4533-8e0e-efbc681902ee/studies/-KgPah7nxgHsVB26Nlaf/meshes/-KgPayhUOPYlMx12mn7m/shapes/GEOMFACE1_n.bin";

mRequest.open('GET', url);
mRequest.responseType = 'arraybuffer';

mRequest.onreadystatechange = function () {
    if (mRequest.readyState === 4) {
        // Get bytes
        var buffer = mRequest.response;
        var dataview = new DataView(buffer);
        // Create buffer (4 bytes / float)
        var mFloatArray = new Float32Array(buffer.byteLength / 4);
        // Copy floats
        for (var i = 0; i < mFloatArray.length; i++)
        {
            mFloatArray[i] = dataview.getFloat32(i * 4); // At every 4th byte
        }
        console.log("mFloatArray "+mFloatArray);
        // Do something with mFloatArray
    }
};

mRequest.send();

Body:
Just tested, it is a matter of little-endian order of the bytes. it works for me, with a little modification, parameter true for little-endian:

mFloatArray[i] = dataview.getFloat32(i * 4, true); // At every 4th byte


问:
How can I bind a specific nested list value in a ListView
I have a json that I have deserialized.  I have a listview that is bound to the rootobject class.

```<code>public class Thumbnails
{
    public string mini { get; set; }
    public string webimage { get; set; }

}

public class RootObject
{
    public string userCreated { get; set; }
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public List<string> property_product { get; set; }
    public Thumbnails thumbnails { get; set; }
}
</code>```

I have bound my list to a listview

```<code>private void BindListView()
{
    lstView.DataSource = myList;
    lstView.DataBind();
}
</code>```

But I need to display only the webimage value from Thumbnails.  I'm at a loss on how to do that.  It displays the others just fine until I try to add the webimage.

```<code><ItemTemplate>
    <td>
        <%# Eval("webimage") %>
    </td>
    <td>
        <%# Eval("id") %>
    </td>
    <td>
        <%# Eval("name") %>
    </td>
    <td>
        <%# Eval("property_product") %>
    </td>
</ItemTemplate>
</code>```

答:
Just a dot notation should help here:

```<code><%# Eval("thumbnails.webimage") %>
</code>```

Or you could cast the object to Thumbnails and use its property:

```<code><%# ((Thumbnails)Eval("thumbnails")).webimage %>
</code>```

Of course be wary of nulls in both cases.

Body:
I have a json that I have deserialized.  I have a listview that is bound to the rootobject class.

public class Thumbnails
{
    public string mini { get; set; }
    public string webimage { get; set; }

}

public class RootObject
{
    public string userCreated { get; set; }
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public List<string> property_product { get; set; }
    public Thumbnails thumbnails { get; set; }
}

I have bound my list to a listview

private void BindListView()
{
    lstView.DataSource = myList;
    lstView.DataBind();
}

But I need to display only the webimage value from Thumbnails.  I'm at a loss on how to do that.  It displays the others just fine until I try to add the webimage.

<ItemTemplate>

        <%# Eval("webimage") %>

        <%# Eval("id") %>

        <%# Eval("name") %>

        <%# Eval("property_product") %>

</ItemTemplate>

Body:
Just a dot notation should help here:

<%# Eval("thumbnails.webimage") %>

Or you could cast the object to Thumbnails and use its property:

<%# ((Thumbnails)Eval("thumbnails")).webimage %>

Of course be wary of nulls in both cases.


问:
How to calculate elapsed time of a function?
I would like to know how to calculate the time consumed for a function in Delphi.

Then I wanted to show the used time and compare it with another function or component so as to know the faster function.

答:
```<code>VAR iFrequency, iTimerStart, iTimerEnd: Int64;

procedure TimerStart;
begin
  if NOT QueryPerformanceFrequency(iFrequency)
  then MesajWarning('High resolution timer not availalbe!');
  WinApi.Windows.QueryPerformanceCounter(iTimerStart);
end;

function TimerElapsed: Double; { In miliseconds }
begin
  QueryPerformanceCounter(iTimerEnd);
  Result:= 1000 * ((iTimerEnd - iTimerStart) / ifrequency);
end;

function TimerElapsedS: string;       { In seconds/miliseconds }
begin
 if TimerElapsed < 1000
 then Result:= Real2Str(TimerElapsed, 2)+ ' ms'
 else Result:= Real2Str(TimerElapsed / 1000, 2)+ ' s';
end;
</code>```


答:
By looking at their documentation you should be able to set useCurrent to false, which is true by default. Source

```<code>$("#datetimepicker1").datetimepicker({
    format: 'MM/DD/YYYY',
    minDate: new Date(),
    useCurrent: false
});
</code>```

Title: Bootstrap datetimepicker without default initial value

Body:
I am using bootstrap datetimepicker I wanted to remove default selected date.

$("#datetimepicker1").datetimepicker({ format: 'MM/DD/YYYY', minDate:new Date() });

Body:
By looking at their documentation you should be able to set useCurrent to false, which is true by default. Source

$("#datetimepicker1").datetimepicker({
    format: 'MM/DD/YYYY',
    minDate: new Date(),
    useCurrent: false
});


问:
What is the significance of trailing slashes in a namespace URI?
I have been studying SOAP and WSDL in preparation for implementing a web service.  One thing that I have encountered that puzzles me is that some of the URIs that I have seen use a trailing slash such as:

```<code>http://www.w3.org/some-namespace/
</code>```

while other examples that I have studied omit this trailing slash.  I really have several questions regarding this:

What is the significance of the trailing slash?

Is the URI, http://www.w3.org/some-namespace the same as http://www.w3.org/some-namespace/?

If they are not the same, how do I decide when one form is warranted versus another?

I have read the guidelines given by w3c regarding URI's and these appear to indicate that that URI should be considered equal only if the case-sensitive comparison of the URI strings are considered equal.  Is this interpretation correct?

答:
No they aren't the same.

The biggest difference would be in the forming of relative uris from that base; with the slash, the relative uri would be a descendent; without the slash it would be a sibling - i.e. (C# example):

```<code>    Uri uri = new Uri(@"http://www.w3.org/some-namespace/");
    Console.WriteLine(new Uri(uri, "foo")); // http://www.w3.org/some-namespace/foo

    uri = new Uri(@"http://www.w3.org/some-namespace");
    Console.WriteLine(new Uri(uri, "foo")); //http://www.w3.org/foo
</code>```

OwnerDisplayName: Jon Trauntvein

Body:
I have been studying SOAP and WSDL in preparation for implementing a web service.  One thing that I have encountered that puzzles me is that some of the URIs that I have seen use a trailing slash such as:

http://www.w3.org/some-namespace/

while other examples that I have studied omit this trailing slash.  I really have several questions regarding this:

What is the significance of the trailing slash?

Is the URI, http://www.w3.org/some-namespace the same as http://www.w3.org/some-namespace/?

If they are not the same, how do I decide when one form is warranted versus another?

I have read the guidelines given by w3c regarding URI's and these appear to indicate that that URI should be considered equal only if the case-sensitive comparison of the URI strings are considered equal.  Is this interpretation correct?

Body:
No they aren't the same.

The biggest difference would be in the forming of relative uris from that base; with the slash, the relative uri would be a descendent; without the slash it would be a sibling - i.e. (C# example):

    Uri uri = new Uri(@"http://www.w3.org/some-namespace/");
    Console.WriteLine(new Uri(uri, "foo")); // http://www.w3.org/some-namespace/foo

    uri = new Uri(@"http://www.w3.org/some-namespace");
    Console.WriteLine(new Uri(uri, "foo")); //http://www.w3.org/foo

OwnerDisplayName: Marc Gravell


问:
C++ behaviour when const
Here's a basic struct (I hope)

```<code>struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};
</code>```

And source

```<code>SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}
</code>```

The I have a class

```<code>struct SomeClass {
    static const SomeType v;

    SomeClass();
};
</code>```

When I then initialise it

```<code>const SomeType SomeClass::v(0,0,0,0);
</code>```

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

答:
From what code are you seeing those incorrect values?  If it's from something like a constructor of another global variable, remember the static initialization order fiasco; v's constructor might just not have run yet.

Put an output statement in the SomeType constructor and check whether the output occurs before you see the incorrect values.

Title: C++ behaviour when const

Body:
Here's a basic struct (I hope)

struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};

And source

SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}

The I have a class

struct SomeClass {
    static const SomeType v;

    SomeClass();
};

When I then initialise it

const SomeType SomeClass::v(0,0,0,0);

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.


问:
Get Text and store into Excel sheet using Groovy Script in SOAPUI
I need to get value from xml in soapui tool and store those data into Excel sheet. I used groovy script in SoapUI tool.

If Response have multiple output and these output store in excel sheet. Like LocationName and CustCity333Name have twice, so these output should store into excel sheet. Please help me to resolve this issue

```<code><ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080013</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              **<ns10:LocationName>REMOVEDEPENDENCY004</ns10:LocationName>**
             <ns10:RailIncData/>
              **<ns10:CustCity333Name>OAKLAND</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
        </ns10:Location>
        <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080018</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              **<ns10:LocationName>REMOVEDEPENDENCY004</ns10:LocationName>**
              <ns10:RailIncData/>
              **<ns10:CustCity333Name>OAKLAND</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
</code>```

答:
NOTE:

Since you mentioned excel or csv is fine, below script uses csv format.

The data you provided is not well-formed. Modified a bit to make it well-formed.

Also using rowId for identification in the row. You may remove if you do not wish.

Groovy Script

```<code>//Provide / edit file path  for csv  file in the below
def fileName = '/tmp/locationData.csv'

def xml = """<root xmlns:ns10='url1' xmlns:ns5='url2'> <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080013</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              <ns10:LocationName>REMOVEDEPENDENCY004</ns10:LocationName>**
             <ns10:RailIncData/>
              <ns10:CustCity333Name>OAKLAND</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
        </ns10:Location>
        <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080018</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              <ns10:LocationName>REMOVEDEPENDENCY004a</ns10:LocationName>**
              <ns10:RailIncData/>
              <ns10:CustCity333Name>OAKLAND1</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
</ns10:Location>
</root>"""
def parsedXml = new XmlSlurper().parseText(xml)
def data = parsedXml.'**'.findAll{ it.name() == 'Location'}.inject([]){list, loc -> list << new Expando(
     rowId: loc?.LocationId?.RowId?.text(),
     locationName: loc?.LocationDetails?.LocationName?.text(),
     cityName: loc?.LocationDetails?.CustCity333Name?.text()); list }
if (0< data.size()) {
  def sb = new StringBuffer(data[0].properties.keySet().join(',')).append('\n')
  data.collect { sb.append(it.properties.values().join(',')).append('\n')}
  new File(fileName).write(sb.toString())
} else {
  println 'No records found'
}
</code>```

You can check how data is generated quickly online Demo

Body:
I need to get value from xml in soapui tool and store those data into Excel sheet. I used groovy script in SoapUI tool.

If Response have multiple output and these output store in excel sheet. Like LocationName and CustCity333Name have twice, so these output should store into excel sheet. Please help me to resolve this issue

<ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080013</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              **<ns10:LocationName>REMOVEDEPENDENCY004</ns10:LocationName>**
             <ns10:RailIncData/>
              **<ns10:CustCity333Name>OAKLAND</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
        </ns10:Location>
        <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080018</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              **<ns10:LocationName>REMOVEDEPENDENCY004</ns10:LocationName>**
              <ns10:RailIncData/>
              **<ns10:CustCity333Name>OAKLAND</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>

Body:
NOTE:

Since you mentioned excel or csv is fine, below script uses csv format.

The data you provided is not well-formed. Modified a bit to make it well-formed.

Also using rowId for identification in the row. You may remove if you do not wish.

Groovy Script

//Provide / edit file path  for csv  file in the below
def fileName = '/tmp/locationData.csv'

def xml = """<root xmlns:ns10='url1' xmlns:ns5='url2'> <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080013</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              <ns10:LocationName>REMOVEDEPENDENCY004</ns10:LocationName>**
             <ns10:RailIncData/>
              <ns10:CustCity333Name>OAKLAND</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
        </ns10:Location>
        <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080018</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              <ns10:LocationName>REMOVEDEPENDENCY004a</ns10:LocationName>**
              <ns10:RailIncData/>
              <ns10:CustCity333Name>OAKLAND1</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
</ns10:Location>
</root>"""
def parsedXml = new XmlSlurper().parseText(xml)
def data = parsedXml.'**'.findAll{ it.name() == 'Location'}.inject([]){list, loc -> list << new Expando(
     rowId: loc?.LocationId?.RowId?.text(),
     locationName: loc?.LocationDetails?.LocationName?.text(),
     cityName: loc?.LocationDetails?.CustCity333Name?.text()); list }
if (0< data.size()) {
  def sb = new StringBuffer(data[0].properties.keySet().join(',')).append('\n')
  data.collect { sb.append(it.properties.values().join(',')).append('\n')}
  new File(fileName).write(sb.toString())
} else {
  println 'No records found'
}

You can check how data is generated quickly online Demo


问:
connection issues between apacheds and tomcat docker containers
Our java web application running in tomcat container needs connection with apacheds container on port 10389 which has error as depicted in below screenshots. Tomcat container is running on 8080 and apacheds on 10389

This is the apacheds container where we tried connecting to tomcat port 8080 which is expose in running tomcat container which worked fine

This is the tomcat container where we tried connecting to apacheds port 10389 which is expose in running apacheds container

答: There was problem with ldap server ip address in our webapp. After changing that it is working.</p>


问:
Hi , I need to make line graphs in Ionic 2 , what is the best plugin for that?
I need to make line graphs in Ionic 2 , what is the best plugin for that ?
Here is an image of the graph I want to make enter image description here</p>

答:
You can use ng2-highcharts with ionic2 to achieve the same.

npm install --save ng2-highcharts

DEMO


问:
start simple 1-producer 2-consumers through executor service
```<code>public class SemActionPlace {

    public SemMonitor StartConsumerProducer() {
        SemMonitor monitor = new SemMonitor();
        List<Thread> threads = new LinkedList<>();
        Thread p1 = new Thread(new Producer(monitor), "P1");
        p1.start();
        Thread c1 = new Thread(new Consumer(monitor), "C-odd");
        c1.start();
        Thread c2 = new Thread(new Consumer(monitor), "C-even");
        c2.start();
        threads.add(p1);
        threads.add(c1);
        threads.add(c2);
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return monitor;
    }
}
</code>```

the code work just fine when I start thread through start() - join(), however, I failed to find mistake when I try to do the same through the executor service. It's important for me to save names of the threads and mutual monitor. Please, tell me how can I execute the threads through the executor service ?

The piece of code below doen't work properly. Where is mistake ?

```<code>public SemMonitor StartConsumerProducer() {
    SemMonitor monitor = new SemMonitor();
    Thread p1 = new Thread(new Producer(monitor), "P1");
    Thread c1 = new Thread(new Consumer(monitor), "C-odd");
    Thread c2 = new Thread(new Consumer(monitor), "C-even");
    ThreadPoolExecutor service = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
    service.execute(p1);
    service.execute(c1);
    service.execute(c2);
    System.out.println(service.getCompletedTaskCount());
    System.out.println(service.getCompletedTaskCount());
    return monitor;
}
</code>```

I need one simple thing from the executor server is that I wanna that it works like simple start() - join() solution works ( first piece of code ) .

```<code>class Consumer implements Runnable {

    private final SemMonitor monitor;

    Consumer(SemMonitor monitor) {
        this.monitor = monitor;
    }

    @Override
    public void run() {
        long t = System.currentTimeMillis();
        long end = t + 1000;
        while (System.currentTimeMillis() < end) {
            consoleLog(monitor.activeThreadName,false);
            if (/*monitor.semaphore.tryAcquire() && */monitor.activeThreadName.equals( Thread.currentThread().getName())) {

                try {
                    consoleLog(String.valueOf(Thread.currentThread().getName() + " was notified "),monitor.enableLog);
                    monitor.semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                monitor.get(Thread.currentThread().getName());
            }
            try{
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        }

    }
}
</code>```

```<code>class Producer implements Runnable {

    private SemMonitor monitor;

    Producer(SemMonitor monitor) {
        this.monitor = monitor;
    }

    @Override
    public void run() {
        String threadNameToWork;
        Integer randNum;
        long t = System.currentTimeMillis();
        long end = t + 500;
        while (System.currentTimeMillis() < end) {
            if (monitor.semaphore.tryAcquire()) {
                randNum = ((Number) (random() * 100)).intValue();
                if (randNum % 2 == 0) {
                    threadNameToWork = "C-even";
                } else {
                    threadNameToWork = "C-odd";
                }
                try {
                    monitor.putItem(randNum, Thread.currentThread().getName(), threadNameToWork);
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

```<code>class Monitor {

    private double currItem;
    private boolean isConsumersShouldWaitProducer = true;
    private boolean isConsuming = false;
    private String threadNameToWork;

    synchronized void putRandNumber(double producerOutput, String producerName, String threadNameToWork) {
        if (isConsumersShouldWaitProducer) {
            System.out.println("Consumers wait for new Production");
        }
        this.threadNameToWork = threadNameToWork;
        currItem = producerOutput;
        System.out.println("Producer " + producerName + " putRandNumber Item: " + currItem);
        if (currItem > 3) {
            notifyAll();
            isConsumersShouldWaitProducer = false;
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    synchronized void consumeRandNumber(String threadName) {
        if (isConsumersShouldWaitProducer) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                System.out.println("Caught Interrupted Exception while waiting to consume currItem: " + e.getMessage());
            }
        }
        if (isConsuming) {
            try {
                this.wait();
                isConsuming = true;
            } catch (InterruptedException e) {
                System.out.println("Caught Interrupted Exception while waiting to consume currItem: " + e.getMessage());
            }
        }
        switch (Thread.currentThread().getName()) {
        /*switch (threadNameToWork) {*/
            case "C-odd":
                isConsuming = true;
                if (currItem % 2 != 0 && threadNameToWork.equals(Thread.currentThread().getName())) {
                    consumeItems(threadName);
                }
                isConsuming = false;
                notifyAll();
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            case "C-even":
                isConsuming = true;
                if (currItem % 2 == 0 && threadNameToWork.equals(Thread.currentThread().getName())) {
                    consumeItems(threadName);
                }
                isConsuming = false;
                notifyAll();
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    private synchronized void consumeItems(String threadName) {
        isConsumersShouldWaitProducer = true;
        String randNumType = "*odd/even*";
        System.out.println("Consumer:" + threadName + " consumed " + randNumType + " Items = " + currItem);
        notifyAll();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
You want to do something with Thread name right? The thread name you created in using new Thread will not pass into ExecutorService, but this will

```<code>ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                                       .setNameFormat("thread-%d").build()
</code>```

Then

```<code>ExecutorService exec = Executors.newSingleThreadExecutor(namedThreadFactory);
</code>```

Now you have thread with name as thread-1, thread-2

OR set thread name in your run() method

```<code>Thread.currentThread().setName(myName)
</code>```

To make sure your thread is finished, add this before you return the monitor,

```<code>service.shutdown();
while (!service.awaitTermination(10, TimeUnit.SECONDS)) {
   log.info("Awaiting completion of threads.");
}
</code>```

Body:
public class SemActionPlace {

    public SemMonitor StartConsumerProducer() {
        SemMonitor monitor = new SemMonitor();
        List<Thread> threads = new LinkedList<>();
        Thread p1 = new Thread(new Producer(monitor), "P1");
        p1.start();
        Thread c1 = new Thread(new Consumer(monitor), "C-odd");
        c1.start();
        Thread c2 = new Thread(new Consumer(monitor), "C-even");
        c2.start();
        threads.add(p1);
        threads.add(c1);
        threads.add(c2);
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return monitor;
    }
}

the code work just fine when I start thread through start() - join(), however, I failed to find mistake when I try to do the same through the executor service. It's important for me to save names of the threads and mutual monitor. Please, tell me how can I execute the threads through the executor service ?

The piece of code below doen't work properly. Where is mistake ?

public SemMonitor StartConsumerProducer() {
    SemMonitor monitor = new SemMonitor();
    Thread p1 = new Thread(new Producer(monitor), "P1");
    Thread c1 = new Thread(new Consumer(monitor), "C-odd");
    Thread c2 = new Thread(new Consumer(monitor), "C-even");
    ThreadPoolExecutor service = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
    service.execute(p1);
    service.execute(c1);
    service.execute(c2);
    System.out.println(service.getCompletedTaskCount());
    System.out.println(service.getCompletedTaskCount());
    return monitor;
}

I need one simple thing from the executor server is that I wanna that it works like simple start() - join() solution works ( first piece of code ) .

class Consumer implements Runnable {

    private final SemMonitor monitor;

    Consumer(SemMonitor monitor) {
        this.monitor = monitor;
    }

    @Override
    public void run() {
        long t = System.currentTimeMillis();
        long end = t + 1000;
        while (System.currentTimeMillis() < end) {
            consoleLog(monitor.activeThreadName,false);
            if (/*monitor.semaphore.tryAcquire() && */monitor.activeThreadName.equals( Thread.currentThread().getName())) {

                try {
                    consoleLog(String.valueOf(Thread.currentThread().getName() + " was notified "),monitor.enableLog);
                    monitor.semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                monitor.get(Thread.currentThread().getName());
            }
            try{
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        }

    }
}

class Producer implements Runnable {

    private SemMonitor monitor;

    Producer(SemMonitor monitor) {
        this.monitor = monitor;
    }

    @Override
    public void run() {
        String threadNameToWork;
        Integer randNum;
        long t = System.currentTimeMillis();
        long end = t + 500;
        while (System.currentTimeMillis() < end) {
            if (monitor.semaphore.tryAcquire()) {
                randNum = ((Number) (random() * 100)).intValue();
                if (randNum % 2 == 0) {
                    threadNameToWork = "C-even";
                } else {
                    threadNameToWork = "C-odd";
                }
                try {
                    monitor.putItem(randNum, Thread.currentThread().getName(), threadNameToWork);
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Monitor {

    private double currItem;
    private boolean isConsumersShouldWaitProducer = true;
    private boolean isConsuming = false;
    private String threadNameToWork;

    synchronized void putRandNumber(double producerOutput, String producerName, String threadNameToWork) {
        if (isConsumersShouldWaitProducer) {
            System.out.println("Consumers wait for new Production");
        }
        this.threadNameToWork = threadNameToWork;
        currItem = producerOutput;
        System.out.println("Producer " + producerName + " putRandNumber Item: " + currItem);
        if (currItem > 3) {
            notifyAll();
            isConsumersShouldWaitProducer = false;
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    synchronized void consumeRandNumber(String threadName) {
        if (isConsumersShouldWaitProducer) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                System.out.println("Caught Interrupted Exception while waiting to consume currItem: " + e.getMessage());
            }
        }
        if (isConsuming) {
            try {
                this.wait();
                isConsuming = true;
            } catch (InterruptedException e) {
                System.out.println("Caught Interrupted Exception while waiting to consume currItem: " + e.getMessage());
            }
        }
        switch (Thread.currentThread().getName()) {
        /*switch (threadNameToWork) {*/
            case "C-odd":
                isConsuming = true;
                if (currItem % 2 != 0 && threadNameToWork.equals(Thread.currentThread().getName())) {
                    consumeItems(threadName);
                }
                isConsuming = false;
                notifyAll();
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            case "C-even":
                isConsuming = true;
                if (currItem % 2 == 0 && threadNameToWork.equals(Thread.currentThread().getName())) {
                    consumeItems(threadName);
                }
                isConsuming = false;
                notifyAll();
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    private synchronized void consumeItems(String threadName) {
        isConsumersShouldWaitProducer = true;
        String randNumType = "*odd/even*";
        System.out.println("Consumer:" + threadName + " consumed " + randNumType + " Items = " + currItem);
        notifyAll();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Body:
You want to do something with Thread name right? The thread name you created in using new Thread will not pass into ExecutorService, but this will

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                                       .setNameFormat("thread-%d").build()

Then

ExecutorService exec = Executors.newSingleThreadExecutor(namedThreadFactory);

Now you have thread with name as thread-1, thread-2

OR set thread name in your run() method

Thread.currentThread().setName(myName)

To make sure your thread is finished, add this before you return the monitor,

service.shutdown();
while (!service.awaitTermination(10, TimeUnit.SECONDS)) {
   log.info("Awaiting completion of threads.");
}


问:
jQuery selector based on deep children text content
This is an example of HTML I am working with.

```<code><html>
    <div class="parent-div">
        <ul>
            <li class="title">Color</li>
            <li>Red</li>
            <li class="title">Shape</li>
            <li>Squared</li>
        </ul>
    </div>
</html>
</code>```

I would like to convert the current HTML in the following list-item

Color: Red

Shape: Squared

And this is what I tried so far:

$("html > div.parent-div > ul > li:contains('Color')")

However it throws an exception:

Uncaught DOMException: Failed to execute 'querySelectorAll' on
  'Document': html > div.parent-div > ul > li:contains('Color')'
  is not a valid selector.

答:
no need to write html in jQuery selector

```<code>$("div.parent-div > ul > li:contains('Color')")
</code>```

Body:
This is an example of HTML I am working with.

Color

Red

Shape

Squared

I would like to convert the current HTML in the following list-item

Color: Red

Shape: Squared

And this is what I tried so far:

$("html > div.parent-div > ul > li:contains('Color')")

However it throws an exception:

Uncaught DOMException: Failed to execute 'querySelectorAll' on
  'Document': html > div.parent-div > ul > li:contains('Color')'
  is not a valid selector.

Body:
no need to write html in jQuery selector

$("div.parent-div > ul > li:contains('Color')")


问:
ReentrantReadWriteLock - why can't reader acquire writer's lock?
In ReentrantReadWriteLock documentation it is said:

```<code>writer can acquire the read lock, but not vice-versa
</code>```

If I understand correctly it means that from the same thread you can execute:

```<code>//thread1
lock.writeLock().lock()
lock.readLock().lock()
print("this line executes")
</code>```

This makes sense: if you already locked write no other thread can enter the locked code. But if you locked read, why can't you enter the write block in the same thread if no other thread make read lock? So this doesn't work:

```<code>//thread1
lock.readLock().lock()
lock.writeLock().lock()
print("this line doesn't execute")
</code>```

Why do you have to unlock the read before locking write in the same thread?

答:
ReentrantReadWriteLock doesn't mean that the normal rules locking are not followed.

If a thread acquired a lock for reading purpose, it expects the value of the target data not to change for the duration of the lock. Having otherwise would prevent repeatable-reads. Conceptually, if you let a thread (the same or another) acquire a write lock when a read lock is out, you are breaching that rule.

If a thread acquired a lock for writing, it implicitly has reading rights as well, so acquisition of a read-lock can be granted because it doesn't really breach the contract of the lock (if I can write, I can read) nor the expectations of the lock holder (I locked for writing so I am the only one that can read or write now).

Body:
In ReentrantReadWriteLock documentation it is said:

writer can acquire the read lock, but not vice-versa

If I understand correctly it means that from the same thread you can execute:

//thread1
lock.writeLock().lock()
lock.readLock().lock()
print("this line executes")

This makes sense: if you already locked write no other thread can enter the locked code. But if you locked read, why can't you enter the write block in the same thread if no other thread make read lock? So this doesn't work:

//thread1
lock.readLock().lock()
lock.writeLock().lock()
print("this line doesn't execute")

Why do you have to unlock the read before locking write in the same thread?


问:
How can I include a D3 (Scatterplot) Chart inside a SAPUI5 Control
I'm trying to implement a scatter plot chart chart inside an SAPUI5 application. I've done some research with other charting frameworks that are more common with SAP (Vizframe), but they are limiting in its supported features (ex: vizframe doesn't support a regression line).

I cannot find an easy way to integrate a d3 chart into a SAPUI5 control. Can anyone provide some guidance on how this can be accomplished? Examples help!

Here's the chart I'm trying to implement:

https://bl.ocks.org/ctufts/298bfe4b11989960eeeecc9394e9f118

答:
Best way is to implement your own custom control based on D3. Library is already available at the SAPUI5 resources here;

```<code>jQuery.sap.require("sap/ui/thirdparty/d3");
</code>```

Some examples;

http://jsbin.com/zutamig/edit

http://jsbin.com/hacuw/1/edit?html,output

https://blogs.sap.com/2014/07/17/custom-sapui5-visualization-controls-with-d3js/

Chart library based on ChartJS, if you want to check;

https://github.com/SAP/openui5-charting-custom-controls

Developing Custom Controls;

https://www.youtube.com/watch?v=W3Qkev2yk9w
https://www.youtube.com/watch?v=Nw8SnXZFqrs

Building Custom Controls to Visualize Data;

https://www.youtube.com/watch?v=cY-WCWC1qxE

Body:
Best way is to implement your own custom control based on D3. Library is already available at the SAPUI5 resources here;

jQuery.sap.require("sap/ui/thirdparty/d3");

Some examples;

http://jsbin.com/zutamig/edit

http://jsbin.com/hacuw/1/edit?html,output

https://blogs.sap.com/2014/07/17/custom-sapui5-visualization-controls-with-d3js/

Chart library based on ChartJS, if you want to check;

https://github.com/SAP/openui5-charting-custom-controls

Developing Custom Controls;

https://www.youtube.com/watch?v=W3Qkev2yk9w
https://www.youtube.com/watch?v=Nw8SnXZFqrs

Building Custom Controls to Visualize Data;

https://www.youtube.com/watch?v=cY-WCWC1qxE


问:
How display a new image in a div, saved in local storage, each time the user re-visits the page?
Hard to explain in the title, let me explain.

I have 3 images and I would like them to be displayed in a div and rotate everytime a user re-visits the page (They will see one image when they visit, and a different image the next time).

I was thinking of having a variable like 'count' which increments each time the user visits, and the value of count would relate to which image is displayed in this div, however I'm not sure how to save the 3 images in the local storage.

I'm expecting the logic wpould be like

```<code>setItem (Img1)
setItem (Img2)
setItem (Img3)

count = count + 1

if count = 1
    div = getItem(Img1)
if count = 2
 etc etc
</code>```

I guess my question is:

Is there a way to store images in the local storage without first adding them to the page?

EDIT

This is now the code I'm using, however an image is not displayed, the div just displays the image location.

```<code>var counter = localStorage.getItem('counter');
  if(counter == null) {
    localStorage.setItem("counter", 0);
    localStorage.setItem("images",'["assets/advert1.png","assets/advert2.png","assets/advert3.png"]');
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[0]);
  }
  else {
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[counter]);
    counter++;
    if(counter > 2) {
      counter = 0;
    }

    localStorage.setItem("counter", counter);
  }
</code>```

(Note this is inside a document.ready function)

答:
Yes. It is possible.

First, draw the image in a canvas:

https://www.w3schools.com/tags/canvas_drawimage.asp

You can also download it directly from a link. Then save the canvas context into the local storage.

How to save and load HTML5 Canvas to & from localStorage?

Body:
Hard to explain in the title, let me explain.

I have 3 images and I would like them to be displayed in a div and rotate everytime a user re-visits the page (They will see one image when they visit, and a different image the next time).

I was thinking of having a variable like 'count' which increments each time the user visits, and the value of count would relate to which image is displayed in this div, however I'm not sure how to save the 3 images in the local storage.

I'm expecting the logic wpould be like

setItem (Img1)
setItem (Img2)
setItem (Img3)

count = count + 1

if count = 1
    div = getItem(Img1)
if count = 2
 etc etc

I guess my question is:

Is there a way to store images in the local storage without first adding them to the page?

EDIT

This is now the code I'm using, however an image is not displayed, the div just displays the image location.

var counter = localStorage.getItem('counter');
  if(counter == null) {
    localStorage.setItem("counter", 0);
    localStorage.setItem("images",'["assets/advert1.png","assets/advert2.png","assets/advert3.png"]');
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[0]);
  }
  else {
    $('#advert').html(JSON.parse(localStorage.getItem('images'))[counter]);
    counter++;
    if(counter > 2) {
      counter = 0;
    }

    localStorage.setItem("counter", counter);
  }

(Note this is inside a document.ready function)