问:
ContentEditable div is not working properly in JS fiddle
While writing in between the sentence of the contenteditable div in JS fiddle, cursor position is goes to end of the sentence.

JSFiddle

答:
Instead of timer event, use key up. I have used wait for tree seconds, after key up. You can change it to increase or decrease delay.</p>

```<code>            <script>

            var changed, timer,
            lastValue = '',
            div = $('#ce'),
            words = ['oele', 'geel', 'politie', 'foo bar'];

        function markWords() {
            var html = div.html().replace(/<\/?strong>/gi, ''),
                text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '),
                exp;
            $.each(words, function(i, word) {
                exp = new RegExp('\\b(' + word + ')\\b', 'gi');
                html = html.replace(exp, function(m) {
               // console.log('WORD MATCH:', m);
                return '<strong>' + m + '</strong>';
                });
            });
            //html = html.replace(' ', ' ').replace(/\s+/g, ' ');
        //console.log('HTML:', html);
        //console.log('----');
            div.html(html);
        }

        //setInterval(function() {
        //    var html = div.html();
        //    if ( lastValue !== html && html ) {
        //console.log(lastValue);
        //console.log(html);
        ////console.log('----');
        //        lastValue = html;
        //        markWords();
        //        setEndOfContenteditable(div[0]);
        //    }
        //}, 500);

        $("#ce").on('keyup', function() {
            clearTimeout(timer);  //clear any running timeout on key up
            timer = setTimeout(function() { //then give it a second to see if the user is finished
                //do
                var html = div.html();
                if ( lastValue !== html && html ) {
            // console.log(lastValue);
            // console.log(html);
            //console.log('----');
                    lastValue = html;
                    markWords();
                    setEndOfContenteditable(div[0]);
                }

            }, 3000);
        });

        function setEndOfContenteditable(contentEditableElement)
        {
            var range,selection;
            if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
            {
                range = document.createRange();//Create a range (a range is a like the selection but invisible)
                range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                selection = window.getSelection();//get the selection object (allows you to change selection)
                selection.removeAllRanges();//remove any selections already made
                selection.addRange(range);//make the range you have just created the visible selection
            }
            else if(document.selection)//IE 8 and lower
            {
                range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                range.select();//Select the range (make it the visible selection
            }
        }

        markWords();
        setEndOfContenteditable(div[0]);
        </script>
</code>```

Body:
Instead of timer event, use key up. I have used wait for tree seconds, after key up. You can change it to increase or decrease delay.

            <script>

            var changed, timer,
            lastValue = '',
            div = $('#ce'),
            words = ['oele', 'geel', 'politie', 'foo bar'];

        function markWords() {
            var html = div.html().replace(/<\/?strong>/gi, ''),
                text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '),
                exp;
            $.each(words, function(i, word) {
                exp = new RegExp('\\b(' + word + ')\\b', 'gi');
                html = html.replace(exp, function(m) {
               // console.log('WORD MATCH:', m);
                return '<strong>' + m + '</strong>';
                });
            });
            //html = html.replace('&nbsp;', ' ').replace(/\s+/g, ' ');
        //console.log('HTML:', html);
        //console.log('----');
            div.html(html);
        }

        //setInterval(function() {
        //    var html = div.html();
        //    if ( lastValue !== html && html ) {
        //console.log(lastValue);
        //console.log(html);
        ////console.log('----');
        //        lastValue = html;
        //        markWords();
        //        setEndOfContenteditable(div[0]);
        //    }
        //}, 500);

        $("#ce").on('keyup', function() {
            clearTimeout(timer);  //clear any running timeout on key up
            timer = setTimeout(function() { //then give it a second to see if the user is finished
                //do
                var html = div.html();
                if ( lastValue !== html && html ) {
            // console.log(lastValue);
            // console.log(html);
            //console.log('----');
                    lastValue = html;
                    markWords();
                    setEndOfContenteditable(div[0]);
                }

            }, 3000);
        });

        function setEndOfContenteditable(contentEditableElement)
        {
            var range,selection;
            if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
            {
                range = document.createRange();//Create a range (a range is a like the selection but invisible)
                range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                selection = window.getSelection();//get the selection object (allows you to change selection)
                selection.removeAllRanges();//remove any selections already made
                selection.addRange(range);//make the range you have just created the visible selection
            }
            else if(document.selection)//IE 8 and lower
            {
                range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                range.select();//Select the range (make it the visible selection
            }
        }

        markWords();
        setEndOfContenteditable(div[0]);
        </script>


来源: stackexchange

问:
Reading 2 GB file with C# takes too much time
I have an indented text file in the following pattern:

```
cl /FoD:\jnks\complire_flags /c legacy\roxapi\fjord\Module.c

Note: including file:   d:\jnks\e\patchlevel.f

Note: including file:   d:\3_4_2_patched4\release\include\pyconfig.f
Note: including file:    C:\11.0\VC\INCLUDE\io.f
```

Using stream reader, I am able to read the above file which requires following processing.

1) Every line starting with cl and ending with c is the Parent file.

2) All files starting with Note and ending with f are child files.

3) The .f file is parent of the .f file below it if left indent increases,(space between file: and drive name) hence pyconfig.f is a parent of io.f

Using Entity framework I am writing above data in two tables of SQL server;
Parent table (for only .c files) and Child table (for only .f files).

My big issue here is- It takes 6 hours to read the file (using stream reader) and another 6 hours to write it in the database (using entity framework).  I tried first reading the whole file and then writing it. I have also tried reading the file one Parent c file at a time and writing its info along with the child .f files.

The file size might increase in future to 5 GB so I really would appreciate help in achieving better performance.

Below is a part of my read logic:

```<code>while (!isEndOfFile)
{
    // Read next Line conditionally
    if (readNextLine)
    {
        if (inputFile.Peek() > -1)
        {
            line = inputFile.ReadLine();
        }
        else
        {
            isEndOfFile = true;
            continue;
        }
    }

    // Get the name of the CPP file - Condition is that it starts with cl
    if (isCPPFile(line))
    {
        // Regular expression match to extract the CPP file name
        Match match = cppFilePathRegex.Match(line);
        if (match.Success)
        {
            cppFileName = match.Value;
            addFileDetails = true;
        }
        readNextLine = true;
    }
    // Check if meets the condition of Header starting text - "Note: including file:" and we have a parent CPP File
    else if (addFileDetails && isHeaderFile(line))
    {
        //do something
    }
</code>```

答:
1) Go and read why GNU grep is fast?. It gives a number of hints on how to process fast input text files, specifically looking for patterns.

2) Use SQlBulkCopy to transfer the data into SQL Server. EF is definitely not an appropriate solution for bulk import.

But, if I was you, I would do a del /q /s on my entire import solution and start from scratch using SQL Server Integration Services. SSIS is a dedicated solution for your task, it contains countless optimizations around file read, record access, buffering, cache access and ultimately database writes.

ContentLicense: CC BY-SA 3.0

Body:
I have an indented text file in the following pattern:

cl /FoD:\jnks\complire_flags /c legacy\roxapi\fjord\Module.c

Note: including file:   d:\jnks\e\patchlevel.f

Note: including file:   d:\3_4_2_patched4\release\include\pyconfig.f
Note: including file:    C:\11.0\VC\INCLUDE\io.f

Using stream reader, I am able to read the above file which requires following processing.

1) Every line starting with cl and ending with c is the Parent file.

2) All files starting with Note and ending with f are child files.

3) The .f file is parent of the .f file below it if left indent increases,(space between file: and drive name) hence pyconfig.f is a parent of io.f

Using Entity framework I am writing above data in two tables of SQL server;
Parent table (for only .c files) and Child table (for only .f files).

My big issue here is- It takes 6 hours to read the file (using stream reader) and another 6 hours to write it in the database (using entity framework).  I tried first reading the whole file and then writing it. I have also tried reading the file one Parent c file at a time and writing its info along with the child .f files.

The file size might increase in future to 5 GB so I really would appreciate help in achieving better performance.

Below is a part of my read logic:

while (!isEndOfFile)
{
    // Read next Line conditionally
    if (readNextLine)
    {
        if (inputFile.Peek() > -1)
        {
            line = inputFile.ReadLine();
        }
        else
        {
            isEndOfFile = true;
            continue;
        }
    }

    // Get the name of the CPP file - Condition is that it starts with cl
    if (isCPPFile(line))
    {
        // Regular expression match to extract the CPP file name
        Match match = cppFilePathRegex.Match(line);
        if (match.Success)
        {
            cppFileName = match.Value;
            addFileDetails = true;
        }
        readNextLine = true;
    }
    // Check if meets the condition of Header starting text - "Note: including file:" and we have a parent CPP File
    else if (addFileDetails && isHeaderFile(line))
    {
        //do something
    }


问:
How to select earliest date according to current sg
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.</p>

```<code>empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31
</code>```

答:
THE SOLUTION:

```<code>SELECT TOP 1 *
FROM YourTableNameHere
ORDER BY Sg DESC, Date_From
</code>```

More Details:

Use ORDER BY in combination with TOP 1. Below I used a temp table that you can run in a NEW QUERY window.

Try this out:

```<code>CREATE TABLE #TempTable(
 Position varchar(20),
 Sg varchar(3),
 Date_From datetime,
 Date_To datetime)

INSERT INTO #TempTable (Position, Sg, Date_From, Date_To)

SELECT
        'ADMIN AIDE IV', '4-3', '2017-01-01', '1900-01-01'
UNION
SELECT
        'ADMIN AIDE IV', '4-3', '2016-01-01', '2016-12-31'
UNION
SELECT
        'ADMIN AIDE IV', '4-3', '2015-01-01', '2015-12-31'
UNION
SELECT
        'ADMIN AIDE IV', '4-2', '2014-01-01', '2014-12-31'
UNION
SELECT
        'ADMIN AIDE IV', '4-2', '2013-01-01', '2013-12-31'

SELECT TOP 1 *
FROM #TempTable
ORDER BY Sg DESC, Date_From
</code>```

Body:
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.

empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31

Body:
THE SOLUTION:

SELECT TOP 1 *
FROM YourTableNameHere
ORDER BY Sg DESC, Date_From

More Details:

Use ORDER BY in combination with TOP 1. Below I used a temp table that you can run in a NEW QUERY window.

Try this out:

CREATE TABLE #TempTable(
 Position varchar(20),
 Sg varchar(3),
 Date_From datetime,
 Date_To datetime)

INSERT INTO #TempTable (Position, Sg, Date_From, Date_To)

SELECT
        'ADMIN AIDE IV', '4-3', '2017-01-01', '1900-01-01'
UNION
SELECT
        'ADMIN AIDE IV', '4-3', '2016-01-01', '2016-12-31'
UNION
SELECT
        'ADMIN AIDE IV', '4-3', '2015-01-01', '2015-12-31'
UNION
SELECT
        'ADMIN AIDE IV', '4-2', '2014-01-01', '2014-12-31'
UNION
SELECT
        'ADMIN AIDE IV', '4-2', '2013-01-01', '2013-12-31'

SELECT TOP 1 *
FROM #TempTable
ORDER BY Sg DESC, Date_From


问:
Seeing the active css element outline style in chrome developer tooling?
In chrome the below button will retain it's outline after it has been clicked.  If I looked at the buttons css settings after selecting the :active checkbox in chrome's developer tools I still can't see what the CSS values are for the outline.  It appears to be about 1px in width and grey visually, but I don't see these values.  Is there a way to see them?

  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>
```
</div>
</div>
</p>

<p>In other words google chrome does add this style (As indicated by one of the answer below):</p>

``` :focus {
     outline: -webkit-focus-ring-color auto 5px;
 }
```

However when I click the focus checkbox in order to be able to see all the CSS that is triggered by focus, I don't see that style in the developer tooling pane ... Is it a google developer tooling bug or do other people see it?

答: The styles console in the chrome developer tools only shows what is currently selected in it's current state. If you want to see the rules for the other states a simple way is to go to the css file it self. To do that next to the element class there is a link as shown in the image below. Clicking this will open the actual css file in the specific row of the selected class. Assuming the other states are declared close to that you'll be able to locate the class you want.

Body:
In chrome the below button will retain it's outline after it has been clicked.  If I looked at the buttons css settings after selecting the :active checkbox in chrome's developer tools I still can't see what the CSS values are for the outline.  It appears to be about 1px in width and grey visually, but I don't see these values.  Is there a way to see them?

  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>

In other words google chrome does add this style (As indicated by one of the answer below):

 :focus {
     outline: -webkit-focus-ring-color auto 5px;
 }

However when I click the focus checkbox in order to be able to see all the CSS that is triggered by focus, I don't see that style in the developer tooling pane ... Is it a google developer tooling bug or do other people see it?


问:
R Shiny Dashboard does not load rendered UI inside of sidebarMenu on initialization
I'm trying to generate a UI element that is dynamic based on how the user wishes to provide their input. I'm using the Shiny Dashboard for simplicity but I have encountered an issue with the sidebarMenu. Previously when I was placing static UI elements directly into the sidebarMenu, I had no issue, however when trying to place dynamic UI elements into the sidebarMenu I have problems. I'm using R 3.3.2 and Shiny 1.0.0 and Dashboard 0.5.3.

The specific problem I have is that when the program first loads up, the dynamic UI elements do not load. There does not appear to be any holdup in the code, as all the features of the interface work fine even while the dynamic UI is unloaded. I am able to get the dynamic UI to load by selecting one of the tabs in the navbar, or by hovering over something that I have implemented a tooltip on.

I am unable to provide the exact code but I have recreated a much smaller reproducible example that has all the same problems that my larger version does.

```<code>library("shiny")
library("shinydashboard")

header = dashboardHeader(
    title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
    sidebarMenu(
        menuItemOutput("dynamic_sidebar")
    )
)
body = dashboardBody(
    tabBox(
        tabPanel(
            strong("One")
        ),
        tabPanel(
            strong("Two")
        )
    )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){
output$dynamic_sidebar = renderMenu({
        sidebarMenu(
            menuItem(
                "Slider or numeric problem",
                radioButtons("slider_or_numeric",
                   label = "Slider or Numeric Input",
                   choices = c("Slider", "Numeric"),
                   selected = "Slider",
                   inline = TRUE
                ),
                uiOutput("input")
            )
        )
    })
    output$input = renderUI({
        if (input$slider_or_numeric == "Slider"){
            sliderInput("slider",
                label = "slider",
                min = 0, max = 1,
                value = 0
            )
        } else {
            numericInput("numeric",
                label = "numeric",
                min = 0, max = 1,
                value = 0
            )
        }
    })
})

shinyApp(ui, server)
</code>```

To verify the problem, after loading it up just open the menu item and you'll see the radio buttons but nothing else. Switch the tab on the navbar from one to two, and the input should appear in the menu (must be done while the menu is open).

I'm really just grasping at straws here, I have been troubleshooting this for hours and I think it's just an incompatibility with these features. I'm really hoping someone can prove me wrong and show me that I'm just doing it wrong. I've already found alternatives for my main program but they don't have the same aesthetic with what I'm trying to accomplish here.

Thanks for any and all help!

答:
I think I found the issue, it was tricky, and took me awhile to find it. Although it is a small change, I will post the whole thing.

I think this is what you want:

```<code>library("shiny")
library("shinydashboard")

header = dashboardHeader(
  title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
  sidebarMenu(
    menuItemOutput("dynamic_sidebar")
  )
)
body = dashboardBody(
  tabBox(
    tabPanel(
      strong("One")
    ),
    tabPanel(
      strong("Two")
    )
  )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){
  output$dynamic_sidebar = renderMenu({
    sidebarMenu(
      menuItem(
        "Slider or numeric problem",
        radioButtons("slider_or_numeric",
                     label = "Slider or Numeric Input",
                     choices = c("Slider", "Numeric"),
                     selected = "Slider",
                     inline = TRUE
        )
      ),
      uiOutput("input")  # no longer in menuItem call
    )
  })
  output$input = renderUI({
    if (input$slider_or_numeric == "Slider"){
      sliderInput("slider",
                  label = "slider",
                  min = 0, max = 1,
                  value = 0
      )
    } else {
      numericInput("numeric",
                   label = "numeric",
                   min = 0, max = 1,
                   value = 0
      )
    }
  })
})
shinyApp(ui, server)
</code>```

I think the problem was that uiOutput("input") somehow slipped into the menuItem call. This is a hazard with Shiny, and Shiny editors obviously need more support for showing this kind of scope.

Frankly I am a bit puzzled as to why it ever showed up when you played around with it. But enough...

While I am not completely sure I understand how you want this to work (it is just a toy example obviously), this is how it looks now at startup:

And here after the menu expansion and changing the input type via the newly exposed radio button control.

Body:
I'm trying to generate a UI element that is dynamic based on how the user wishes to provide their input. I'm using the Shiny Dashboard for simplicity but I have encountered an issue with the sidebarMenu. Previously when I was placing static UI elements directly into the sidebarMenu, I had no issue, however when trying to place dynamic UI elements into the sidebarMenu I have problems. I'm using R 3.3.2 and Shiny 1.0.0 and Dashboard 0.5.3.

The specific problem I have is that when the program first loads up, the dynamic UI elements do not load. There does not appear to be any holdup in the code, as all the features of the interface work fine even while the dynamic UI is unloaded. I am able to get the dynamic UI to load by selecting one of the tabs in the navbar, or by hovering over something that I have implemented a tooltip on.

I am unable to provide the exact code but I have recreated a much smaller reproducible example that has all the same problems that my larger version does.

library("shiny")
library("shinydashboard")

header = dashboardHeader(
    title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
    sidebarMenu(
        menuItemOutput("dynamic_sidebar")
    )
)
body = dashboardBody(
    tabBox(
        tabPanel(
            strong("One")
        ),
        tabPanel(
            strong("Two")
        )
    )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){
output$dynamic_sidebar = renderMenu({
        sidebarMenu(
            menuItem(
                "Slider or numeric problem",
                radioButtons("slider_or_numeric",
                   label = "Slider or Numeric Input",
                   choices = c("Slider", "Numeric"),
                   selected = "Slider",
                   inline = TRUE
                ),
                uiOutput("input")
            )
        )
    })
    output$input = renderUI({
        if (input$slider_or_numeric == "Slider"){
            sliderInput("slider",
                label = "slider",
                min = 0, max = 1,
                value = 0
            )
        } else {
            numericInput("numeric",
                label = "numeric",
                min = 0, max = 1,
                value = 0
            )
        }
    })
})

shinyApp(ui, server)

To verify the problem, after loading it up just open the menu item and you'll see the radio buttons but nothing else. Switch the tab on the navbar from one to two, and the input should appear in the menu (must be done while the menu is open).

I'm really just grasping at straws here, I have been troubleshooting this for hours and I think it's just an incompatibility with these features. I'm really hoping someone can prove me wrong and show me that I'm just doing it wrong. I've already found alternatives for my main program but they don't have the same aesthetic with what I'm trying to accomplish here.

Thanks for any and all help!

Body:
I think I found the issue, it was tricky, and took me awhile to find it. Although it is a small change, I will post the whole thing.

I think this is what you want:

library("shiny")
library("shinydashboard")

header = dashboardHeader(
  title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
  sidebarMenu(
    menuItemOutput("dynamic_sidebar")
  )
)
body = dashboardBody(
  tabBox(
    tabPanel(
      strong("One")
    ),
    tabPanel(
      strong("Two")
    )
  )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){
  output$dynamic_sidebar = renderMenu({
    sidebarMenu(
      menuItem(
        "Slider or numeric problem",
        radioButtons("slider_or_numeric",
                     label = "Slider or Numeric Input",
                     choices = c("Slider", "Numeric"),
                     selected = "Slider",
                     inline = TRUE
        )
      ),
      uiOutput("input")  # no longer in menuItem call
    )
  })
  output$input = renderUI({
    if (input$slider_or_numeric == "Slider"){
      sliderInput("slider",
                  label = "slider",
                  min = 0, max = 1,
                  value = 0
      )
    } else {
      numericInput("numeric",
                   label = "numeric",
                   min = 0, max = 1,
                   value = 0
      )
    }
  })
})
shinyApp(ui, server)

I think the problem was that uiOutput("input") somehow slipped into the menuItem call. This is a hazard with Shiny, and Shiny editors obviously need more support for showing this kind of scope.

Frankly I am a bit puzzled as to why it ever showed up when you played around with it. But enough...

While I am not completely sure I understand how you want this to work (it is just a toy example obviously), this is how it looks now at startup:

And here after the menu expansion and changing the input type via the newly exposed radio button control.


问:
Boostrap table button don't work after search
I have a problem with the component "Bootstrap table". I have a column that show a simple popover when clicked, but if I change page or search a result, if I re-clicked it, doesn't show anymore the popover (this problem happened not only with popover , but also with other js method). Even if I used DataTable, this problem doesn't happen. How can I fix it? That's my code:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

      Codice
      Nome
      Server
      Database
      Versione
      Attivo
      Licenza

      17894
      Ekipe
      oasis.amcweb.it
      ET_017894
      5.16.20
      SI
      <button type="button" class="btn btn-info" data-toggle="popover" title="TEST 2" data-content="Some content inside the popover" data-placement="top">Visualizza</button>

      14785
      Ekipe
      web.amclab.it
      ET_017894
      5.16.20
      SI
       <button type="button" class="btn btn-info" data-toggle="popover" title="TEST 1" data-content="Some content inside the popover" data-placement="top">Visualizza</button>

```

答:
You should run execute $('[data-toggle="popover"]').popover(); everytime after you trigger the script modifying the table.

Update 1:

This would be easier, replace the existing script with this:

```<code>$('table').on('post-body.bs.table', function () { $('[data-toggle="popover"]').popover(); });
</code>```

Don't forget to replace $('table') with your specific table you intend for it to take effect.

Body:
You should run execute $('[data-toggle="popover"]').popover(); everytime after you trigger the script modifying the table.

Update 1:

This would be easier, replace the existing script with this:

$('table').on('post-body.bs.table', function () { $('[data-toggle="popover"]').popover(); });

Don't forget to replace $('table') with your specific table you intend for it to take effect.


问:
react link vs a tag and arrow function
I just started on react router.

I have two questions. What is the difference between using <Link to="/page"> and href="page">? Both make the exact same get request to /page but I get an error when I use href="page"> but it works when I use <Link to="/page"> when I am nesting routes. I don't understand, how there could be any difference, when I know for fact that both render to exact same url?

Second is the weird arrow function in react router v4 documentation

```<code>const About = () => (
  <div>
    <h2>About</h2>
  </div>
)
</code>```

I know () => {} these are new in ES6 but I cannot find anything on normal brackets instead of parentheses. What are they?

Edit

My index.js class (I have all the imports)

```<code>render((
    <Router>
        <div>
            <Route component={App}/>
        </div>
    </Router>
), document.getElementById('root')
);
</code>```

My App.js class

```<code>class App extends Component {
render() {
    return (
        <div className="container">
            <header>
                <span className="icn-logo"><i className="material-icons">code</i></span>
                <ul className="main-nav">
                    <li><Link to="/">Home</Link></li>
                    <li><Link to="/about">About</Link></li>
                    <li><Link to="/teachers">Teachers</Link></li>
                    <li><Link to="/courses">Courses</Link></li>
                </ul>
            </header>
            <Route exact path="/" component={Home}/>
            <Route path="/about" component={About}/>
            <Route path="/teachers" component={Teachers}/>
            <Route path="/courses" component={Course}/>
        </div>
    );
}
}

export default App;
</code>```

The error I'm getting.
Cannot GET /about on the browser when I try to move to localhost:8080/about. However, when I click the about button, it goes to exactly the same url /about and renders perfectly

答:
The  component allows you to do more than the normal  link element. For instance, because it's a React component you have the benefits of having a state and what not (if you want that). You can see more documentation on  here. Without the error I'm not sure what happens, but I suspect the routing library wants you to use the  component, over a normal html element.

With regards to () => {} this is a construct which is called an anonymous function, or a lambda expression. It's basically the same as saving a function in a variable: var x = function(){ return (
...) }; if you have anything in the first parenthesis, it's a parameter which you have access to: const x = (y) => return y*2; The reason it's done in React is to expose the function scope to the component it lies in.

ContentLicense: CC BY-SA 4.0

Title: react link vs a tag and arrow function

Body:
I just started on react router.

I have two questions. What is the difference between using <Link to="/page"> and ? Both make the exact same get request to /page but I get an error when I use  but it works when I use <Link to="/page"> when I am nesting routes. I don't understand, how there could be any difference, when I know for fact that both render to exact same url?

Second is the weird arrow function in react router v4 documentation

const About = () => (

About

)

I know () => {} these are new in ES6 but I cannot find anything on normal brackets instead of parentheses. What are they?

Edit

My index.js class (I have all the imports)

render((
    <Router>

            <Route component={App}/>

    </Router>
), document.getElementById('root')
);

My App.js class

class App extends Component {
render() {
    return (

                code

<Link to="/">Home</Link>

<Link to="/about">About</Link>

<Link to="/teachers">Teachers</Link>

<Link to="/courses">Courses</Link>

            <Route exact path="/" component={Home}/>
            <Route path="/about" component={About}/>
            <Route path="/teachers" component={Teachers}/>
            <Route path="/courses" component={Course}/>

    );
}
}

export default App;

The error I'm getting.
Cannot GET /about on the browser when I try to move to localhost:8080/about. However, when I click the about button, it goes to exactly the same url /about and renders perfectly

Body:
The  component allows you to do more than the normal  link element. For instance, because it's a React component you have the benefits of having a state and what not (if you want that). You can see more documentation on  here. Without the error I'm not sure what happens, but I suspect the routing library wants you to use the  component, over a normal html element.

With regards to () => {} this is a construct which is called an anonymous function, or a lambda expression. It's basically the same as saving a function in a variable: var x = function(){ return (<div>...) }; if you have anything in the first parenthesis, it's a parameter which you have access to: const x = (y) => return y*2; The reason it's done in React is to expose the function scope to the component it lies in.


问:
Lotus Notes: NotesSQL Restrictions
Does anybody know the restrictions of the NotesSQL API (Domino ODBC API)?
E.g. can I read mail attachments with this API?
Or should the domino.dll the prefered way to access NSF files (in the .NET World)?

答:
The NotesSQL API uses views to create its pseudo-tables. As an attachment is stored as an RTF field and RTF-fields can't be displayed in views, I think this is not possible.

I'm not completely up-to-date, my last experience with NotesSQL was with 6.5. But back then it was not very stable when querying large datasets so we dropped it quite fast for production use.

ContentLicense: CC BY-SA 2.5

Title: Lotus Notes: NotesSQL Restrictions


问:
How do I make flex box work in safari?
How do I make flex boxes work in Safari?
I have a responsive nav that uses a CSS flex box to be responsive
and for some reason it won't work in Safari.

Here is my code:

#menu {
 clear: both;
 height: auto;
 font-family: Arial, Tahoma, Verdana;
 font-size: 1em;
 /*padding:10px;*/
 margin: 5px;
 display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
 display: -moz-box;    /* OLD - Firefox 19- (buggy but mostly works) */
 display: -ms-flexbox;  /* TWEENER - IE 10 */
 display: -webkit-flex; /* NEW - Chrome */
 display: flex;         /* NEW, Spec - Opera 12.1, Firefox 20+ */
 justify-content: center;
 -webkit-box-align: center;
 -webkit-flex-align: center;
 -ms-flex-align: center;
 -webkit-align-items: center;
 align-items: center;fffff
 font-style: normal;
 font-weight: 400px;
}
#menu a:link {
 display: inline-block;
 width: 100px;
 height: 50px;
 padding: 5px;
 background-color: yellow;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-weight: bold;
 color: #1689D6;
 font-size: 85%;
}
#menu a:visited {
 display: inline-block;
 width: 100px;
 height: 50px;
 padding: 5px;
 background-color: yellow;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-weight: bold;
 color: #1689D6;
 font-size: 85%;
}
#menu a:hover {
 display: inline-block;
 color: #fff;
 width: 100px;
 height: 50px;
 padding: 5px;
 background-color: red;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-weight: bold;
 font-size: 85%;
}
#menu a:active {
 display: inline-block;
 color: #fff;
 width: 100px;
 height: 50px;
 padding-top: 5px;
 padding-right: 5px;
 padding-left: 5px;
 padding-bottom: 5px;
 background-color: red;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-style: normal;
 font-weight: bold;
 font-size: 85%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav id="menu">
  Philadelphia
  <!--Vacation Packages-->
  United States of America
  Philippines
  Long Destinations Names
  Some Destination
  Australia
</nav></code>```

http://jsfiddle.net/cyberjo50/n55xh/3/

Is there a prefix I'm missing to make it work in Safari?

答:
Demo -> https://jsfiddle.net/xdsuozxf/

Safari still requires the -webkit- prefix to use flexbox.

.row{
    box-sizing: border-box;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex: 0 1 auto;
    -ms-flex: 0 1 auto;
    flex: 0 1 auto;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -webkit-flex-direction: row;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}

.col {
    background:red;
    border:1px solid black;

    -webkit-flex: 1 ;-ms-flex: 1 ;flex: 1 ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">

    <div class="content">
        <div class="row">
            <div class="col medium">
                <div class="box">
                    work on safari browser
                </div>
            </div>
            <div class="col medium">
                <div class="box">
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                </div>
            </div>
            <div class="col medium">
                <div class="box">
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser  work on safari browser
                    work on safari browser
                </div>
            </div>
        </div>
    </div>
</div></code>```

Title: How do I make flex box work in safari?

Body:
How do I make flex boxes work in Safari?
I have a responsive nav that uses a CSS flex box to be responsive
and for some reason it won't work in Safari.

Here is my code:

#menu {
 clear: both;
 height: auto;
 font-family: Arial, Tahoma, Verdana;
 font-size: 1em;
 /*padding:10px;*/
 margin: 5px;
 display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
 display: -moz-box;    /* OLD - Firefox 19- (buggy but mostly works) */
 display: -ms-flexbox;  /* TWEENER - IE 10 */
 display: -webkit-flex; /* NEW - Chrome */
 display: flex;         /* NEW, Spec - Opera 12.1, Firefox 20+ */
 justify-content: center;
 -webkit-box-align: center;
 -webkit-flex-align: center;
 -ms-flex-align: center;
 -webkit-align-items: center;
 align-items: center;fffff
 font-style: normal;
 font-weight: 400px;
}
#menu a:link {
 display: inline-block;
 width: 100px;
 height: 50px;
 padding: 5px;
 background-color: yellow;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-weight: bold;
 color: #1689D6;
 font-size: 85%;
}
#menu a:visited {
 display: inline-block;
 width: 100px;
 height: 50px;
 padding: 5px;
 background-color: yellow;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-weight: bold;
 color: #1689D6;
 font-size: 85%;
}
#menu a:hover {
 display: inline-block;
 color: #fff;
 width: 100px;
 height: 50px;
 padding: 5px;
 background-color: red;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-weight: bold;
 font-size: 85%;
}
#menu a:active {
 display: inline-block;
 color: #fff;
 width: 100px;
 height: 50px;
 padding-top: 5px;
 padding-right: 5px;
 padding-left: 5px;
 padding-bottom: 5px;
 background-color: red;
 /*border: 1px solid #cccccc;*/
 margin: 5px;
 display: flex;
 flex-grow: 1;
 align-items: center;
 text-align: center;
 justify-content: center;
 font-style: normal;
 font-weight: bold;
 font-size: 85%;
}

  Philadelphia

  United States of America
  Philippines
  Long Destinations Names
  Some Destination
  Australia

http://jsfiddle.net/cyberjo50/n55xh/3/

Is there a prefix I'm missing to make it work in Safari?

Body:
Demo -> https://jsfiddle.net/xdsuozxf/

Safari still requires the -webkit- prefix to use flexbox.

.row{
    box-sizing: border-box;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex: 0 1 auto;
    -ms-flex: 0 1 auto;
    flex: 0 1 auto;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -webkit-flex-direction: row;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}

.col {
    background:red;
    border:1px solid black;

    -webkit-flex: 1 ;-ms-flex: 1 ;flex: 1 ;
}

<div class="wrapper">

    <div class="content">
        <div class="row">
            <div class="col medium">
                <div class="box">
                    work on safari browser
                </div>
            </div>
            <div class="col medium">
                <div class="box">
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                </div>
            </div>
            <div class="col medium">
                <div class="box">
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser
                    work on safari browser  work on safari browser
                    work on safari browser
                </div>
            </div>
        </div>
    </div>
</div>


问:
Is there any way to convert coordinates to location object in Sikulix?
I am trying to implement a method to find the center of an image and click at that location. On a normal day I would have tried the getCenter() method of SikuliX. But, this time I need this method to be abstract and work for a wide number of images. All the images are exactly same in appearance but are of different dimensions (length & width). So I am trying to find the center by evaluating the coordinates of the corner and then finding out the center using simple coordinate geometry. Problem: I cannot click at a coordinate location. I guess SikuliX requires location object instead of coordinates. Is there any way I can convert coordinates into a location object.

Thank You

答:
If I understand your question correctly and what you have is just integer/double/etc.. coordinates of a location you want to click, you can simply do something like this:</p>

```<code>@Test
public void locationByInteger() throws FindFailed {

    Screen s = new Screen(0);

        int x = 100;
        int y = 100;

        s.click(new Location(x, y));

    }
</code>```

Body:
If I understand your question correctly and what you have is just integer/double/etc.. coordinates of a location you want to click, you can simply do something like this:

@Test
public void locationByInteger() throws FindFailed {

    Screen s = new Screen(0);

        int x = 100;
        int y = 100;

        s.click(new Location(x, y));

    }


问:
json array parsing in javascript
I have a json array printed out from php file.
And then tried to get elements by parsing it. But I am confused where is wrong.</p>

```<code>    <?php

    $json = array("a1", "a2", "a3", "a4", "a5".......);
    echo json_encode($json);

    ?>

    <script>
    $.ajax({
    /*other codes*/

    success : function(data){

            var json = parseJSON(data);
            for(var i = 0 ; i < json.length; i++){
               alert(json[i]);
            }

            }
</code>```

答:
If data is a JSON String then you can use JSON.parse() method to convert it into JSON Object and then we can parse it using Array map() method or for...in loop.

```<code>var json = JSON.parse(data);
var result = json.map(function(item) {
    return item;
});
</code>```

Title: json array parsing in javascript

Body:
I have a json array printed out from php file.
And then tried to get elements by parsing it. But I am confused where is wrong.

    <?php

    $json = array("a1", "a2", "a3", "a4", "a5".......);
    echo json_encode($json);

    ?>

Body:
If data is a JSON String then you can use JSON.parse() method to convert it into JSON Object and then we can parse it using Array map() method or for...in loop.

var json = JSON.parse(data);
var result = json.map(function(item) {
    return item;
});


问:
Java - Flatten nested map using Stream
I have been messing around with Java 8 Stream API and ran into something I could only do through traditional for-loops.

Given a nested map of

```<code>{
    1999: {
             3: [23, 24, 25],
             4: [1, 2, 3]
          },
    2001: {
             11: [12, 13, 14],
             12: [25, 26, 27]

          }
}
</code>```

How can I transform this into

```<code>['23,3,1999', '24,3,1999', '25,3,1999', '1,4,1999', '2,4,1999', '3,4,1999', '12,11,2001', '13,11,2001', '14,11,2001', '25,12,2001', '26,12,2001', '27,12,2001']
</code>```

Basically I want to replicate:

```<code>    Map<Integer, Map<Integer, List<Integer>>> dates...
    List<String> flattened = new ArrayList<>();
    for (Integer key1 : map.keySet()) {
        for (Integer key2 : map.get(key1).keySet()) {
            for (Integer value : map.get(key1).get(key2)) {
                flattened.add(value + "," + key2 + "," + key1);
            }
        }
    }
</code>```

答:
Try this for example:

```<code>public static void main(String[] args) {
    Map<Integer, Map<Integer, List<Integer>>> dates =
        new HashMap<Integer, Map<Integer, List<Integer>>>() {{
            put(1999, new HashMap<Integer, List<Integer>>() {{
                put(3, Arrays.asList(23, 24, 25));
                put(4, Arrays.asList(1, 2, 3));
            }});
            put(2001, new HashMap<Integer, List<Integer>>() {{
                    put(11, Arrays.asList(12, 13, 14));
                    put(12, Arrays.asList(25, 26, 27));
            }});
        }};

    dates.entrySet().stream().flatMap(year ->
        year.getValue().entrySet().stream().flatMap(month ->
            month.getValue().stream()
                .map(day -> day + "," + month.getKey() + "," + year.getKey())))
        .forEach(System.out::println);
}
</code>```

and if you need them sorted by year then month then day try this:

```<code>    dates.entrySet().stream().flatMap(year ->
        year.getValue().entrySet().stream().flatMap(month ->
            month.getValue().stream()
                .map(day -> Arrays.asList(year.getKey(), month.getKey(), day))))
        .sorted(Comparator.comparing(l -> l.get(0)*10000 + l.get(1)*100 + l.get(2)))
        .forEach(System.out::println);
</code>```

Title: Java - Flatten nested map using Stream

Body:
I have been messing around with Java 8 Stream API and ran into something I could only do through traditional for-loops.

Given a nested map of

{
    1999: {
             3: [23, 24, 25],
             4: [1, 2, 3]
          },
    2001: {
             11: [12, 13, 14],
             12: [25, 26, 27]

          }
}

How can I transform this into

['23,3,1999', '24,3,1999', '25,3,1999', '1,4,1999', '2,4,1999', '3,4,1999', '12,11,2001', '13,11,2001', '14,11,2001', '25,12,2001', '26,12,2001', '27,12,2001']

Basically I want to replicate:

    Map<Integer, Map<Integer, List<Integer>>> dates...
    List<String> flattened = new ArrayList<>();
    for (Integer key1 : map.keySet()) {
        for (Integer key2 : map.get(key1).keySet()) {
            for (Integer value : map.get(key1).get(key2)) {
                flattened.add(value + "," + key2 + "," + key1);
            }
        }
    }

Body:
Try this for example:

public static void main(String[] args) {
    Map<Integer, Map<Integer, List<Integer>>> dates =
        new HashMap<Integer, Map<Integer, List<Integer>>>() {{
            put(1999, new HashMap<Integer, List<Integer>>() {{
                put(3, Arrays.asList(23, 24, 25));
                put(4, Arrays.asList(1, 2, 3));
            }});
            put(2001, new HashMap<Integer, List<Integer>>() {{
                    put(11, Arrays.asList(12, 13, 14));
                    put(12, Arrays.asList(25, 26, 27));
            }});
        }};

    dates.entrySet().stream().flatMap(year ->
        year.getValue().entrySet().stream().flatMap(month ->
            month.getValue().stream()
                .map(day -> day + "," + month.getKey() + "," + year.getKey())))
        .forEach(System.out::println);
}

and if you need them sorted by year then month then day try this:

    dates.entrySet().stream().flatMap(year ->
        year.getValue().entrySet().stream().flatMap(month ->
            month.getValue().stream()
                .map(day -> Arrays.asList(year.getKey(), month.getKey(), day))))
        .sorted(Comparator.comparing(l -> l.get(0)*10000 + l.get(1)*100 + l.get(2)))
        .forEach(System.out::println);


问:
IllegalArgumentException: GoogleApiClient parameter is required
First of all sorry for asking this silly question. As i am new to android so i am trying to make an app in which first there will dialog box open for asking the permission to turn on the GPS like google maps or ola do. Then after that i wanted to get user latitude and longitude but unfortunately i tried and search so many links but i didn't get right solution. so can anyone help me out.

My Code is :

```<code>public class GpsPlaceSearch extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener
{
    Activity context;
    GoogleApiClient googleApiClient, getGoogleApiClient;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;
    LocationRequest locationRequest1;

    Location location;
    private double currentLatitude;
    private double currentLongitude;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 111;

    public GpsPlaceSearch(){

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps_place_search);
        getGoogleApiClient = new GoogleApiClient.Builder(this)
                class will handle connection stuff
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)

                .addApi(LocationServices.API)
                .build();

        locationRequest1=locationRequests();
    }

    public GpsPlaceSearch(Activity context){
        this.context=context;
        googleApiClient=getInstance();
        if (googleApiClient!=null){
            settingsrequest();

            googleApiClient.connect();
        }
    }

    public LocationRequest locationRequests(){
        LocationRequest locationRequest=LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        return locationRequest;
    }

    public GoogleApiClient getInstance(){
        GoogleApiClient mGoogleApiClient=new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        return mGoogleApiClient;
    }

    public void settingsrequest(){
        Log.e("settingsrequest","Comes");

        locationRequest1=locationRequests();
        LocationSettingsRequest.Builder builder=new LocationSettingsRequest.Builder().addLocationRequest(locationRequest1);

        builder.setAlwaysShow(true);
        final PendingResult<LocationSettingsResult> result= LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                Status status=result.getStatus();
                LocationSettingsStates states=result.getLocationSettingsStates();
                switch (status.getStatusCode()){
                    case LocationSettingsStatusCodes.SUCCESS:

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try{
                            status.startResolutionForResult(context,REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        break;
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onConnected(Bundle bundle) {
        location=LocationServices.FusedLocationApi.getLastLocation(getGoogleApiClient);
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},108);
            LocationServices.FusedLocationApi.requestLocationUpdates(getGoogleApiClient,locationRequest1,this);

        }
        else {

            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " AND " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        if (connectionResult.hasResolution()){
            try {
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
        else {
            Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        Activity mActivity=this;
        GpsPlaceSearch gpsPlaceSearch=new GpsPlaceSearch(mActivity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Now lets connect to the API
        getGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (getGoogleApiClient.isConnected()){
            LocationServices.FusedLocationApi.removeLocationUpdates(getGoogleApiClient,this);
            getGoogleApiClient.disconnect();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LocationSettingsStates states=LocationSettingsStates.fromIntent(data);
        switch (requestCode){
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode){
                    case Activity.RESULT_OK:
                        break;
                    case Activity.RESULT_CANCELED:
                        startActivity(new Intent(getApplicationContext(),Login_page.class));
                        break;
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
        Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_FINE_LOCATION:
                if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){

                }
                else {

                }
                return;
        }
    }
}
</code>```

Logcat :

FATAL EXCEPTION: main
                                                                        Process: com.bigfoot.trialapp, PID: 17660
                                                                        java.lang.IllegalArgumentException: GoogleApiClient parameter is
  required.
                                                                            at com.google.android.gms.common.internal.zzaa.zzb(Unknown Source)
                                                                            at com.google.android.gms.location.LocationServices.zzj(Unknown
  Source)
                                                                            at
  com.google.android.gms.location.internal.zzd.getLastLocation(Unknown
  Source)
                                                                            at
  com.bigfoot.trialapp.GpsPlaceSearch.onConnected(GpsPlaceSearch.java:128)
                                                                            at com.google.android.gms.common.internal.zzk.zzp(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrd.zzn(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrb.zzass(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrb.onConnected(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrf.onConnected(Unknown Source)
                                                                            at com.google.android.gms.internal.zzqr.onConnected(Unknown Source)
                                                                            at com.google.android.gms.common.internal.zzj$1.onConnected(Unknown
  Source)
                                                                            at com.google.android.gms.common.internal.zze$zzj.zzavj(Unknown
  Source)
                                                                            at com.google.android.gms.common.internal.zze$zza.zzc(Unknown Source)
                                                                            at com.google.android.gms.common.internal.zze$zza.zzv(Unknown Source)
                                                                            at com.google.android.gms.common.internal.zze$zze.zzavl(Unknown
  Source)
                                                                            at
  com.google.android.gms.common.internal.zze$zzd.handleMessage(Unknown
  Source)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

答:
You should remove below line from onConnected

```<code> location=LocationServices.FusedLocationApi.getLastLocation(getGoogleApiClient);
</code>```

and should only call  requestLocationUpdates method in onConnected

```<code>@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onConnected(Bundle bundle) {

    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},108);
        LocationServices.FusedLocationApi.requestLocationUpdates(getGoogleApiClient,locationRequest1,this);

    }
}else{
    //custom dialog for "please enable location permission to access device location"
}
</code>```

Body:
First of all sorry for asking this silly question. As i am new to android so i am trying to make an app in which first there will dialog box open for asking the permission to turn on the GPS like google maps or ola do. Then after that i wanted to get user latitude and longitude but unfortunately i tried and search so many links but i didn't get right solution. so can anyone help me out.

My Code is :

public class GpsPlaceSearch extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener
{
    Activity context;
    GoogleApiClient googleApiClient, getGoogleApiClient;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;
    LocationRequest locationRequest1;

    Location location;
    private double currentLatitude;
    private double currentLongitude;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 111;

    public GpsPlaceSearch(){

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps_place_search);
        getGoogleApiClient = new GoogleApiClient.Builder(this)
                class will handle connection stuff
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)

                .addApi(LocationServices.API)
                .build();

        locationRequest1=locationRequests();
    }

    public GpsPlaceSearch(Activity context){
        this.context=context;
        googleApiClient=getInstance();
        if (googleApiClient!=null){
            settingsrequest();

            googleApiClient.connect();
        }
    }

    public LocationRequest locationRequests(){
        LocationRequest locationRequest=LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        return locationRequest;
    }

    public GoogleApiClient getInstance(){
        GoogleApiClient mGoogleApiClient=new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        return mGoogleApiClient;
    }

    public void settingsrequest(){
        Log.e("settingsrequest","Comes");

        locationRequest1=locationRequests();
        LocationSettingsRequest.Builder builder=new LocationSettingsRequest.Builder().addLocationRequest(locationRequest1);

        builder.setAlwaysShow(true);
        final PendingResult<LocationSettingsResult> result= LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                Status status=result.getStatus();
                LocationSettingsStates states=result.getLocationSettingsStates();
                switch (status.getStatusCode()){
                    case LocationSettingsStatusCodes.SUCCESS:

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try{
                            status.startResolutionForResult(context,REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        break;
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onConnected(Bundle bundle) {
        location=LocationServices.FusedLocationApi.getLastLocation(getGoogleApiClient);
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},108);
            LocationServices.FusedLocationApi.requestLocationUpdates(getGoogleApiClient,locationRequest1,this);

        }
        else {

            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " AND " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        if (connectionResult.hasResolution()){
            try {
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
        else {
            Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        Activity mActivity=this;
        GpsPlaceSearch gpsPlaceSearch=new GpsPlaceSearch(mActivity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Now lets connect to the API
        getGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (getGoogleApiClient.isConnected()){
            LocationServices.FusedLocationApi.removeLocationUpdates(getGoogleApiClient,this);
            getGoogleApiClient.disconnect();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LocationSettingsStates states=LocationSettingsStates.fromIntent(data);
        switch (requestCode){
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode){
                    case Activity.RESULT_OK:
                        break;
                    case Activity.RESULT_CANCELED:
                        startActivity(new Intent(getApplicationContext(),Login_page.class));
                        break;
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
        Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_FINE_LOCATION:
                if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){

                }
                else {

                }
                return;
        }
    }
}

Logcat :

FATAL EXCEPTION: main
                                                                        Process: com.bigfoot.trialapp, PID: 17660
                                                                        java.lang.IllegalArgumentException: GoogleApiClient parameter is
  required.
                                                                            at com.google.android.gms.common.internal.zzaa.zzb(Unknown Source)
                                                                            at com.google.android.gms.location.LocationServices.zzj(Unknown
  Source)
                                                                            at
  com.google.android.gms.location.internal.zzd.getLastLocation(Unknown
  Source)
                                                                            at
  com.bigfoot.trialapp.GpsPlaceSearch.onConnected(GpsPlaceSearch.java:128)
                                                                            at com.google.android.gms.common.internal.zzk.zzp(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrd.zzn(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrb.zzass(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrb.onConnected(Unknown Source)
                                                                            at com.google.android.gms.internal.zzrf.onConnected(Unknown Source)
                                                                            at com.google.android.gms.internal.zzqr.onConnected(Unknown Source)
                                                                            at com.google.android.gms.common.internal.zzj$1.onConnected(Unknown
  Source)
                                                                            at com.google.android.gms.common.internal.zze$zzj.zzavj(Unknown
  Source)
                                                                            at com.google.android.gms.common.internal.zze$zza.zzc(Unknown Source)
                                                                            at com.google.android.gms.common.internal.zze$zza.zzv(Unknown Source)
                                                                            at com.google.android.gms.common.internal.zze$zze.zzavl(Unknown
  Source)
                                                                            at
  com.google.android.gms.common.internal.zze$zzd.handleMessage(Unknown
  Source)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

Body:
You should remove below line from onConnected

 location=LocationServices.FusedLocationApi.getLastLocation(getGoogleApiClient);

and should only call  requestLocationUpdates method in onConnected

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onConnected(Bundle bundle) {

    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},108);
        LocationServices.FusedLocationApi.requestLocationUpdates(getGoogleApiClient,locationRequest1,this);

    }
}else{
    //custom dialog for "please enable location permission to access device location"
}


问:
how can I use a literal # in a python variable or string without it commenting out the rest?
Probably simple but I want to send a post with a color hex in it that the target is expecting but I can't set that value in the color key because it comments out everything after it.</p>

答:
You can't use # as part of the name of a Python variable (see identifiers and keywords), but you can put # followed by the color code in a string and send it as part of your payload for POSTing:

```<code>var = '#42'
</code>```

Body:
You can't use # as part of the name of a Python variable (see identifiers and keywords), but you can put # followed by the color code in a string and send it as part of your payload for POSTing:

var = '#42'


问:
Keras lambda function dot product mistmatch
I have the following function:

```<code>def transpose_dot(vects):
    x, y = vects
    # <x,x> + <y,y> - 2<x,y>

    return K.dot(x, K.transpose(y))
</code>```

When try to evaluate it with keras it works

```<code>x = K.variable(np.array(np_x))
y = K.variable(np.array(np_x))
obj = transpose_dot
objective_output = obj((x, y))
print('-----------------')
print (K.eval(objective_output))
</code>```

result with:

```<code>[[ 1.  1.  1.  2.]
 [ 1.  2.  2.  4.]
 [ 1.  2.  2.  4.]
 [ 2.  4.  4.  8.]
</code>```

But, when try to use it as function for Lambda layer it does not work.

```<code>np_x = [[1, 0], [1, 1], [1, 1], [2, 2]]
features = np.array([np_x])
test_input = Input(shape=np.array(np_x).shape)
dot_layer= Lambda(transpose_dot, output_shape=(4,4))([test_input, test_input])
x = Model(inputs=test_input, outputs=dot_layer)
x.predict(features, batch_size=1)
</code>```

Result with

```<code>self.fn() if output_subset is None else\
ValueError: Shape mismatch: x has 2 cols (and 4 rows) but y has 4 rows (and 2 cols)
Apply node that caused the error: Dot22(Reshape{2}.0, Reshape{2}.0)
Toposort index: 11
Inputs types: [TensorType(float32, matrix), TensorType(float32, matrix)]
Inputs shapes: [(4, 2), (4, 2)]
Inputs strides: [(8, 4), (8, 4)]
Inputs values: ['not shown', 'not shown']
Outputs clients: [[Reshape{4}(Dot22.0, MakeVector{dtype='int64'}.0)]]
</code>```

Any idea what I'm missing here?

Edit:
Added output of the error message

答:
With the help from guys at https://github.com/fchollet/keras/ I found my mistake.
The function expect to get (n,m). But when using a Lambda function it expect to get (samples,n,m).</p>

Body:
I have the following function:

def transpose_dot(vects):
    x, y = vects
    # <x,x> + <y,y> - 2<x,y>

    return K.dot(x, K.transpose(y))

When try to evaluate it with keras it works

x = K.variable(np.array(np_x))
y = K.variable(np.array(np_x))
obj = transpose_dot
objective_output = obj((x, y))
print('-----------------')
print (K.eval(objective_output))

result with:

[[ 1.  1.  1.  2.]
 [ 1.  2.  2.  4.]
 [ 1.  2.  2.  4.]
 [ 2.  4.  4.  8.]

But, when try to use it as function for Lambda layer it does not work.

np_x = [[1, 0], [1, 1], [1, 1], [2, 2]]
features = np.array([np_x])
test_input = Input(shape=np.array(np_x).shape)
dot_layer= Lambda(transpose_dot, output_shape=(4,4))([test_input, test_input])
x = Model(inputs=test_input, outputs=dot_layer)
x.predict(features, batch_size=1)

Result with

self.fn() if output_subset is None else\
ValueError: Shape mismatch: x has 2 cols (and 4 rows) but y has 4 rows (and 2 cols)
Apply node that caused the error: Dot22(Reshape{2}.0, Reshape{2}.0)
Toposort index: 11
Inputs types: [TensorType(float32, matrix), TensorType(float32, matrix)]
Inputs shapes: [(4, 2), (4, 2)]
Inputs strides: [(8, 4), (8, 4)]
Inputs values: ['not shown', 'not shown']
Outputs clients: [[Reshape{4}(Dot22.0, MakeVector{dtype='int64'}.0)]]

Any idea what I'm missing here?

Edit:
Added output of the error message


问:
Override onSavedInstanceState: savedInstanceState object is always null
I have two activities (A and B). Activity A calls activity B. Activity B has Back (Up) button like this:

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

Now when this UP button is pressed, onCreate of activity A is again called. In the activity A, there is a classId variable (which I got from an Intent) which I want to retain. For this I have following code in my onCreate of activity A:

```<code>        if (savedInstanceState == null)
        {
            Intent intent = getIntent();
            classId = intent.getIntExtra("CLASS_ID", 0);
        }
        else
        {
            classId = savedInstanceState.getInt("CLASS_ID");
        }
</code>```

I have also overriden the onSavedInstanceState method:

```<code>@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putInt("CLASS_ID", classId);
    super.onSaveInstanceState(savedInstanceState);
}
</code>```

I am following this SO answer:
onCreate being called on Activity A in up navigation

The problem I am facing is that when I come again to activity A by passing back button in activity B, onCreate gets called and I found savedInstanceState to be NULL.

Edit:

Is there any other way to save my classId variable so that when I return again to activity A, I can use that?

Edit 2

If I set launch mode of my activity A to SingleTop in the manifest file, my issue gets resolved. Is it the right approach?

答:
You should not suppose that onSaveInstanceState called each time you go to next activity.See the docs

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

You may further consult with official docs here

Body:
I have two activities (A and B). Activity A calls activity B. Activity B has Back (Up) button like this:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Now when this UP button is pressed, onCreate of activity A is again called. In the activity A, there is a classId variable (which I got from an Intent) which I want to retain. For this I have following code in my onCreate of activity A:

        if (savedInstanceState == null)
        {
            Intent intent = getIntent();
            classId = intent.getIntExtra("CLASS_ID", 0);
        }
        else
        {
            classId = savedInstanceState.getInt("CLASS_ID");
        }

I have also overriden the onSavedInstanceState method:

@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putInt("CLASS_ID", classId);
    super.onSaveInstanceState(savedInstanceState);
}

I am following this SO answer:
onCreate being called on Activity A in up navigation

The problem I am facing is that when I come again to activity A by passing back button in activity B, onCreate gets called and I found savedInstanceState to be NULL.

Edit:

Is there any other way to save my classId variable so that when I return again to activity A, I can use that?

Edit 2

If I set launch mode of my activity A to SingleTop in the manifest file, my issue gets resolved. Is it the right approach?


问:
How to put translation corpus into different files
I want to deal with a one-line translation corpus between Japanese and Chinese like

JST_JC_ENVI-abst-06A0281759-par1-sen1 ||| Ｃ＆Ｄ管理施設の高度化 ||| Ｃ＆Ｄ管理设施的高度化JST_JC_ENVI-abst-06A0281759-par1-sen2 ||| メーンのポートランドはＲｉｖｅｒｓｉｄｅリサイクリング施設（ＲＲＦ）を所有しているが，建設及び解体（Ｃ＆Ｄ）ごみの埋立地に立地している。 ||| 缅因州的波特兰拥有Ｒｉｖｅｒｓｉｄｅ循环使用设施（ＲＲＦ），但其却位置选定于建设及解体（Ｃ＆Ｄ）垃圾的填埋地。JST_JC_ENVI-abst-06A0281759-par1-sen3 ||| この施設はかさばる廃棄物，住民の出す葉やＣ＆Ｄごみを受け入れているが，その最近の作業状況を紹介した。 ||| 该设施接受体积大的废弃物、居民投弃的叶子或Ｃ＆Ｄ垃圾，本文介绍了该设施最近的作业情况。

The Chinese and Japanese are begin with the prefix JST_JC_ENVI-abstXXXXXXXX string and split by ||| .

So my question is how to delete all the same prefix "JST_JC_ENVI-abstXXXXXXXX" strings and output the Chinese into chinese.txt by line ,the Japanese into japanese.txt by line？

Thank you.

答:
First，deal with the lines and split with space.

```<code># -*- coding: utf-8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

infile=open('dev.txt','r')
outfile1 =open('dev-mid.txt','w')
lines = infile.read()
i = lines.split()
for e in i:
    outfile1.write(e+'\n')
</code>```

then，use WORD to delete space and same prefix strings in dev-mid.txt .

At last ,

```<code>    import os

    infile=open('dev-mid.txt','r')
    outfile1 =open('dev-in.txt','w')
    outfile2 =open('dev-out.txt','w')

    i=1

    for line in infile.readlines():
        if i%2==1:
    ##        print(line)
            outfile1.write(line)
            i+=1
        else:
            i+=1
    ##        print(line)
            outfile2.write(line)
    infile.close()
    outfile1.close()
    outfile2.close()
</code>```

Dealing with even and odd rows.
dev-in.txt is Japanese and dev-out.txt is Chinese:-D

Body:
First，deal with the lines and split with space.

# -*- coding: utf-8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

infile=open('dev.txt','r')
outfile1 =open('dev-mid.txt','w')
lines = infile.read()
i = lines.split()
for e in i:
    outfile1.write(e+'\n')

then，use WORD to delete space and same prefix strings in dev-mid.txt .

At last ,

    import os

    infile=open('dev-mid.txt','r')
    outfile1 =open('dev-in.txt','w')
    outfile2 =open('dev-out.txt','w')

    i=1

    for line in infile.readlines():
        if i%2==1:
    ##        print(line)
            outfile1.write(line)
            i+=1
        else:
            i+=1
    ##        print(line)
            outfile2.write(line)
    infile.close()
    outfile1.close()
    outfile2.close()

Dealing with even and odd rows.
dev-in.txt is Japanese and dev-out.txt is Chinese:-D


问:
Start Activity from within ArrayAdapter
I have a custom adapter that extends ArrayAdapter. I want to go to MapActivity when the EMAIL is clicked. If I remove the intent part a toast appears with the correct position of the item clicked. However, if I add the startActivity function, the app crashes (no toast). I removed the irrelevant code such as getting distance and setters.getters. Any help or pointer would be appreciated!

ArrayAdapter code

```<code>import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;

import java.util.ArrayList;
import java.util.List;

public class TrackAdapter extends ArrayAdapter{

    private Context c;
    //ArrayLists to save items

    public TrackAdapter(Context context, int resource)
    {
        super(context, resource);
        this.c = context;
    }

    public void add(/*items to be added*/)
    {
       //add to ArrayLists and super.add()
    }

    static class RowHolder
    {
        TextView EMAIL;
        TextView DISTANCE;
    }

    @Override
    public int getCount()
    {
        return this.email.size();
    }

    @Override
    public Object getItem(int position)
    {
        return this.email.get(position);
    }

    /*other setters and getters*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row;
        row = convertView;
        RowHolder holder;

        final int currentPosition = position;

        if (convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.track_item, parent, false);

            holder = new RowHolder();

            holder.EMAIL = (TextView) row.findViewById(R.id.track_item_text);
            holder.DISTANCE = (TextView) row.findViewById(R.id.track_item_distance);

            holder.EMAIL.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(c, MapActivity.class);
                    c.startActivity(intent);
                }
            });

            row.setTag(holder);
        }
        else
        {
            holder = (RowHolder) row.getTag();
        }

        String EM = (String) getItem(position);
        holder.EMAIL.setText(EM);

        //calculate and display distance

        return row;

    }
}
</code>```

I also tried replacing c with c.getApplicationContext() and v.getContext(), which also doesn't work.

EDIT- I ran the app on an emulator, and it goes to the MapActivity. However, when  ran on an android device connected by USB, the app crashes

EDIT2 - Here is the crash report

```<code>--------- beginning of crash
03-29 03:23:42.036 7768-7768/com.example.*******
E/AndroidRuntime: FATAL EXCEPTION: main

                                                                                android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:672)
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:659)
                                                                                at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
                                                                                at com.example.ankit.findyourfellow.TrackAdapter$1.onClick(TrackAdapter.java:127)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Inside your click listener do something like:

```<code>holder.EMAIL.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(c, MapActivity.class);
                //if you want to send data to called activity uncomment next line
                // intent.putExtra("extra", "value");

                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                c.startActivity(intent);
            }
        });
</code>```

It should work :)

Title: Start Activity from within ArrayAdapter

Body:
I have a custom adapter that extends ArrayAdapter. I want to go to MapActivity when the EMAIL is clicked. If I remove the intent part a toast appears with the correct position of the item clicked. However, if I add the startActivity function, the app crashes (no toast). I removed the irrelevant code such as getting distance and setters.getters. Any help or pointer would be appreciated!

ArrayAdapter code

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;

import java.util.ArrayList;
import java.util.List;

public class TrackAdapter extends ArrayAdapter{

    private Context c;
    //ArrayLists to save items

    public TrackAdapter(Context context, int resource)
    {
        super(context, resource);
        this.c = context;
    }

    public void add(/*items to be added*/)
    {
       //add to ArrayLists and super.add()
    }

    static class RowHolder
    {
        TextView EMAIL;
        TextView DISTANCE;
    }

    @Override
    public int getCount()
    {
        return this.email.size();
    }

    @Override
    public Object getItem(int position)
    {
        return this.email.get(position);
    }

    /*other setters and getters*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row;
        row = convertView;
        RowHolder holder;

        final int currentPosition = position;

        if (convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.track_item, parent, false);

            holder = new RowHolder();

            holder.EMAIL = (TextView) row.findViewById(R.id.track_item_text);
            holder.DISTANCE = (TextView) row.findViewById(R.id.track_item_distance);

            holder.EMAIL.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(c, MapActivity.class);
                    c.startActivity(intent);
                }
            });

            row.setTag(holder);
        }
        else
        {
            holder = (RowHolder) row.getTag();
        }

        String EM = (String) getItem(position);
        holder.EMAIL.setText(EM);

        //calculate and display distance

        return row;

    }
}

I also tried replacing c with c.getApplicationContext() and v.getContext(), which also doesn't work.

EDIT- I ran the app on an emulator, and it goes to the MapActivity. However, when  ran on an android device connected by USB, the app crashes

EDIT2 - Here is the crash report

--------- beginning of crash
03-29 03:23:42.036 7768-7768/com.example.*******
E/AndroidRuntime: FATAL EXCEPTION: main

                                                                                android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:672)
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:659)
                                                                                at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
                                                                                at com.example.ankit.findyourfellow.TrackAdapter$1.onClick(TrackAdapter.java:127)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
Inside your click listener do something like:

holder.EMAIL.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(c, MapActivity.class);
                //if you want to send data to called activity uncomment next line
                // intent.putExtra("extra", "value");

                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                c.startActivity(intent);
            }
        });

It should work :)


问:
Using javax.mail to send to multiple recipients
I've got the following...

```<code>msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
</code>```

Which works fine but when I attempt to add this multiple times (with different variables for to) it only sends to the last statement. I've also attempted sending something like email1@gmail.com :email2@gmail.com as the to variable but this throws back an error.

Does anyone have any suggestions as to how I'd send mail to multiple recipients using JUST one e-mail and not multiple e-mails using javax.mail?

答:
Use Message's subclass - MimeMessage. It implments the setRecipients(Message.RecipientType type, Address[] addresses)  method.

Furthermore, you could choose which specific message you need to use: IMAPMessage, POP3Message, SMTPMessage.

Body:
I've got the following...

msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

Which works fine but when I attempt to add this multiple times (with different variables for to) it only sends to the last statement. I've also attempted sending something like email1@gmail.com :email2@gmail.com as the to variable but this throws back an error.

Does anyone have any suggestions as to how I'd send mail to multiple recipients using JUST one e-mail and not multiple e-mails using javax.mail?


问:
Vuforia Detecting and Tracking Multiple Targets Simultaneously with Cloud
I use vuforia cloud recognition and I will show 2 targets to camera at the same time. I want to see two object  at the same time but It only can detect one target and show one object. Is it possible to do that with cloud recognition?

I add exapmle picture. I want to see the same time 2 cube together.
Picture

答:
Yes this is possible. The Vuforia SDK can track up to five Object Targets simultaneously. This feature can be enabled by providing hints to the Vuforia SDK.

For more details, visit this link How To Detect and Track Multiple Targets Simultaneously