问:
Updating a SQL Server Table with data that does not exist
I have the below script that served it's time and I need some modifications done. The script runs 2 to 3 times daily to import data from the table.  Some data may be duplicated and what I want is that the modified script will only import and write to the table if the data does not exist.

Someone mentioned that I can try to merge the data or use Where Not Exist.

Unfortunately I'm not sure how I will implement either and hence I've turned to you all for help.  Any help will be greatly appreciated.

```<code>BEGIN TRY
BEGIN TRANSACTION
Declare @Date As DATE

IF OBJECT_ID('Tempdb..#1','U') IS NOT NULL
DROP TABLE #1

SELECT [EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE]
INTO #1
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                 'Excel 12.0;Database=\\VF_RSOSDCNASUDA\xxx\SQL\ESO\ALLAttendance.xlsm;HDR=YES',
                 'SELECT * FROM [ForEmail$]');

SELECT TOP 1 @Date=[DATE] FROM #1

DELETE [dbo].[ALLAttendance$] WHERE CONVERT(char(10),[Date],102)=@Date;

INSERT INTO [dbo].[ALLAttendance$]
SELECT [EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE]
FROM #1
DROP TABLE #1
COMMIT
END TRY
BEGIN CATCH

IF @@TRANCOUNT > 0
    ROLLBACK
END CATCH
</code>```

*****UPDATE*****
I came up with the below and it appears to work but not sure if it's the correct way of doing this

```<code>with CTE
AS
(
SELECT [EMP_ID]
   ,[NAME]
   ,[DEPT]
   ,[DATE]
   ,[Start Time]
   ,[LOGIN]
   ,[LATE/AWOL]
   ,[Team Manager]
   ,[Senior Manager]
   ,[SITE]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                 'Excel 12.0;Database=\\VF_RSOSDCNASUDA\xxx\SQL\ESO\ALLAttendance.xlsm;HDR=YES',
                 'SELECT * FROM [ForEmail$]')
)
merge [dbo].[ALLAttendance$] t
using CTE s
on s.[EMP_ID] = t.[EMP_ID]
and s.[NAME] = t.[NAME]
and s.[DEPT] = t.[DEPT]
and s.[DATE] = t.[DATE]
and s.[Start Time] = t.[Start Time]
and s.[LOGIN] = t.[LOGIN]
and s.[LATE/AWOL] = t.[LATE/AWOL]
and s.[Team Manager] = t.[Team Manager]
and s.[Senior Manager] = t.[Senior Manager]
and s.[SITE] = t.[SITE]
when not matched by target
then insert ([EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE])
values (s.[EMP_ID],s.[NAME],s.[DEPT],s.[DATE],s.[Start Time],s.[LOGIN],s.[LATE/AWOL],s.[Team Manager],s.[Senior Manager],s.[SITE]);
</code>```

答:
My final solution to the issue is below.</p>

```<code>BEGIN TRY
BEGIN TRANSACTION
;with CTE
AS
(
SELECT [EMP_ID]
   ,[NAME]
   ,[DEPT]
   ,[DATE]
   ,[Start Time]
   ,[LOGIN]
   ,[LATE/AWOL]
   ,[Team Manager]
   ,[Senior Manager]
   ,[SITE]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                 'Excel 12.0;Database=\\VF_RSOSDCNASUDA\xxx\National_Command\National Command Centre\SQL\ESO\ALLAttendance.xlsm;HDR=YES',
                 'SELECT * FROM [ForEmail$]')
)
merge ESO.[dbo].[ALLAttendance$] t
using CTE s
on s.[EMP_ID] = t.[EMP_ID]
and s.[NAME] = t.[NAME]
and s.[DEPT] = t.[DEPT]
and s.[DATE] = t.[DATE]
and s.[Start Time] = t.[Start Time]
and s.[LOGIN] = t.[LOGIN]
and s.[LATE/AWOL] = t.[LATE/AWOL]
and s.[Team Manager] = t.[Team Manager]
and s.[Senior Manager] = t.[Senior Manager]
and s.[SITE] = t.[SITE]
when not matched by target
then insert ([EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE])
values (s.[EMP_ID],s.[NAME],s.[DEPT],s.[DATE],s.[Start Time],s.[LOGIN],s.[LATE/AWOL],s.[Team Manager],s.[Senior Manager],s.[SITE]);
COMMIT
END TRY
BEGIN CATCH

IF @@TRANCOUNT > 0
    ROLLBACK
END CATCH
</code>```

Body:
I have the below script that served it's time and I need some modifications done. The script runs 2 to 3 times daily to import data from the table.  Some data may be duplicated and what I want is that the modified script will only import and write to the table if the data does not exist.

Someone mentioned that I can try to merge the data or use Where Not Exist.

Unfortunately I'm not sure how I will implement either and hence I've turned to you all for help.  Any help will be greatly appreciated.

BEGIN TRY
BEGIN TRANSACTION
Declare @Date As DATE

IF OBJECT_ID('Tempdb..#1','U') IS NOT NULL
DROP TABLE #1

SELECT [EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE]
INTO #1
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                 'Excel 12.0;Database=\\VF_RSOSDCNASUDA\xxx\SQL\ESO\ALLAttendance.xlsm;HDR=YES',
                 'SELECT * FROM [ForEmail$]');

SELECT TOP 1 @Date=[DATE] FROM #1

DELETE [dbo].[ALLAttendance$] WHERE CONVERT(char(10),[Date],102)=@Date;

INSERT INTO [dbo].[ALLAttendance$]
SELECT [EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE]
FROM #1
DROP TABLE #1
COMMIT
END TRY
BEGIN CATCH

IF @@TRANCOUNT > 0
    ROLLBACK
END CATCH

*****UPDATE*****
I came up with the below and it appears to work but not sure if it's the correct way of doing this

with CTE
AS
(
SELECT [EMP_ID]
   ,[NAME]
   ,[DEPT]
   ,[DATE]
   ,[Start Time]
   ,[LOGIN]
   ,[LATE/AWOL]
   ,[Team Manager]
   ,[Senior Manager]
   ,[SITE]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                 'Excel 12.0;Database=\\VF_RSOSDCNASUDA\xxx\SQL\ESO\ALLAttendance.xlsm;HDR=YES',
                 'SELECT * FROM [ForEmail$]')
)
merge [dbo].[ALLAttendance$] t
using CTE s
on s.[EMP_ID] = t.[EMP_ID]
and s.[NAME] = t.[NAME]
and s.[DEPT] = t.[DEPT]
and s.[DATE] = t.[DATE]
and s.[Start Time] = t.[Start Time]
and s.[LOGIN] = t.[LOGIN]
and s.[LATE/AWOL] = t.[LATE/AWOL]
and s.[Team Manager] = t.[Team Manager]
and s.[Senior Manager] = t.[Senior Manager]
and s.[SITE] = t.[SITE]
when not matched by target
then insert ([EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE])
values (s.[EMP_ID],s.[NAME],s.[DEPT],s.[DATE],s.[Start Time],s.[LOGIN],s.[LATE/AWOL],s.[Team Manager],s.[Senior Manager],s.[SITE]);

Body:
My final solution to the issue is below.

BEGIN TRY
BEGIN TRANSACTION
;with CTE
AS
(
SELECT [EMP_ID]
   ,[NAME]
   ,[DEPT]
   ,[DATE]
   ,[Start Time]
   ,[LOGIN]
   ,[LATE/AWOL]
   ,[Team Manager]
   ,[Senior Manager]
   ,[SITE]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                 'Excel 12.0;Database=\\VF_RSOSDCNASUDA\xxx\National_Command\National Command Centre\SQL\ESO\ALLAttendance.xlsm;HDR=YES',
                 'SELECT * FROM [ForEmail$]')
)
merge ESO.[dbo].[ALLAttendance$] t
using CTE s
on s.[EMP_ID] = t.[EMP_ID]
and s.[NAME] = t.[NAME]
and s.[DEPT] = t.[DEPT]
and s.[DATE] = t.[DATE]
and s.[Start Time] = t.[Start Time]
and s.[LOGIN] = t.[LOGIN]
and s.[LATE/AWOL] = t.[LATE/AWOL]
and s.[Team Manager] = t.[Team Manager]
and s.[Senior Manager] = t.[Senior Manager]
and s.[SITE] = t.[SITE]
when not matched by target
then insert ([EMP_ID],[NAME],[DEPT],[DATE],[Start Time],[LOGIN],[LATE/AWOL],[Team Manager],[Senior Manager],[SITE])
values (s.[EMP_ID],s.[NAME],s.[DEPT],s.[DATE],s.[Start Time],s.[LOGIN],s.[LATE/AWOL],s.[Team Manager],s.[Senior Manager],s.[SITE]);
COMMIT
END TRY
BEGIN CATCH

IF @@TRANCOUNT > 0
    ROLLBACK
END CATCH


来源: stackexchange

问:
how to assign a function's expression to a variable in smarty
say I've got a text like this:

```<code>{l s='Total'}
</code>```

'l' is a function. The string 'Total' in fact will be a translation: 'l' will output that. I would need to assign the resulting translation to another smarty variable. Is it possible and how to?

答:
You can do it with assign var

```<code>{assign var='translatedString' value={l s='Total'}}
</code>```

And then somewhere else in the template file to output it.

```<code>{$translatedString}
</code>```

Or with capture

```<code>{capture name=translatedString}
    {l s='Total'}
{/capture}
</code>```

And output with

```<code>{$smarty.capture.translatedString}
</code>```

You could also assign capture to a var

```<code>{assign var='capturedVar' value=$smarty.capture.translatedString}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
say I've got a text like this:

{l s='Total'}

'l' is a function. The string 'Total' in fact will be a translation: 'l' will output that. I would need to assign the resulting translation to another smarty variable. Is it possible and how to?

Body:
You can do it with assign var

{assign var='translatedString' value={l s='Total'}}

And then somewhere else in the template file to output it.

{$translatedString}

Or with capture

{capture name=translatedString}
    {l s='Total'}
{/capture}

And output with

{$smarty.capture.translatedString}

You could also assign capture to a var

{assign var='capturedVar' value=$smarty.capture.translatedString}


问:
How to optimise large loops for debug mode
I have implemented a pixel mask class used for checking for perfect collision. I am using SFML so the implementation is fairly straight forward:

Loop through each pixel of the image and decide whether its true or false based on its transparency value. Here is the code I have used:

```<code>// Create an Image from the given texture
    sf::Image image(texture.copyToImage());

    // measure the time this function takes
    sf::Clock clock;
    sf::Time time = sf::Time::Zero;
    clock.restart();

    // Reserve memory for the pixelMask vector to avoid repeating allocation
    pixelMask.reserve(image.getSize().x);

    // Loop through every pixel of the texture
    for (unsigned int i = 0; i < image.getSize().x; i++)
    {
        // Create the mask for one line
        std::vector<bool> tempMask;
        // Reserve memory for the pixelMask vector to avoid repeating allocation
        tempMask.reserve(image.getSize().y);

        for (unsigned int j = 0; j < image.getSize().y; j++)
        {
            // If the pixel is not transparrent
            if (image.getPixel(i, j).a > 0)
                // Some part of the texture is there --> push back true
                tempMask.push_back(true);
            else
                // The user can't see this part of the texture --> push back false
                tempMask.push_back(false);
        }
        pixelMask.push_back(tempMask);
    }

    time = clock.restart();
    std::cout << std::endl << "The creation of the pixel mask took: " << time.asMicroseconds() << " microseconds (" << time.asSeconds() << ")";
</code>```

I have used the an instance of the sf::Clock to meassure time.

My problem is that this function takes ages (e.g. 15 seconds) for larger images(e.g. 1280x720). Interestingly, only in debug mode. When compiling the release version the same texture/image only takes 0.1 seconds or less.

I have tried to reduce memory allocations by using the resize() method but it didn't change much. I know that looping through almost 1 million pixels is slow but it should not be 15 seconds slow should it?

Since I want to test my code in debug mode (for obvious reasons) and I don't want  to wait 5 min till all the pixel masks have been created, what I am looking for is basically a way to:

Either optimise the code / have I missed somthing obvious?

Or get something similar to the release performance in debug mode

Thanks for your help!

答:
Optimizing For Debug

Optimizing for debug builds is generally a very counter-productive idea. It could even have you optimize for debug in a way that not only makes maintaining code more difficult, but may even slow down release builds. Debug builds in general are going to be much slower to run. Even with the flattest kind of C code I write which doesn't pose much for an optimizer to do beyond reasonable register allocation and instruction selection, it's normal for the debug build to take 20 times longer to finish an operation. That's just something to accept rather than change too much.

That said, I can understand the temptation to do so at times. Sometimes you want to debug a certain part of code only for the other operations in the software to takes ages, requiring you to wait a long time before you can even get to the code you are interested in tracing through. I find in those cases that it's helpful, if you can, to separate debug mode input sizes from release mode (ex: having the debug mode only work with an input that is 1/10th of the original size). That does cause discrepancies between release and debug as a negative, but the positives sometimes outweigh the negatives from a productivity standpoint. Another strategy is to build parts of your code in release and just debug the parts you're interested in, like building a plugin in debug against a host application in release.

Approach at Your Own Peril

With that aside, if you really want to make your debug builds run faster and accept all the risks associated, then the main way is to just pose less work for your compiler to optimize away. That's going to be flatter code typically with more plain old data types, less function calls, and so forth.

First and foremost, you might be spending a lot of time on debug mode assertions for safety. See things like checked iterators and how to disable them:
https://msdn.microsoft.com/en-us/library/aa985965.aspx

For your case, you can easily flatten your nested loop into a single loop. There's no need to create these pixel masks with separate containers per scanline, since you can always get at your scanline data with some basic arithmetic (y*image_width or y*image_stride). So initially I'd flatten the loop. That might even help modestly for release mode. I don't know the SFML API so I'll illustrate with pseudocode.

```<code>const int num_pixels = image.w * image.h;
vector<bool> pixelMask(num_pixels);
for (int j=0; j < num_pixels; ++j)
    pixelMask[j] = image.pixelAlpha(j) > 0;
</code>```

Just that already might help a lot. Hopefully SFML lets you access pixels with a single index without having to specify column and row (x and y). If you want to go even further, it might help to grab the pointer to the array of pixels from SFML (also hopefully possible) and use that:

```<code>vector<bool> pixelMask(image.w * image.h);

const unsigned int* pixels = image.getPixels();
for (int j=0; j < num_pixels; ++j)
{
    // Assuming 32-bit pixels (should probably use uint32_t).
    // Note that no right shift is necessary when you just want
    // to check for non-zero values.
    const unsigned int alpha = pixels[j] & 0xff000000;
    pixelMask[j] = alpha > 0;
}
</code>```

Also vector<bool> stores each boolean as a single bit. That saves memory but translates to some more instructions for random-access. Sometimes you can get a speed up even in release by just using more memory. I'd test both release and debug and time carefully, but you can try this:

```<code>vector<char> pixelMask(image.w * image.h);

const unsigned int* pixels = image.getPixels();
char* pixelUsed = &pixelMask[0];
for (int j=0; j < num_pixels; ++j)
{
    const unsigned int alpha = pixels[j] & 0xff000000;
    pixelUsed[j] = alpha > 0;
}
</code>```

Body:
I have implemented a pixel mask class used for checking for perfect collision. I am using SFML so the implementation is fairly straight forward:

Loop through each pixel of the image and decide whether its true or false based on its transparency value. Here is the code I have used:

// Create an Image from the given texture
    sf::Image image(texture.copyToImage());

    // measure the time this function takes
    sf::Clock clock;
    sf::Time time = sf::Time::Zero;
    clock.restart();

    // Reserve memory for the pixelMask vector to avoid repeating allocation
    pixelMask.reserve(image.getSize().x);

    // Loop through every pixel of the texture
    for (unsigned int i = 0; i < image.getSize().x; i++)
    {
        // Create the mask for one line
        std::vector<bool> tempMask;
        // Reserve memory for the pixelMask vector to avoid repeating allocation
        tempMask.reserve(image.getSize().y);

        for (unsigned int j = 0; j < image.getSize().y; j++)
        {
            // If the pixel is not transparrent
            if (image.getPixel(i, j).a > 0)
                // Some part of the texture is there --> push back true
                tempMask.push_back(true);
            else
                // The user can't see this part of the texture --> push back false
                tempMask.push_back(false);
        }
        pixelMask.push_back(tempMask);
    }

    time = clock.restart();
    std::cout << std::endl << "The creation of the pixel mask took: " << time.asMicroseconds() << " microseconds (" << time.asSeconds() << ")";

I have used the an instance of the sf::Clock to meassure time.

My problem is that this function takes ages (e.g. 15 seconds) for larger images(e.g. 1280x720). Interestingly, only in debug mode. When compiling the release version the same texture/image only takes 0.1 seconds or less.

I have tried to reduce memory allocations by using the resize() method but it didn't change much. I know that looping through almost 1 million pixels is slow but it should not be 15 seconds slow should it?

Since I want to test my code in debug mode (for obvious reasons) and I don't want  to wait 5 min till all the pixel masks have been created, what I am looking for is basically a way to:

Either optimise the code / have I missed somthing obvious?

Or get something similar to the release performance in debug mode

Thanks for your help!

Body:
Optimizing For Debug

Optimizing for debug builds is generally a very counter-productive idea. It could even have you optimize for debug in a way that not only makes maintaining code more difficult, but may even slow down release builds. Debug builds in general are going to be much slower to run. Even with the flattest kind of C code I write which doesn't pose much for an optimizer to do beyond reasonable register allocation and instruction selection, it's normal for the debug build to take 20 times longer to finish an operation. That's just something to accept rather than change too much.

That said, I can understand the temptation to do so at times. Sometimes you want to debug a certain part of code only for the other operations in the software to takes ages, requiring you to wait a long time before you can even get to the code you are interested in tracing through. I find in those cases that it's helpful, if you can, to separate debug mode input sizes from release mode (ex: having the debug mode only work with an input that is 1/10th of the original size). That does cause discrepancies between release and debug as a negative, but the positives sometimes outweigh the negatives from a productivity standpoint. Another strategy is to build parts of your code in release and just debug the parts you're interested in, like building a plugin in debug against a host application in release.

Approach at Your Own Peril

With that aside, if you really want to make your debug builds run faster and accept all the risks associated, then the main way is to just pose less work for your compiler to optimize away. That's going to be flatter code typically with more plain old data types, less function calls, and so forth.

First and foremost, you might be spending a lot of time on debug mode assertions for safety. See things like checked iterators and how to disable them:
https://msdn.microsoft.com/en-us/library/aa985965.aspx

For your case, you can easily flatten your nested loop into a single loop. There's no need to create these pixel masks with separate containers per scanline, since you can always get at your scanline data with some basic arithmetic (y*image_width or y*image_stride). So initially I'd flatten the loop. That might even help modestly for release mode. I don't know the SFML API so I'll illustrate with pseudocode.

const int num_pixels = image.w * image.h;
vector<bool> pixelMask(num_pixels);
for (int j=0; j < num_pixels; ++j)
    pixelMask[j] = image.pixelAlpha(j) > 0;

Just that already might help a lot. Hopefully SFML lets you access pixels with a single index without having to specify column and row (x and y). If you want to go even further, it might help to grab the pointer to the array of pixels from SFML (also hopefully possible) and use that:

vector<bool> pixelMask(image.w * image.h);

const unsigned int* pixels = image.getPixels();
for (int j=0; j < num_pixels; ++j)
{
    // Assuming 32-bit pixels (should probably use uint32_t).
    // Note that no right shift is necessary when you just want
    // to check for non-zero values.
    const unsigned int alpha = pixels[j] & 0xff000000;
    pixelMask[j] = alpha > 0;
}

Also vector<bool> stores each boolean as a single bit. That saves memory but translates to some more instructions for random-access. Sometimes you can get a speed up even in release by just using more memory. I'd test both release and debug and time carefully, but you can try this:

vector<char> pixelMask(image.w * image.h);

const unsigned int* pixels = image.getPixels();
char* pixelUsed = &pixelMask[0];
for (int j=0; j < num_pixels; ++j)
{
    const unsigned int alpha = pixels[j] & 0xff000000;
    pixelUsed[j] = alpha > 0;
}


问:
How Do I Convert this specific string to a Datetime in c#?
I'm really confused I've tried a lot to get it to work.

This is the date I'm trying to convert:

6/29/17, 1:15 PM

This is the code:

```<code>DateTime.ParseExact(dateString, "MM/dd/yy, HH:mm tt", System.Globalization.CultureInfo.InvariantCulture);
</code>```

Anyone knows how to approach this?

答:
You need to use M/dd/yy, h:mm tt format instead.

M specifier is for single digit month numbers without leading zero.

h specifier is for single hour digit 12-hour format without leading zero.

```<code>DateTime.ParseExact(dateString, "M/dd/yy, h:mm tt", CultureInfo.InvariantCulture);
</code>```

Body:
I'm really confused I've tried a lot to get it to work.

This is the date I'm trying to convert:

6/29/17, 1:15 PM

This is the code:

DateTime.ParseExact(dateString, "MM/dd/yy, HH:mm tt", System.Globalization.CultureInfo.InvariantCulture);

Anyone knows how to approach this?

Body:
You need to use M/dd/yy, h:mm tt format instead.

M specifier is for single digit month numbers without leading zero.

h specifier is for single hour digit 12-hour format without leading zero.

DateTime.ParseExact(dateString, "M/dd/yy, h:mm tt", CultureInfo.InvariantCulture);


问:
How do you set the height of a Vaadin 8 Grid to be undefined?
I've tried both Grid.setUndefined() and Grid.setHeight("-1px") and neither works. They should both be doing the same but if my grid only has say 3 items then the bottom of the grid is empty and the height is significantly taller than 3 rows.

答: Try setHeightByRows method (Java doc).

Body: Try setHeightByRows method (Java doc).


问:
Debugging Android on Netbeans
I've setup Netbeans using nbandroid (http://kenai.com/projects/nbandroid) which has been working just fine for the last few days. I've already made a small app which runs in the emulator and even on my phone.

The thing I can't get to work is the debugger console in netbeans.
If I add these lines of code to my app nothing appears in any of the output screens in netbeans.

```<code>System.out.println("blaat");
Log.d("info", "blaat")
</code>```

Even though I'm 100% sure the code should run. Any suggestions on what I might have missed?

答:
Ok, just found a better solution in another question:
Android Debugging with Logcat and Emulator. Is it possible?

started using ddms, which is exactly what I wanted.

ContentLicense: CC BY-SA 2.5

Title: Debugging Android on Netbeans

Body:
I've setup Netbeans using nbandroid (http://kenai.com/projects/nbandroid) which has been working just fine for the last few days. I've already made a small app which runs in the emulator and even on my phone.

The thing I can't get to work is the debugger console in netbeans.
If I add these lines of code to my app nothing appears in any of the output screens in netbeans.

System.out.println("blaat");
Log.d("info", "blaat")

Even though I'm 100% sure the code should run. Any suggestions on what I might have missed?


问:
Need to change date format of the xml value
I want to change the date format of the "LAST_MODIFIED_DATE" xml tag value. can any one please help me out.

Actual output:

```<code><MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
  <LAST_MODIFIED_DATE>23-Dec-2017</LAST_MODIFIED_DATE>
</LOCATIONS>
</MESSAGE>
</code>```

Expected output:

```<code><MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
  <LAST_MODIFIED_DATE>12/23/2017</LAST_MODIFIED_DATE>
</LOCATIONS>
</MESSAGE>
</code>```

答:
Through the below type we have the loaded data in xml :

```<code>  CREATE OR REPLACE MESSAGE
    AS
       OBJECT (
              Location_ID         NUMBER,
              Loc_type            VARCHAR2(20),
              Name                VARCHAR2(20),
              phone_num           VARCHAR2(20),
              Last_modified       DATE
              );
    /

declare
 l_sql    VARCHAR2(2000);
 l_test_t MESSAGE:= MESSAGE();
 l_to_xml   xmltype;
begin
 l_test_t.Location_ID := 9999;
 l_test_t.Loc_type := 'S';
 l_test_t.Name := 'Test Location';
 l_test_t.phone_num := '08';
 l_test_t.Last_modified := Sysdate;
 l_to_xml := XMLTYPE(l_test_t);
 DBMS_OUTPUT.put_line(l_to_xml.getstringval);
end;
</code>```

we cant able to change the type structure. so i need any other option to change the date format.

Body:
I want to change the date format of the "LAST_MODIFIED_DATE" xml tag value. can any one please help me out.

Actual output:

<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
  <LAST_MODIFIED_DATE>23-Dec-2017</LAST_MODIFIED_DATE>
</LOCATIONS>
</MESSAGE>

Expected output:

<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
  <LAST_MODIFIED_DATE>12/23/2017</LAST_MODIFIED_DATE>
</LOCATIONS>
</MESSAGE>

Body:
Through the below type we have the loaded data in xml :

  CREATE OR REPLACE MESSAGE
    AS
       OBJECT (
              Location_ID         NUMBER,
              Loc_type            VARCHAR2(20),
              Name                VARCHAR2(20),
              phone_num           VARCHAR2(20),
              Last_modified       DATE
              );
    /

declare
 l_sql    VARCHAR2(2000);
 l_test_t MESSAGE:= MESSAGE();
 l_to_xml   xmltype;
begin
 l_test_t.Location_ID := 9999;
 l_test_t.Loc_type := 'S';
 l_test_t.Name := 'Test Location';
 l_test_t.phone_num := '08';
 l_test_t.Last_modified := Sysdate;
 l_to_xml := XMLTYPE(l_test_t);
 DBMS_OUTPUT.put_line(l_to_xml.getstringval);
end;

we cant able to change the type structure. so i need any other option to change the date format.


问:
Property 'FroalaEditor' does not exist on type 'JQueryStatic' - Angular 4
I am using Angular 4 'FroalaEditor' which uses 'JQuery'.

I have implemented it successfully.
Now I need to add custom buttons in that plugin.

I found following solution

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-froala-editor',
  templateUrl: './froala-editor.component.html',
  styleUrls: ['./froala-editor.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FroalaEditorComponent implements OnInit {
  options;
  constructor() { }

  ngOnInit(){
    $.FroalaEditor.DefineIcon('alert', {NAME: 'info'});
    $.FroalaEditor.RegisterCommand('alert', {
      title: 'Hello',
      focus: false,
      undo: false,
      refreshAfterCallback: false,
      callback: function () {
        alert('Hello!');
      }
    });

    this.options={
      toolbarButtons: ['bold', 'italic', 'underline', 'paragraphFormat','alert', '|', 'insertLink', 'insertImage', 'specialCharacters', 'color', '|', 'align', 'formatOL', 'formatUL', '|', 'undo', 'redo', 'clearFormatting', 'print'],
    }
  }

}
</code>```

But I am having following error.

Property 'FroalaEditor' does not exist on type 'JQueryStatic'.

I found this solution, but I'm not sure how to implement it.

Have anyone faced this issue?

答:
I had the same issue with froala on Aurelia and I solved it by doing like this:</p>

```<code>$['FroalaEditor'].DefineIcon('alert', {NAME: 'info'});
</code>```

Body:
I am using Angular 4 'FroalaEditor' which uses 'JQuery'.

I have implemented it successfully.
Now I need to add custom buttons in that plugin.

I found following solution

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-froala-editor',
  templateUrl: './froala-editor.component.html',
  styleUrls: ['./froala-editor.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FroalaEditorComponent implements OnInit {
  options;
  constructor() { }

  ngOnInit(){
    $.FroalaEditor.DefineIcon('alert', {NAME: 'info'});
    $.FroalaEditor.RegisterCommand('alert', {
      title: 'Hello',
      focus: false,
      undo: false,
      refreshAfterCallback: false,
      callback: function () {
        alert('Hello!');
      }
    });

    this.options={
      toolbarButtons: ['bold', 'italic', 'underline', 'paragraphFormat','alert', '|', 'insertLink', 'insertImage', 'specialCharacters', 'color', '|', 'align', 'formatOL', 'formatUL', '|', 'undo', 'redo', 'clearFormatting', 'print'],
    }
  }

}

But I am having following error.

Property 'FroalaEditor' does not exist on type 'JQueryStatic'.

I found this solution, but I'm not sure how to implement it.

Have anyone faced this issue?

Body:
I had the same issue with froala on Aurelia and I solved it by doing like this:

$['FroalaEditor'].DefineIcon('alert', {NAME: 'info'});


问:
To capture a floating-point overflow excepiton
I have a simple C program that computes (1e200)^2, which  should cause a floating-point overflow exception since the largest double is 1e308 or so.

```<code>double square(double x){
  return x*x;
}

int main(){
  double x = 1e200;
  double y= square(x);
}
</code>```

My questions are:

(1) How can you capture the exception via a command line, in such a way that when running the program, the exception can be printed out to the terminal?

(2) How can you capture the exception through injecting additional statements that print out the floating-point exception signal during program execution? For the sake of generality, I would prefer  not to use y==inf to achieve this goal.

Thanks.

答:
I think you are looking for something like this... although this is type char, you could so something similar I believe... and then you can enter whatever printf statement you want within the errno==ERANGE elseif condition.</p>

```<code>int check_for_non_number(char *input)
{
    errno = 0;
    char *endptr;
    double xnum = strtod(input, &endptr);
    // IF endptr FOUND A NON-VALID ENTRY AND THAT ENTRY IS NOT THE NEW LINE CHARACTER THEN ITS AN ERROR
    if((*endptr) && (*endptr != '\n'))
    {
        return 1;
    }
    else if (errno == ERANGE)
    {
        printf("OPERAND IS OUT OF RANGE");
        return 1;
    }
    // ELSE IF endptr FOUND A NON-VALID ENTRY AND THAT ENTRY IS THE NEW LINE CHARACTER THEN RETURN 2 TO CHECK IF IT SHOULD BE A NEW LINE
    else if((*endptr) && (*endptr == '\n'))
    {
        return 2;
    }
    else
    {
        return 0;
    }
}
</code>```

Body:
I have a simple C program that computes (1e200)^2, which  should cause a floating-point overflow exception since the largest double is 1e308 or so.

double square(double x){
  return x*x;
}

int main(){
  double x = 1e200;
  double y= square(x);
}

My questions are:

(1) How can you capture the exception via a command line, in such a way that when running the program, the exception can be printed out to the terminal?

(2) How can you capture the exception through injecting additional statements that print out the floating-point exception signal during program execution? For the sake of generality, I would prefer  not to use y==inf to achieve this goal.

Thanks.

Body:
I think you are looking for something like this... although this is type char, you could so something similar I believe... and then you can enter whatever printf statement you want within the errno==ERANGE elseif condition.

int check_for_non_number(char *input)
{
    errno = 0;
    char *endptr;
    double xnum = strtod(input, &endptr);
    // IF endptr FOUND A NON-VALID ENTRY AND THAT ENTRY IS NOT THE NEW LINE CHARACTER THEN ITS AN ERROR
    if((*endptr) && (*endptr != '\n'))
    {
        return 1;
    }
    else if (errno == ERANGE)
    {
        printf("OPERAND IS OUT OF RANGE");
        return 1;
    }
    // ELSE IF endptr FOUND A NON-VALID ENTRY AND THAT ENTRY IS THE NEW LINE CHARACTER THEN RETURN 2 TO CHECK IF IT SHOULD BE A NEW LINE
    else if((*endptr) && (*endptr == '\n'))
    {
        return 2;
    }
    else
    {
        return 0;
    }
}


问:
Excel VBA Bolding red text in a string
I'm working on an Excel macro that will loop through cells and bold all text within each that is already formatted as red. Each cell contains a string with automatic black text except for keywords which are highlighted as red. I just want those red keywords to also be bolded.

The way I have it set up now, it iterates through each character individually, which although not the fastest, is fine for my purposes, since it will only be run on a few cells at a time.
I initially had it coded as this:

```<code>Sub redTxtBold2()
Dim i As Integer

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                currentCell.Characters(i, 1).Font.Bold = True
            End If
        Next i
    End If
Next currentCell
End Sub
</code>```

The problem I ran into here was that, although it worked fine for most cells, in cases where the first character in a cell was red, it would bold that character and remove the red text formatting in the rest of the cell. Figuring out why it does this and preventing it would be the best solution, but I came up with a workaround:

```<code>Sub redTxtBold1()
Dim i, tstart As Integer
Dim redTxt As String
Dim BoldText As String

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                redTxt = redTxt & currentCell.Characters(i, 1).Text
                Debug.Print redTxt
            End If
        Next i
    End If
    tstart = InStr(currentCell.Text, redTxt)
    Debug.Print tstart
    currentCell.Characters(tstart, Len(redTxt)).Font.Bold = True
    redTxt = ""
Next currentCell
End Sub
</code>```

The problem now with this one is that if the string contains multiple red keywords spaced throughout, redTxt collects and merges them together, causing InStr to not find the substring. The macro thus bolds the first few characters for Len(redTxt) regardless of which are red or not.

I've only been experimenting with VBA for a couple months now, so my skills are still fairly limited. How can I code this better so it bolds all red, and only red characters?

答:
I can't explain the reason.  But here is a workaround that seems to work for the cases you cite.

Pass through once and collect the character pos of all the cells that are red.

Then pass through the second time and make all those characters both red and bold

```<code>Option Explicit
Sub redTxtBold2()
Dim i As Integer
Dim currentCell As Range
Dim SearchString As String
Dim Col As Collection, V As Variant

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        Set Col = New Collection
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then _
                    Col.Add i
        Next i
        With currentCell
            For Each V In Col
                .Characters(V, 1).Font.Bold = True
                .Characters(V, 1).Font.ColorIndex = 3
            Next V
        End With
    End If
Next currentCell
End Sub
</code>```

Title: Excel VBA Bolding red text in a string

Body:
I'm working on an Excel macro that will loop through cells and bold all text within each that is already formatted as red. Each cell contains a string with automatic black text except for keywords which are highlighted as red. I just want those red keywords to also be bolded.

The way I have it set up now, it iterates through each character individually, which although not the fastest, is fine for my purposes, since it will only be run on a few cells at a time.
I initially had it coded as this:

Sub redTxtBold2()
Dim i As Integer

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                currentCell.Characters(i, 1).Font.Bold = True
            End If
        Next i
    End If
Next currentCell
End Sub

The problem I ran into here was that, although it worked fine for most cells, in cases where the first character in a cell was red, it would bold that character and remove the red text formatting in the rest of the cell. Figuring out why it does this and preventing it would be the best solution, but I came up with a workaround:

Sub redTxtBold1()
Dim i, tstart As Integer
Dim redTxt As String
Dim BoldText As String

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                redTxt = redTxt & currentCell.Characters(i, 1).Text
                Debug.Print redTxt
            End If
        Next i
    End If
    tstart = InStr(currentCell.Text, redTxt)
    Debug.Print tstart
    currentCell.Characters(tstart, Len(redTxt)).Font.Bold = True
    redTxt = ""
Next currentCell
End Sub

The problem now with this one is that if the string contains multiple red keywords spaced throughout, redTxt collects and merges them together, causing InStr to not find the substring. The macro thus bolds the first few characters for Len(redTxt) regardless of which are red or not.

I've only been experimenting with VBA for a couple months now, so my skills are still fairly limited. How can I code this better so it bolds all red, and only red characters?

Body:
I can't explain the reason.  But here is a workaround that seems to work for the cases you cite.

Pass through once and collect the character pos of all the cells that are red.

Then pass through the second time and make all those characters both red and bold

Option Explicit
Sub redTxtBold2()
Dim i As Integer
Dim currentCell As Range
Dim SearchString As String
Dim Col As Collection, V As Variant

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        Set Col = New Collection
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then _
                    Col.Add i
        Next i
        With currentCell
            For Each V In Col
                .Characters(V, 1).Font.Bold = True
                .Characters(V, 1).Font.ColorIndex = 3
            Next V
        End With
    End If
Next currentCell
End Sub


问:
Windows 7 Gadget Flyout Question
I'm having troubles with my flyout.  What happens with my gadget is you double click a component and it will have a corresponding flyout window.  If you double click that or any other visual component with a flyout, though, the flyout document is returned as null.  I have no idea why this is, and if you make the flyout go away and reopen it or a new one it's ok.  It's only when a flyout is already opened this happens.  I'm looking for some ideas on why this is.

Double click code:

```<code>Blah.prototype.ondblclick = function()
{

    var me = this.parent;

    if (System.Gadget.Flyout.show)
    {
        // flyout is already shown, make sure it shows our stuff
        System.Gadget.Flyout.file = FLYOUT_FILE;
        onFlyoutShow();
    }
    else
    {
        System.Gadget.Flyout.file = FLYOUT_FILE;
        System.Gadget.Flyout.onShow = onFlyoutShow;
        System.Gadget.Flyout.show = true;
    }
    System.Gadget.Flyout.onHide = onFlyoutHide;

    function onFlyoutShow()
    {
        me.flyoutOpen = true;
        me.updateFlyout();
    }

    function onFlyoutHide()
    {
        me.flyoutOpen = false;
    }
};
</code>```

Executed code:

```<code>Blah.prototype.updateFlyout = function ()
{
    var flyoutDoc = System.Gadget.Flyout.document;
    //flyoutDoc is null at this point
    var info = flyoutDoc.getElementById("info");
    info.innerHTML = "info: " + this.information;
    //Error thrown: 'null' is null or not an object
}
</code>```

答:
I don't know a lot about writing gadgets for windows 7, but to me it looks a lot like a timing issue. When the flyout is already there, you change the file property which tells it to load a new file. Without waiting you then call onFlyoutShow which tries to get the document and the document isn't loaded yet.

My first thought is: Doesn't the onShow event fire when you set the file? Probably doesn't or you wouldn't have the if, but worth verifying.

If that doesn't work, calling onFlyoutShow in a timeout. Start with a long timer, like 1000. And then shorten it, hopefully you can get down to 0: setTimeout(onFlyoutShow, 0);

Title: Windows 7 Gadget Flyout Question

Body:
I'm having troubles with my flyout.  What happens with my gadget is you double click a component and it will have a corresponding flyout window.  If you double click that or any other visual component with a flyout, though, the flyout document is returned as null.  I have no idea why this is, and if you make the flyout go away and reopen it or a new one it's ok.  It's only when a flyout is already opened this happens.  I'm looking for some ideas on why this is.

Double click code:

Blah.prototype.ondblclick = function()
{

    var me = this.parent;

    if (System.Gadget.Flyout.show)
    {
        // flyout is already shown, make sure it shows our stuff
        System.Gadget.Flyout.file = FLYOUT_FILE;
        onFlyoutShow();
    }
    else
    {
        System.Gadget.Flyout.file = FLYOUT_FILE;
        System.Gadget.Flyout.onShow = onFlyoutShow;
        System.Gadget.Flyout.show = true;
    }
    System.Gadget.Flyout.onHide = onFlyoutHide;

    function onFlyoutShow()
    {
        me.flyoutOpen = true;
        me.updateFlyout();
    }

    function onFlyoutHide()
    {
        me.flyoutOpen = false;
    }
};

Executed code:

Blah.prototype.updateFlyout = function ()
{
    var flyoutDoc = System.Gadget.Flyout.document;
    //flyoutDoc is null at this point
    var info = flyoutDoc.getElementById("info");
    info.innerHTML = "info: " + this.information;
    //Error thrown: 'null' is null or not an object
}


问:
How to get device make and model on iOS?
I was wondering if it's possible to determine what kind of iPhone (for example) the currentdevice is? I know it's possible to get the model through

    NSString *deviceType = [[UIDevice currentDevice] model];

which will just return whether I have an "iPhone" or an "iPod", BUT I was wondering if it's possible to detect/know if I have an iPhone 3GS vs. and iPhone 4 vs. an iPhone 4S (in actuality, all I really want to do is determine if I have a 3G or not, because I'm doing fairly graphics intensive stuff).

So yeah, let me know, thank you!

答:
This solution works for both physical devices and iOS simulator in a way that simulator returns the same model as physical device would return for a model e.g. "iPhone10,6" for iPhone X (GSM) rather than "x86_64".

Definition - Swift 4:

```<code>import UIKit

extension UIDevice {
    var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        if let value = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
            return value
        } else {
            return identifier
        }
    }
}
</code>```

Usage:

```<code>print(UIDevice.current.modelName)
</code>```

Body:
This solution works for both physical devices and iOS simulator in a way that simulator returns the same model as physical device would return for a model e.g. "iPhone10,6" for iPhone X (GSM) rather than "x86_64".

Definition - Swift 4:

import UIKit

extension UIDevice {
    var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        if let value = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
            return value
        } else {
            return identifier
        }
    }
}

Usage:

print(UIDevice.current.modelName)

ContentLicense: CC BY-SA 4.0


问:
Realm search in async function and use the result in main thread
I need to perform a search to one of my Realm table based on a keyword. The search function is done in an async function but it is quite slow: 3-5 seconds to search and show the results for 9000 data.

The search is done in three steps:

Search based on the query and return the list of Guid

Return the list of objects based on list of Guid

Use the result value to update the UI

When I try to return List<IssueTable> directly from SearchIssueInProject, I can't access its property later because "this realm instance has been closed" (something like that).

This is my search functions:

```<code>public async Task<List<IssueTable>> GetFilteredIssuesInProject(string query)
{
     if (!string.IsNullOrEmpty(query))
     {
          var searchResults = await Task.Run(() => SearchIssueInProject(query));
          return searchResults.Select(i => RealmConnection.Find<IssueTable>(i)).ToList();
     }

     return this.AllIssuesInProject;
}

List<string> SearchIssueInProject(string query)
{
     using (var realm = Realm.GetInstance(RealmConfiguration))
     {
          Func<IssueTable, bool> searchIssue = d =>
                            string.IsNullOrEmpty(query) ? true :
                            Contains(d.Id.ToString(), query) ||
                            Contains(d.Status.DisplayName, query) ||
                            Contains(d.Status.Value, query) ||
                            Contains(d.Team.Name, query) ||
                            Contains(d.Team.Initial, query) ||
                            Contains(d.StandardIssueCategory.Title, query) ||
                            Contains(d.StandardIssueType.Title, query) ||
                            Contains(d.Drawing.Title, query) ||
                            Contains(d.Location.Title, query) ||
                            Contains(d.CreatedBy.DisplayName, query) ||
                            Contains(d.UpdatedBy.DisplayName, query);

          var result = realm.All<IssueTable>().Where(searchIssue)
                                  .OrderByDescending(i => i.UpdatedDate)
                                  .Select(i => i.Guid)
                                  .ToList();

          return result;
     }
}

        public List<IssueTable> GetAllIssues()
        {
            return RealmConnection.All<IssueTable>()
                            .OrderByDescending(i => i.UpdatedDate)
                            .ToList();
        }
</code>```

Contains function:

```<code>public static bool Contains(string source, string filter)
{
     return source.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0;
}
</code>```

And this is how I use the search function:

```<code>this.WhenAnyValue(x => x.ViewModel.IssueSearchQuery)
    .Throttle(TimeSpan.FromMilliseconds(1000), RxApp.MainThreadScheduler)
    .DistinctUntilChanged()
    .Do(_ =>
     {
         this.IssueAdapter.Issues.Clear();
     })
    .Select(searchTerm =>
     {
         if (SearchingProgressDialog == null && Activity != null)
         {
              ShowLoadingProgress();
         }
         var result = this.ViewModel.GetFilteredIssuesInProject(searchTerm);
          return result
                       .ToObservable()
                       .ObserveOn(RxApp.MainThreadScheduler);
      })
     .Switch()
     .Subscribe(searchResult =>
      {
          this.IssueAdapter.Issues.AddRange(searchResult);
          this.IssueAdapter.NotifyDataSetChanged();
          if (SearchingProgressDialog != null)
          {
               SearchingProgressDialog.Dismiss();
               SearchingProgressDialog = null;
          }
      });
</code>```

How to improve the search function?

答:
Because you're creating a function and not an expression, the query isn't evaluated by Realm, but rather by LINQ to objects which means every object needs to be fetched by Realm, then the accessed properties will be fetched one by one to be used by the comparison. Unfortunately, all the fields you search by need traversing a related object which is not yet supported by Realm .NET.

One approach to resolve this would be to denormalize your data and copy these properties on the IssueTable object. Then you can execute a query like:

```<code>var result = realm.All<IssueTable>()
                  // Note that the .Where overload we select uses Expression<Func<>>
                  // Also, StatusDisplayName is a copy of Status.DisplayName
                  .Where(i => i.StatusDisplayName || ...)
                  .OrderByDescending(i => i.UpdatedDate)
                  .ToArray()
                  .Select(i => i.Guid)
                  .ToList();
</code>```

Body:
I need to perform a search to one of my Realm table based on a keyword. The search function is done in an async function but it is quite slow: 3-5 seconds to search and show the results for 9000 data.

The search is done in three steps:

Search based on the query and return the list of Guid

Return the list of objects based on list of Guid

Use the result value to update the UI

When I try to return List<IssueTable> directly from SearchIssueInProject, I can't access its property later because "this realm instance has been closed" (something like that).

This is my search functions:

public async Task<List<IssueTable>> GetFilteredIssuesInProject(string query)
{
     if (!string.IsNullOrEmpty(query))
     {
          var searchResults = await Task.Run(() => SearchIssueInProject(query));
          return searchResults.Select(i => RealmConnection.Find<IssueTable>(i)).ToList();
     }

     return this.AllIssuesInProject;
}

List<string> SearchIssueInProject(string query)
{
     using (var realm = Realm.GetInstance(RealmConfiguration))
     {
          Func<IssueTable, bool> searchIssue = d =>
                            string.IsNullOrEmpty(query) ? true :
                            Contains(d.Id.ToString(), query) ||
                            Contains(d.Status.DisplayName, query) ||
                            Contains(d.Status.Value, query) ||
                            Contains(d.Team.Name, query) ||
                            Contains(d.Team.Initial, query) ||
                            Contains(d.StandardIssueCategory.Title, query) ||
                            Contains(d.StandardIssueType.Title, query) ||
                            Contains(d.Drawing.Title, query) ||
                            Contains(d.Location.Title, query) ||
                            Contains(d.CreatedBy.DisplayName, query) ||
                            Contains(d.UpdatedBy.DisplayName, query);

          var result = realm.All<IssueTable>().Where(searchIssue)
                                  .OrderByDescending(i => i.UpdatedDate)
                                  .Select(i => i.Guid)
                                  .ToList();

          return result;
     }
}

        public List<IssueTable> GetAllIssues()
        {
            return RealmConnection.All<IssueTable>()
                            .OrderByDescending(i => i.UpdatedDate)
                            .ToList();
        }

Contains function:

public static bool Contains(string source, string filter)
{
     return source.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0;
}

And this is how I use the search function:

this.WhenAnyValue(x => x.ViewModel.IssueSearchQuery)
    .Throttle(TimeSpan.FromMilliseconds(1000), RxApp.MainThreadScheduler)
    .DistinctUntilChanged()
    .Do(_ =>
     {
         this.IssueAdapter.Issues.Clear();
     })
    .Select(searchTerm =>
     {
         if (SearchingProgressDialog == null && Activity != null)
         {
              ShowLoadingProgress();
         }
         var result = this.ViewModel.GetFilteredIssuesInProject(searchTerm);
          return result
                       .ToObservable()
                       .ObserveOn(RxApp.MainThreadScheduler);
      })
     .Switch()
     .Subscribe(searchResult =>
      {
          this.IssueAdapter.Issues.AddRange(searchResult);
          this.IssueAdapter.NotifyDataSetChanged();
          if (SearchingProgressDialog != null)
          {
               SearchingProgressDialog.Dismiss();
               SearchingProgressDialog = null;
          }
      });

How to improve the search function?

Body:
Because you're creating a function and not an expression, the query isn't evaluated by Realm, but rather by LINQ to objects which means every object needs to be fetched by Realm, then the accessed properties will be fetched one by one to be used by the comparison. Unfortunately, all the fields you search by need traversing a related object which is not yet supported by Realm .NET.

One approach to resolve this would be to denormalize your data and copy these properties on the IssueTable object. Then you can execute a query like:

var result = realm.All<IssueTable>()
                  // Note that the .Where overload we select uses Expression<Func<>>
                  // Also, StatusDisplayName is a copy of Status.DisplayName
                  .Where(i => i.StatusDisplayName || ...)
                  .OrderByDescending(i => i.UpdatedDate)
                  .ToArray()
                  .Select(i => i.Guid)
                  .ToList();


问:
How I can add '0' for number with PHP command?
If the number is smaller than 10-digit number then it should to add automatically '0', so that the number get to fill to 10-digit number. Example:
$number = "123456";
Then add '0' -> it should to show: 0000123456

If example 7-digit number then so: 0001234567

How I code it? Thank you for helping.

答:
str_pad($input, 10, "0", STR_PAD_LEFT);

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

You can also use sprintf to return a formatted string.


问:
Why many people use left shift << instead of multiplication

In many codes, people are using left shift to accomplish the multiplication. For example, 3 * i, some people prefer to use i << 1 + i, is there any benefit over the common one by using left shift.

答:
One reason that jumps to my mind is to make the point that bitwise operations are being performed;  The code can become a lot cleaner and intentions clearer with this style of notation than using hex (matter of opinion).

For example - to make the point that the 3rd bit is being set an engineer might do

```<code>uint32 foo = 1 << 3;
</code>```

Note that in this case, the compiler will optimize this away completely and replace with an assign of 0x08; but the intent of 3rd bit being set is very clear.

This has a lot of use in embedded programming, encryption and other bit specific twiddling that don't jump to my mind.

It is not for performance optimizations, since the compiler can be expected to optimize a multiply by 2 to a shift it's not any faster; and in any case you'd be unlikely to notice the gains in most applications.

Your example however,  3*i being replaced by i << 1+i is poor since they are not the same operation.

Body:
One reason that jumps to my mind is to make the point that bitwise operations are being performed;  The code can become a lot cleaner and intentions clearer with this style of notation than using hex (matter of opinion).

For example - to make the point that the 3rd bit is being set an engineer might do

uint32 foo = 1 << 3;

Note that in this case, the compiler will optimize this away completely and replace with an assign of 0x08; but the intent of 3rd bit being set is very clear.

This has a lot of use in embedded programming, encryption and other bit specific twiddling that don't jump to my mind.

It is not for performance optimizations, since the compiler can be expected to optimize a multiply by 2 to a shift it's not any faster; and in any case you'd be unlikely to notice the gains in most applications.

Your example however,  3*i being replaced by i << 1+i is poor since they are not the same operation.


问:
Highcharts annotations not rendering
I'm trying to dynamically add annotations to my high charts in React. I'm using the addAnnotation function to add a new annotation whenever a hover event is triggered on my app, but the annotation does not render. I dropped a debugger into my code, and when I call chart.annotations I can see there is currently an array of annotations, but they are not rendering. I even have make a call to the addPlotLine in this function and the plotline is rendered on the chart.  My config file looks like this

```<code>chart: {
      annotations: [{
        labelOptions: {
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          verticalAlign: 'top',
          align: 'right',
        }
      }],
      annotationsOptions: {
      },
    .... some lots more config options
}
</code>```

and my on hover function to add the annotation is as follows

```<code>if( isNumber(value) )
   //this renders a plotline
    chart.xAxis[0].addPlotLine(baseChartHandle.generateInteractivePlotLine(value));
    // this doesn't render my annotation however
    chart.addAnnotation({
      linkedTo: value,
      title: {
        text: "It works!"
      }
    });
}
</code>```

答:
I found that when I added annotations using Highcharts that the "linkedTo" function never worked despite my trials.

Despite adding a guid to my point, it never was able to apply it. I would suggest in your case adding it by x and y value, then finding the point that way instead. Here is how I have added annotations in the past successfully:

```<code> series.data.forEach(function (point) {

                var annotationObject =
                    {
                        id: point.id,
                        labelOptions: {
                            y: 15,
                            verticalAlign: 'bottom',
                            distance: 25
                        },
                        labels: []
                    };

                }

                var text = <get text you want to push>;

                annotationObject.labels.push(
                    {
                        point: {
                            xAxis: 0,
                            yAxis: 0,
                            x: point.x,
                            y: point.y
                        },
                        text: text
                    }

                );

                _chart.addAnnotation(annotationObject);
            });
</code>```

I also found a bug in HighCharts when using remove annotations, as a heads up. Each point will need an id like above, but it should be called by this line:

```<code>           _chart.removeAnnotation(id);
</code>```

It will remove the annotation, however you will get lots of complaints from highcharts if you try to do anything after, and it will break. I found the answer here, in annotations.js :

The red box is code I added. If you do removeAnnotation(ann.id), and it rerenders, it will fail because the labels object is null. Adding this check lets you do that without the labelCollectors failing.

Happy charting.

Title: Highcharts annotations not rendering

Body:
I'm trying to dynamically add annotations to my high charts in React. I'm using the addAnnotation function to add a new annotation whenever a hover event is triggered on my app, but the annotation does not render. I dropped a debugger into my code, and when I call chart.annotations I can see there is currently an array of annotations, but they are not rendering. I even have make a call to the addPlotLine in this function and the plotline is rendered on the chart.  My config file looks like this

chart: {
      annotations: [{
        labelOptions: {
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          verticalAlign: 'top',
          align: 'right',
        }
      }],
      annotationsOptions: {
      },
    .... some lots more config options
}

and my on hover function to add the annotation is as follows

if( isNumber(value) )
   //this renders a plotline
    chart.xAxis[0].addPlotLine(baseChartHandle.generateInteractivePlotLine(value));
    // this doesn't render my annotation however
    chart.addAnnotation({
      linkedTo: value,
      title: {
        text: "It works!"
      }
    });
}

Body:
I found that when I added annotations using Highcharts that the "linkedTo" function never worked despite my trials.

Despite adding a guid to my point, it never was able to apply it. I would suggest in your case adding it by x and y value, then finding the point that way instead. Here is how I have added annotations in the past successfully:

 series.data.forEach(function (point) {

                var annotationObject =
                    {
                        id: point.id,
                        labelOptions: {
                            y: 15,
                            verticalAlign: 'bottom',
                            distance: 25
                        },
                        labels: []
                    };

                }

                var text = <get text you want to push>;

                annotationObject.labels.push(
                    {
                        point: {
                            xAxis: 0,
                            yAxis: 0,
                            x: point.x,
                            y: point.y
                        },
                        text: text
                    }

                );

                _chart.addAnnotation(annotationObject);
            });

I also found a bug in HighCharts when using remove annotations, as a heads up. Each point will need an id like above, but it should be called by this line:

           _chart.removeAnnotation(id);

It will remove the annotation, however you will get lots of complaints from highcharts if you try to do anything after, and it will break. I found the answer here, in annotations.js :

The red box is code I added. If you do removeAnnotation(ann.id), and it rerenders, it will fail because the labels object is null. Adding this check lets you do that without the labelCollectors failing.

Happy charting.


问:
Deal with EndOfStreamException from ZooKeeper while Curator's retry attempt?
I'm using Apache Curator framework to create a cluster, managed by ZK.

When suddenly some node in the cluster loses its connection to ZK, it tries to reconnect with it every 5 seconds. I'm using RetryForever policy with the specified timing for this.

While sessionTimeout/connectionTimeouts are not fully elapsed we're still trying to reconnect.

But even if we raised ZK and acquired connection to it within this time period, we're still getting strange messages in logs:

```<code>Thu Nov 30 20:47:51.574 GMT 2017|  INFO  | org.apache.zookeeper.ClientCnxn$SendThread | Socket connection established to zk_1.default/138.122.177.23:2181, initiating session |Client Details{sessionTag:{}}| localhost-startStop-1-SendThread(zk_1.default:2181)

Thu Nov 30 20:47:51.592 GMT 2017|  INFO  |
org.apache.zookeeper.ClientCnxn$SendThread | Unable to read additional
data from server sessionid 0x1600ea13dcd0000, likely server has closed
socket, closing socket connection and attempting reconnect |Client
Details{sessionTag:{}}|
localhost-startStop-1-SendThread(zk_1.default:2181)
</code>```

Why do we still receive these messages and can't fully connect to a freshly raised ZK node?

A little bit later I have found that this error means that ZK has exhausted its maxClientCnxns (maximum connections to ZK) parameter, but I haven't found how to configure it using Curator... Only in tests...

On ZK server side I see following errors:

```<code>2017-12-04 15:48:29,972 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /192.168.107.4:37130
2017-12-04 15:48:29,974 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:ZooKeeperServer@915] - Refusing session request for client /138.122.177.23:37130 as it has seen zxid 0xd our last zxid is 0x0 client must try another server
</code>```

答:
The answer is right here: http://grokbase.com/t/cloudera/cdh-user/134hrpr3nc/zookeeperserver-refusing-session-request-for-client-any-ideas

This means the client was talking to a ZK server and last saw transaction
ID 0x11be4 (or 72676 in decimal). The current server to which it's trying
to connect currently has transaction ID 0x3f82 (or 16258 in decimal) which
is (much) lower. The assumption is that the client has seen later data than
what the server could provide, potentially resulting in conflicting
information. Instead of giving the client bad (outdated) info, it refuses
the connection with the assumption that the client will reconnect to
another server in the quorum with more up to date data, or the currently
the outdated server will eventually receive a snapshot from another quorum
member to catch it up.

Body:
I'm using Apache Curator framework to create a cluster, managed by ZK.

When suddenly some node in the cluster loses its connection to ZK, it tries to reconnect with it every 5 seconds. I'm using RetryForever policy with the specified timing for this.

While sessionTimeout/connectionTimeouts are not fully elapsed we're still trying to reconnect.

But even if we raised ZK and acquired connection to it within this time period, we're still getting strange messages in logs:

Thu Nov 30 20:47:51.574 GMT 2017|  INFO  | org.apache.zookeeper.ClientCnxn$SendThread | Socket connection established to zk_1.default/138.122.177.23:2181, initiating session |Client Details{sessionTag:{}}| localhost-startStop-1-SendThread(zk_1.default:2181)

Thu Nov 30 20:47:51.592 GMT 2017|  INFO  |
org.apache.zookeeper.ClientCnxn$SendThread | Unable to read additional
data from server sessionid 0x1600ea13dcd0000, likely server has closed
socket, closing socket connection and attempting reconnect |Client
Details{sessionTag:{}}|
localhost-startStop-1-SendThread(zk_1.default:2181)

Why do we still receive these messages and can't fully connect to a freshly raised ZK node?

A little bit later I have found that this error means that ZK has exhausted its maxClientCnxns (maximum connections to ZK) parameter, but I haven't found how to configure it using Curator... Only in tests...

On ZK server side I see following errors:

2017-12-04 15:48:29,972 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /192.168.107.4:37130
2017-12-04 15:48:29,974 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:ZooKeeperServer@915] - Refusing session request for client /138.122.177.23:37130 as it has seen zxid 0xd our last zxid is 0x0 client must try another server


问:
How to remove div if its text is identical to another div?
I have a d3 area chart with a tooltip that displays the same text in two different divs. The first div, .tooltip.headline.record, displays the selected value in bold. Another div class, .record-label, displays the all of the values at a given point on the x-axis — for both the selected and non-selected paths. Here's a Plunker of the problem.

To illustrate, it currently looks like this:

I've been trying to achieve a result like this:

... or like this:

I've tried the following methods of hiding or removing the duplicative .record-label div, without success — and without error messages to assist in further diagnosis.

```<code>function getRecordContent(obj, pos) {
  if ( $(".tooltip-headline-record").text() == $(".record-label").text() ) {
  $(".record-label").hide();
  //$(".record-label").remove();
  //console.log("same");
  }
    return '<li><div class="record-label">' + obj.state + " " + obj.record.toLowerCase() + " " + numFormat(obj.values[pos].y) + '</div></li>'
}
</code>```

Here, again, is a Plunker that demonstrates the problem I'm trying to solve (see, specifically, the code beginning at line 480:
http://plnkr.co/edit/NfMeTpXzXGTxgNFKPFJe?p=preview

答:
Is this what you're looking for?

Plunkr

Relevant code changes:

The whole dataset was being passed to the getRecordContent function. So I changed that: when hovered over "admissions", pass "transfers" and "codependents". (line: 435)

```<code>var filtered_dataset = dataset.filter(function(row){return row.record !== d.record; });
for (var i = 0; i < filtered_dataset.length; i++) {
   content += getRecordContent(filtered_dataset[i], idx);
}
</code>```

Seems like you need to specify the state name as well along with the record. (line 480)

```<code>return '<li><span class="record-label">' + obj.state + ' ' + obj.record.toLowerCase() + '</span><span class="record-value">' + numFormat(obj.values[pos].y) + '</span></li>'
</code>```

Edit:

Changes made for the tooltip to adapt to the main chart as well:

```<code>var filtered_dataset = dataset.filter(function(row){return row.record !== d.record && row.state === d.state; });
</code>```

Changed z-index for the tooltip in main.css (try removing it and hovering close to the jquery slider)

```<code>z-index: 2;
</code>```

Hope this helps. :)

Body:
I have a d3 area chart with a tooltip that displays the same text in two different divs. The first div, .tooltip.headline.record, displays the selected value in bold. Another div class, .record-label, displays the all of the values at a given point on the x-axis — for both the selected and non-selected paths. Here's a Plunker of the problem.

To illustrate, it currently looks like this:

I've been trying to achieve a result like this:

... or like this:

I've tried the following methods of hiding or removing the duplicative .record-label div, without success — and without error messages to assist in further diagnosis.

function getRecordContent(obj, pos) {
  if ( $(".tooltip-headline-record").text() == $(".record-label").text() ) {
  $(".record-label").hide();
  //$(".record-label").remove();
  //console.log("same");
  }
    return '

' + obj.state + " " + obj.record.toLowerCase() + " " + numFormat(obj.values[pos].y) + '

'
}

Here, again, is a Plunker that demonstrates the problem I'm trying to solve (see, specifically, the code beginning at line 480:
http://plnkr.co/edit/NfMeTpXzXGTxgNFKPFJe?p=preview

Body:
Is this what you're looking for?

Plunkr

Relevant code changes:

The whole dataset was being passed to the getRecordContent function. So I changed that: when hovered over "admissions", pass "transfers" and "codependents". (line: 435)

var filtered_dataset = dataset.filter(function(row){return row.record !== d.record; });
for (var i = 0; i < filtered_dataset.length; i++) {
   content += getRecordContent(filtered_dataset[i], idx);
}

Seems like you need to specify the state name as well along with the record. (line 480)

return '<li><span class="record-label">' + obj.state + ' ' + obj.record.toLowerCase() + '</span><span class="record-value">' + numFormat(obj.values[pos].y) + '</span></li>'

Edit:

Changes made for the tooltip to adapt to the main chart as well:

var filtered_dataset = dataset.filter(function(row){return row.record !== d.record && row.state === d.state; });

Changed z-index for the tooltip in main.css (try removing it and hovering close to the jquery slider)

z-index: 2;

Hope this helps. :)


问:
NHibernate updates row before deleting it?
I'm having a strange behavior with nhibernate. The problem is that
nhibernate performs an update before it deletes an entity.
I have a Category class and a Product class. Category has a bag of
products. When I remove a product from Category, nhibernate does the
following:

It updates the product entity which I removed from collection

It deletes the product entity from database.

Here's mapping

```<code>  <class name="Category">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" length="20" />

    <bag name="Products" cascade="all-delete-orphan" lazy="false"
inverse="false">
      <key column="CategoryId" />
      <one-to-many class="Product" />
    </bag>
  </class>

  <class name="Product">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" />
    <property name="Discontinued" lazy="false" />
    <property name="Price" lazy="false" />
    <many-to-one name="Category"
             class="Category"
             column="CategoryId"
             cascade="none" />
  </class>
</code>```

Here's the code

```<code>    using (var session = NHibernateHelper.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
        var c1 = session.Load<Category>(32768);
        c1.Ps.RemoveAt(0);

        session.SaveOrUpdate(c1);
        transaction.Commit();
    }
</code>```

and here's the result:

```<code>exec sp_executesql N'UPDATE Product SET CategoryId = null WHERE
CategoryId = @p0 AND Id = @p1',N'@p0 int,@p1 int',@p0=32768,@p1=65537
go

exec sp_executesql N'DELETE FROM Product WHERE Id = @p0',N'@p0
int',@p0=65537
go
</code>```

Anyone can explain this strange behavior?

Thanks.

答:
EDIT: Sorry, got confused by the code; Ps is not a very descriptive property. What's happening in this case is that, because of the way you are deleting the Product (by removing it from the collection on Category and then saving the Category), NHibernate is first removing the reference to the Category from the Product, because that Product no longer belongs to the Category (this is a key translation between objects and tables; in OOP the reference is held by the containing object, while in SQL it's held by the contained object). Now the record doesn't belong to any Category; it's orphaned, and you've told NHibernate to clean up orphaned references in its cascade behavior, so it performs the delete.

If you want to do it with just one SQL statement, try this:

```<code>using (var session = NHibernateHelper.OpenSession())
using (var transaction = session.BeginTransaction())
{
    var c1 = session.Load<Category>(32768);
    var toDelete = c1.Ps[0];
    c1.Ps.RemoveAt(0);

    session.Delete(toDelete);
    transaction.Commit();
    //you shouldn't need to update the c1 object
}
</code>```

Body:
I'm having a strange behavior with nhibernate. The problem is that
nhibernate performs an update before it deletes an entity.
I have a Category class and a Product class. Category has a bag of
products. When I remove a product from Category, nhibernate does the
following:

It updates the product entity which I removed from collection

It deletes the product entity from database.

Here's mapping

  <class name="Category">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" length="20" />

    <bag name="Products" cascade="all-delete-orphan" lazy="false"
inverse="false">
      <key column="CategoryId" />
      <one-to-many class="Product" />
    </bag>
  </class>

  <class name="Product">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" />
    <property name="Discontinued" lazy="false" />
    <property name="Price" lazy="false" />
    <many-to-one name="Category"
             class="Category"
             column="CategoryId"
             cascade="none" />
  </class>

Here's the code

    using (var session = NHibernateHelper.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
        var c1 = session.Load<Category>(32768);
        c1.Ps.RemoveAt(0);

        session.SaveOrUpdate(c1);
        transaction.Commit();
    }

and here's the result:

exec sp_executesql N'UPDATE Product SET CategoryId = null WHERE
CategoryId = @p0 AND Id = @p1',N'@p0 int,@p1 int',@p0=32768,@p1=65537
go

exec sp_executesql N'DELETE FROM Product WHERE Id = @p0',N'@p0
int',@p0=65537
go

Anyone can explain this strange behavior?

Thanks.

Body:
EDIT: Sorry, got confused by the code; Ps is not a very descriptive property. What's happening in this case is that, because of the way you are deleting the Product (by removing it from the collection on Category and then saving the Category), NHibernate is first removing the reference to the Category from the Product, because that Product no longer belongs to the Category (this is a key translation between objects and tables; in OOP the reference is held by the containing object, while in SQL it's held by the contained object). Now the record doesn't belong to any Category; it's orphaned, and you've told NHibernate to clean up orphaned references in its cascade behavior, so it performs the delete.

If you want to do it with just one SQL statement, try this:

using (var session = NHibernateHelper.OpenSession())
using (var transaction = session.BeginTransaction())
{
    var c1 = session.Load<Category>(32768);
    var toDelete = c1.Ps[0];
    c1.Ps.RemoveAt(0);

    session.Delete(toDelete);
    transaction.Commit();
    //you shouldn't need to update the c1 object
}


问:
TF Timeline shows serial execution despite multithreading settings on Dataset
I am relatively new to Tensorflow, still struggling to understand how I can improve performance. I used the TF Timeline tool to examine the execution of my code, and I was surprised to see that execution looks like it's serial, as shown in this image below:

The code below is what I used to set up the data input:

```<code>filenames = tf.placeholder(tf.string, shape=[None])
dataset   = tf.data.TFRecordDataset(filenames, "ZLIB", 128 * 1024 * 1024)
dataset   = dataset.map(_parse_function, 13)
dataset   = dataset.batch(8192)
dataset   = dataset.prefetch(8192 * 3)
iterator  = dataset.make_initializable_iterator()
X, y      = iterator.get_next()
</code>```

In particular, given that I have set the number of worker threads on map to 13 (consistent with my hardware) and also set a prefetch equal to 3 times batch size, I would have expected the CPU to fully overlap with GPU and CPU/GPU transfer time. So my questions are:

Why does this look serial? Am I misreading what I see?

Is there something wrong with how I am using Dataset? I understand that batch size & prefetching size should eventually be tuned to get optimal performance, but what's the point if I don't see parallel use of CPU vs. GPU at all?

答:
The profile looks serial because none of operations in (the parallel invocations of) _parse_function() are included in the timeline trace. The IteratorGetNext trace region will overlap with some of the operations in the pipeline, but the dataset.prefetch(8192 * 3) means that most of the work will be being performed asynchronously in a background thread.

David Parks' comment makes a good point: a prefetch buffer size of 8192 * 3 batches is probably larger than you need, and might be causing memory pressure. Typically setting the prefetch buffer size to a small value (e.g. 1 or 2) is sufficient to overlap preprocessing with training; I would expect diminishing returns soon after that point. Try increasing the num_parallel_calls argument to Dataset.map() to see if this increases the throughput of your training.

Body:
I am relatively new to Tensorflow, still struggling to understand how I can improve performance. I used the TF Timeline tool to examine the execution of my code, and I was surprised to see that execution looks like it's serial, as shown in this image below:

The code below is what I used to set up the data input:

filenames = tf.placeholder(tf.string, shape=[None])
dataset   = tf.data.TFRecordDataset(filenames, "ZLIB", 128 * 1024 * 1024)
dataset   = dataset.map(_parse_function, 13)
dataset   = dataset.batch(8192)
dataset   = dataset.prefetch(8192 * 3)
iterator  = dataset.make_initializable_iterator()
X, y      = iterator.get_next()

In particular, given that I have set the number of worker threads on map to 13 (consistent with my hardware) and also set a prefetch equal to 3 times batch size, I would have expected the CPU to fully overlap with GPU and CPU/GPU transfer time. So my questions are:

Why does this look serial? Am I misreading what I see?

Is there something wrong with how I am using Dataset? I understand that batch size & prefetching size should eventually be tuned to get optimal performance, but what's the point if I don't see parallel use of CPU vs. GPU at all?


问:
Implementing Modal as confirmation before redirecting
I am currently trying to implement a table that, when a row is clicked on, will display a modal that acts as a confirmation page where the user can then submit the information. When the user clicks on the submit in the modal, it needs to add the row data to a sql database and redirect the user to another page. I am stuck on how to pass the information that the user clicks on to my python code where I can add it to sql and I can't get the page to redirect.

This is my table tag

```<code><tr class="room" data-id="{{ res.room_id }}" data-toggle="modal" data-target="#orderModal" >
</code>```

This is my modal

```<code><div id="orderModal" class="modal fade" role="dialog" aria-labelledby="orderModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2>Order</h2>
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
      </div>
      <div id="orderDetails" class="modal-body"></div>
      <div id="orderItems" class="modal-body"></div>

      <div class="modal-footer">
           <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <a href="#" id="submit" type="submit" class="btn btn-success">Submit</a>
      </div>
    </div>
  </div>
</div>

</div>
</code>```

This is my javascript

```<code>$('#orderModal').modal({
        keyboarnd: true,
        backdrop: "static",
        show:false,

    }).on('show.bs.modal', function(){
          var getIdFromRow = $(this).data('orderid');
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });

    $(".table-striped").find('tr[data-target]').on('click', function(){
        //or do your operations here instead of on show of modal to populate values to modal.
         $('#orderModal').data('orderid',$(this).data('id'));
    });
</code>```

This is my python pseudocode

```<code>@app.route("/table", methods=["GET", "POST"])
@login_required
def book():
     # """Confirm the room you have selected to book"""

     # User reached route via POST (as by submitting a form via POST) --> BUT ONLY BY CLICKING OK BUTTON, NOT CANCEL BUTTON
    if request.method == "POST":

         # Update bookings with user's booking
         # Redirect to history.html where it displays a table of only your history of bookings (date, start time, end time, room)

          return redirect("/")

    else:
        return render_template("history.html")
</code>```

Thank you for any help!

答:
You can use Bootbox.js for confirmation modal

http://bootboxjs.com

Body:
I am currently trying to implement a table that, when a row is clicked on, will display a modal that acts as a confirmation page where the user can then submit the information. When the user clicks on the submit in the modal, it needs to add the row data to a sql database and redirect the user to another page. I am stuck on how to pass the information that the user clicks on to my python code where I can add it to sql and I can't get the page to redirect.

This is my table tag

This is my modal

Order

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>

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

This is my javascript

$('#orderModal').modal({
        keyboarnd: true,
        backdrop: "static",
        show:false,

    }).on('show.bs.modal', function(){
          var getIdFromRow = $(this).data('orderid');
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($(' Order Id selected: ' + getIdFromRow  + ''))
    });

    $(".table-striped").find('tr[data-target]').on('click', function(){
        //or do your operations here instead of on show of modal to populate values to modal.
         $('#orderModal').data('orderid',$(this).data('id'));
    });

This is my python pseudocode

@app.route("/table", methods=["GET", "POST"])
@login_required
def book():
     # """Confirm the room you have selected to book"""

     # User reached route via POST (as by submitting a form via POST) --> BUT ONLY BY CLICKING OK BUTTON, NOT CANCEL BUTTON
    if request.method == "POST":

         # Update bookings with user's booking
         # Redirect to history.html where it displays a table of only your history of bookings (date, start time, end time, room)

          return redirect("/")

    else:
        return render_template("history.html")

Thank you for any help!


问:
Split list into smaller lists of n-size with stream
How can I take a Java list and split it into smaller lists of size n in Java using streams?

In JavaScript, I'd use the reduce() function and do something like this:

const n = 3;
const sublists = [1,2,3,4,5,6,7,8,9,0]
  .reduce((r, i) => {
    r[r.length - 1].length == n
      ? r.push([i])
      : r[r.length - 1].push(i);
    return r;
  }, [[]]);
console.log(sublists);```

I'm trying to do that with a Java stream, but I can't seem to figure out how to get it to let me use an ArrayList<ArrayList<Integer>> as my initial value and then add the lists. I'm a little confused how the combinator and accumulator play in to let me use them, or even if reduce() is the best approach for Java.

答:
Pretty straightforward:

```<code>    List<Integer> list = List.of(1, 2, 3, 4, 5, 7, 8, 9, 10, 11);
    int n = 3;
    List<List<Integer>> result = new LinkedList<>();
    int size = list.size();
    for (int i = 0; i <= size; i += n) {
        result.add(list.subList(i, Math.min(i + n, size)));
    }
    System.out.println(result);  // [[1, 2, 3], [4, 5, 7], [8, 9, 10], [11]]
</code>```

A Java 8 solution:

```<code>List<Integer> list = List.of(1, 2, 3, 4, 5, 7, 8, 9, 10, 11);
int n = 3;
List<List<Integer>> result = IntStream.range(0, list.size())
    .filter(i -> i % n == 0)
    .mapToObj(i -> list.subList(i, Math.min(i + n, list.size())))
    .collect(Collectors.toList());
System.out.println(result);  // [[1, 2, 3], [4, 5, 7], [8, 9, 10], [11]]
</code>```

Body:
How can I take a Java list and split it into smaller lists of size n in Java using streams?

In JavaScript, I'd use the reduce() function and do something like this:

const n = 3;
const sublists = [1,2,3,4,5,6,7,8,9,0]
  .reduce((r, i) => {
    r[r.length - 1].length == n
      ? r.push([i])
      : r[r.length - 1].push(i);
    return r;
  }, [[]]);
console.log(sublists);

I'm trying to do that with a Java stream, but I can't seem to figure out how to get it to let me use an ArrayList<ArrayList<Integer>> as my initial value and then add the lists. I'm a little confused how the combinator and accumulator play in to let me use them, or even if reduce() is the best approach for Java.

Body:
Pretty straightforward:

    List<Integer> list = List.of(1, 2, 3, 4, 5, 7, 8, 9, 10, 11);
    int n = 3;
    List<List<Integer>> result = new LinkedList<>();
    int size = list.size();
    for (int i = 0; i <= size; i += n) {
        result.add(list.subList(i, Math.min(i + n, size)));
    }
    System.out.println(result);  // [[1, 2, 3], [4, 5, 7], [8, 9, 10], [11]]

A Java 8 solution:

List<Integer> list = List.of(1, 2, 3, 4, 5, 7, 8, 9, 10, 11);
int n = 3;
List<List<Integer>> result = IntStream.range(0, list.size())
    .filter(i -> i % n == 0)
    .mapToObj(i -> list.subList(i, Math.min(i + n, list.size())))
    .collect(Collectors.toList());
System.out.println(result);  // [[1, 2, 3], [4, 5, 7], [8, 9, 10], [11]]


问:
Accuracy of integer sqrt using double
I would like to compute the integer part of an uint64_t. For 32-bit uint32_t, it is frequently recommended to first cast it to double, sqrt and then cast it back to uint32_t.

Does it work for uint64_t as well, given that double can exactly accommodate numbers only up to 2^53? I.e., is the following always going to give the correct answer:

```<code>#include <math.h>
uint64_t x = ...;
uint64_t result = (uint64_t)sqrt((double)x);
</code>```

or even:

```<code>#include <math.h>
uint64_t x = ...;
uint32_t result = (uint32_t)sqrt((double)x);
</code>```

答:
Empirically, the answer is no.  The result for an input of 4503599761588224 is computed incorrectly as 67108865 rather than 67108864.

The following code identifies this case.1  Of course, you can remove the break; to observe other cases.

#include <stdio.h>
#include <stdint.h>
#include <math.h>

int main(void) {
    for (uint32_t y = 1; y != 0; y++) {
        // *Just* smaller than a perfect square
        uint64_t x = ((uint64_t)y * (uint64_t)y) - 1;

        // We expect the floor of the result
        uint32_t expected = y - 1;

        uint32_t result = (uint32_t)sqrt((double)x);

        if (result != expected) {
            printf("Incorrect: x = %llu, result = %u\n", x, result);
            break;
        }
    }
    return 0;
}
```

What's special about the value 4503599761588224?  Well, it's exactly (226 + 1)2 - 1, AKA (252 + 227).  This can be exactly represented by a double, so the error is not due to the long -> double conversion.

Instead, the error is internal to the sqrt implementation.  The delta (vs. a perfect square) here reduces the square root by around 2-27, which is around 253 times smaller than result itself.  This is at the limit of what double-precision can handle, so we would naturally expect to see off-by-one errors at this point.2

1. Live demo.

2. Credit to @EricPostpischil for identifying the root cause in comments below :)

Title: Accuracy of integer sqrt using double

Body:
I would like to compute the integer part of an uint64_t. For 32-bit uint32_t, it is frequently recommended to first cast it to double, sqrt and then cast it back to uint32_t.

Does it work for uint64_t as well, given that double can exactly accommodate numbers only up to 2^53? I.e., is the following always going to give the correct answer:

#include <math.h>
uint64_t x = ...;
uint64_t result = (uint64_t)sqrt((double)x);

or even:

#include <math.h>
uint64_t x = ...;
uint32_t result = (uint32_t)sqrt((double)x);

Body:
Empirically, the answer is no.  The result for an input of 4503599761588224 is computed incorrectly as 67108865 rather than 67108864.

The following code identifies this case.1  Of course, you can remove the break; to observe other cases.

#include <stdio.h>
#include <stdint.h>
#include <math.h>

int main(void) {
    for (uint32_t y = 1; y != 0; y++) {
        // *Just* smaller than a perfect square
        uint64_t x = ((uint64_t)y * (uint64_t)y) - 1;

        // We expect the floor of the result
        uint32_t expected = y - 1;

        uint32_t result = (uint32_t)sqrt((double)x);

        if (result != expected) {
            printf("Incorrect: x = %llu, result = %u\n", x, result);
            break;
        }
    }
    return 0;
}

What's special about the value 4503599761588224?  Well, it's exactly (226 + 1)2 - 1, AKA (252 + 227).  This can be exactly represented by a double, so the error is not due to the long -> double conversion.

Instead, the error is internal to the sqrt implementation.  The delta (vs. a perfect square) here reduces the square root by around 2-27, which is around 253 times smaller than result itself.  This is at the limit of what double-precision can handle, so we would naturally expect to see off-by-one errors at this point.2

1. Live demo.

2. Credit to @EricPostpischil for identifying the root cause in comments below :)


问:
amc, aerospike are not recognized inside docker container
I've docker ubuntu 16.04 image and I'm running aerospike server in it.

```<code>$ docker run -d -p 3000:3000 -p 3001:3001 -p 3002:3002 -p 3003:3003  -p 8081:8081  --name aerospike aerospike/aerospike-server
</code>```

The docker container is running successfully.

```<code>$ docker ps
CONTAINER ID        IMAGE                        COMMAND
CREATED             STATUS              PORTS
NAMES
b0b4c63d7e22        aerospike/aerospike-server   "/entrypoint.sh asd"
36 seconds ago      Up 35 seconds       0.0.0.0:3000-3003->3000-3003/tcp, 0.0.0.0:8081->8081/tcp   aerospike
</code>```

I've logged into the docker container

```<code>$ docker exec -it b0b4c63d7e22 bash
root@b0b4c63d7e22:/#
</code>```

I have listed the directories -

```<code>root@b0b4c63d7e22:/# ls
bin  boot  core  dev  entrypoint.sh  etc  home  lib  lib64  media  mnt  opt
proc  root  run  sbin  srv  sys  tmp  usr  var
root@b0b4c63d7e22:/#
</code>```

I changed the directory to bin folder and listed the commands

```<code>root@b0b4c63d7e22:/# cd bin
root@b0b4c63d7e22:/bin# ls
bash   dnsdomainname  ip          mount          readlink    systemctl
touch         zegrep
cat    domainname     journalctl  mountpoint     rm          systemd
true          zfgrep
chgrp  echo           kill        mv             rmdir       systemd-ask-
password            umount        zforce
chmod  egrep          ln          netstat        run-parts   systemd-escape
uname         zgrep
chown  false          login       networkctl     sed         systemd-inhibit
uncompress    zless
cp     fgrep          loginctl    nisdomainname  sh          systemd-machine-
id-setup        vdir          zmore
dash   findmnt        ls          pidof          sh.distrib  systemd-notify
wdctl         znew
date   grep           lsblk       ping           sleep       systemd-tmpfiles
which
dd     gunzip         mkdir       ping6          ss          systemd-tty-ask-
password-agent  ypdomainname
df     gzexe          mknod       ps             stty        tailf
zcat
dir    gzip           mktemp      pwd            su          tar
zcmp
dmesg  hostname       more        rbash          sync        tempfile
zdiff
</code>```

Then I want to check the service -

```<code>root@b0b4c63d7e22:/bin# service amc status
amc: unrecognized service
</code>```

答:
Aerospike's official docker container does not have Aerospike Server running as a daemon, but instead as a foreground process. You can see this in the official github DOCKERFILE.

AMC is not part of Aerospike's Docker Image. It is up to you to run AMC from the environment of your choosing.

Finally, since you have not created a custom aerospike.conf file, Aerospike Server will only respond to clients on the Docker internal network. The -p parameters are not sufficient in itself to expose Aerospike's ports to clients, you'd also need to configure access-address, if you'd want client access from outside of the docker environment. Read more about Aerospike's networking at: https://www.aerospike.com/docs/operations/configure/network/general

Body:
I've docker ubuntu 16.04 image and I'm running aerospike server in it.

$ docker run -d -p 3000:3000 -p 3001:3001 -p 3002:3002 -p 3003:3003  -p 8081:8081  --name aerospike aerospike/aerospike-server

The docker container is running successfully.

$ docker ps
CONTAINER ID        IMAGE                        COMMAND
CREATED             STATUS              PORTS
NAMES
b0b4c63d7e22        aerospike/aerospike-server   "/entrypoint.sh asd"
36 seconds ago      Up 35 seconds       0.0.0.0:3000-3003->3000-3003/tcp, 0.0.0.0:8081->8081/tcp   aerospike

I've logged into the docker container

$ docker exec -it b0b4c63d7e22 bash
root@b0b4c63d7e22:/#

I have listed the directories -

root@b0b4c63d7e22:/# ls
bin  boot  core  dev  entrypoint.sh  etc  home  lib  lib64  media  mnt  opt
proc  root  run  sbin  srv  sys  tmp  usr  var
root@b0b4c63d7e22:/#

I changed the directory to bin folder and listed the commands

root@b0b4c63d7e22:/# cd bin
root@b0b4c63d7e22:/bin# ls
bash   dnsdomainname  ip          mount          readlink    systemctl
touch         zegrep
cat    domainname     journalctl  mountpoint     rm          systemd
true          zfgrep
chgrp  echo           kill        mv             rmdir       systemd-ask-
password            umount        zforce
chmod  egrep          ln          netstat        run-parts   systemd-escape
uname         zgrep
chown  false          login       networkctl     sed         systemd-inhibit
uncompress    zless
cp     fgrep          loginctl    nisdomainname  sh          systemd-machine-
id-setup        vdir          zmore
dash   findmnt        ls          pidof          sh.distrib  systemd-notify
wdctl         znew
date   grep           lsblk       ping           sleep       systemd-tmpfiles
which
dd     gunzip         mkdir       ping6          ss          systemd-tty-ask-
password-agent  ypdomainname
df     gzexe          mknod       ps             stty        tailf
zcat
dir    gzip           mktemp      pwd            su          tar
zcmp
dmesg  hostname       more        rbash          sync        tempfile
zdiff

Then I want to check the service -

root@b0b4c63d7e22:/bin# service amc status
amc: unrecognized service