问:
Using variable 'i' outside of its function
Okay, I was playing around javascript.  I wanted to create a webpage with a "change background" button that cycled between different colors.  So I wrote it like this (script tag starts out of view)

```<code> var bgcolors = ["pink", "beige", "wheat", "white", "brown"];

        var i = 0;

        function cyclebg(){

            document.body.style.backgroundColor = bgcolors[i];

            i++;

            if (i > (bgcolors.length - 1))
            {
                i = 0;
            }

        }

        //other ideas:
        //-say color next to button
    </script>
    <br>
    <br>
    <button type="button"  style="background-color:red; border-color: red;" OnClick="cyclebg()">Change Background Color</button>
</code>```

That worked just fine.  Then I decided to make an edition, and have the name of the color displayed right next to the button.  So I added...

```<code><script>document.write(bgcolors[i]);

    </script>
</code>```

However, "pink" is always written.  It seems like this "document.write" script is only capable of reading what "i" is outside the function.  Why is this?  Aren't all variables global in javaSCRIPT?  How can I get it to read what "i" is inside the function, so it displays the name of the color being used in the background?

答:
It seems like this "document.write" script is only capable of reading
  what "i" is outside the function. Why is this?

When document.wite is being executed the value of i is 0. As per your code it appears that you are not writing/executing document.write(bgcolors[i]); code each time cyclebg() is called.

Aren't all variables global in javaSCRIPT?

A variable declared outside a function, becomes GLOBAL

How can I get it to read what "i" is inside the function, so it
  displays the name of the color being used in the background?

See @Jach M's answer. Write code within your cyclebg() function to do it.

Body:
Okay, I was playing around javascript.  I wanted to create a webpage with a "change background" button that cycled between different colors.  So I wrote it like this (script tag starts out of view)

 var bgcolors = ["pink", "beige", "wheat", "white", "brown"];

        var i = 0;

        function cyclebg(){

            document.body.style.backgroundColor = bgcolors[i];

            i++;

            if (i > (bgcolors.length - 1))
            {
                i = 0;
            }

        }

        //other ideas:
        //-say color next to button
    </script>

    <button type="button"  style="background-color:red; border-color: red;" OnClick="cyclebg()">Change Background Color</button>

That worked just fine.  Then I decided to make an edition, and have the name of the color displayed right next to the button.  So I added...

However, "pink" is always written.  It seems like this "document.write" script is only capable of reading what "i" is outside the function.  Why is this?  Aren't all variables global in javaSCRIPT?  How can I get it to read what "i" is inside the function, so it displays the name of the color being used in the background?


来源: stackexchange

问:
How to separate array processing into goroutines?
I have a slice of 30'000 strings. How do I separate processing this slice into, say, 10 goroutines that would take 3000 strings from the slice, extract some data from them and push into a new slice?

So, in the end, I will have 10 slices with 3000 processed results in each. What's the pattern to handle this problem?

I have had a look at this article, but not sure which of these patterns applies to my case.

答:
I agree with @JimB in that why limit the go routines.  However since that's your inquiry I'd maybe so something like this.. If you really want to have each gorountine do 3000 items, then it might be easier to create a 2d slice. [[3000 items],[3000 items],..] then have 1 go routine process per index in that 2d array. Otherwise below just limits the gorountines to 10.
METHOD 1
    package main

```<code>import (
    "crypto/rand"
    "fmt"
    "log"
    "sync"
    "time"
)

var s []string

// genetate some mock data
func init() {
    s = make([]string, 30000)
    n := 5
    for i := 0; i < 30000; i++ {
        b := make([]byte, n)
        if _, err := rand.Read(b); err != nil {
            panic(err)
        }
        s[i] = fmt.Sprintf("%X", b)
    }
}

func main() {
    // set the number of workers
    ch := make(chan string)
    var mut sync.Mutex
    counter := 0

    // limit the number of gorountines to 10
    for w := 0; w < 10; w++ {
        go func(ch chan string, mut *sync.Mutex) {
            for {
                // get and update counter using mux to stop race condtions
                mut.Lock()
                i := counter
                counter++
                mut.Unlock()
                // break the loop
                if counter > len(s) {
                    return
                }
                // get string
                myString := s[i]
                // to some work then pass to channel
                ch <- myString

            }
        }(ch, &mut)
    }
    // adding time.  If you play wiht the number of gorountines youll see how changing the number above can efficiency
    t := time.Now()
    for i := 0; i < len(s); i++ {
        result := <-ch
        log.Println(time.Since(t), result, i)
    }
}
</code>```

METHOD2 the init function is creating a 2d array chunked out into 10 arrays each containing 3000 elements.. if you parse your data that way the logic below that needs very little modification to work

```<code>package main

import (
    "crypto/rand"
    "fmt"
    "log"
    "sync"
)

var chunkedSlice [10][3000]string

// genetate some mock data
// 2d array, each chunk has 3000 items in it
// there are 10 chunks, 1 go rountine per chunk
func init() {
    n := 5
    for i := 0; i < 10; i++ {
        for j := 0; j < 3000; j++ {
            b := make([]byte, n)
            if _, err := rand.Read(b); err != nil {
                panic(err)
            }
            chunkedSlice[i][j] = fmt.Sprintf("%X", b)
        }
    }
}

func main() {
    // channel to send parsed data to

    ch := make(chan string)
    var wg sync.WaitGroup

    // 10 chunks
    for _, chunk := range chunkedSlice {
        wg.Add(1)
        // if defining the 2d array e.g [10][3000]string, you need to pass it as a pointer to avoid stack error
        go func(ch chan string, wg *sync.WaitGroup, chunk *[3000]string) {
            defer wg.Done()
            for i := 0; i < len(chunk); i++ {
                str := chunk[i]
                // fmt.Println(str)
                // parse the data (emulating)
                parsedData := str
                // send parsed data to the channel
                ch <- parsedData
            }
        }(ch, &wg, &chunk)
    }
    // wait for all the routines to finish and close the channel
    go func() {
        wg.Wait()
        close(ch)
    }()

    var counter int // adding to check that the right number of items was parsed
    // get the data from the channel
    for res := range ch {
        log.Println(res, counter)
        counter++
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I agree with @JimB in that why limit the go routines.  However since that's your inquiry I'd maybe so something like this.. If you really want to have each gorountine do 3000 items, then it might be easier to create a 2d slice. [[3000 items],[3000 items],..] then have 1 go routine process per index in that 2d array. Otherwise below just limits the gorountines to 10.
METHOD 1
    package main

import (
    "crypto/rand"
    "fmt"
    "log"
    "sync"
    "time"
)

var s []string

// genetate some mock data
func init() {
    s = make([]string, 30000)
    n := 5
    for i := 0; i < 30000; i++ {
        b := make([]byte, n)
        if _, err := rand.Read(b); err != nil {
            panic(err)
        }
        s[i] = fmt.Sprintf("%X", b)
    }
}

func main() {
    // set the number of workers
    ch := make(chan string)
    var mut sync.Mutex
    counter := 0

    // limit the number of gorountines to 10
    for w := 0; w < 10; w++ {
        go func(ch chan string, mut *sync.Mutex) {
            for {
                // get and update counter using mux to stop race condtions
                mut.Lock()
                i := counter
                counter++
                mut.Unlock()
                // break the loop
                if counter > len(s) {
                    return
                }
                // get string
                myString := s[i]
                // to some work then pass to channel
                ch <- myString

            }
        }(ch, &mut)
    }
    // adding time.  If you play wiht the number of gorountines youll see how changing the number above can efficiency
    t := time.Now()
    for i := 0; i < len(s); i++ {
        result := <-ch
        log.Println(time.Since(t), result, i)
    }
}

METHOD2 the init function is creating a 2d array chunked out into 10 arrays each containing 3000 elements.. if you parse your data that way the logic below that needs very little modification to work

package main

import (
    "crypto/rand"
    "fmt"
    "log"
    "sync"
)

var chunkedSlice [10][3000]string

// genetate some mock data
// 2d array, each chunk has 3000 items in it
// there are 10 chunks, 1 go rountine per chunk
func init() {
    n := 5
    for i := 0; i < 10; i++ {
        for j := 0; j < 3000; j++ {
            b := make([]byte, n)
            if _, err := rand.Read(b); err != nil {
                panic(err)
            }
            chunkedSlice[i][j] = fmt.Sprintf("%X", b)
        }
    }
}

func main() {
    // channel to send parsed data to

    ch := make(chan string)
    var wg sync.WaitGroup

    // 10 chunks
    for _, chunk := range chunkedSlice {
        wg.Add(1)
        // if defining the 2d array e.g [10][3000]string, you need to pass it as a pointer to avoid stack error
        go func(ch chan string, wg *sync.WaitGroup, chunk *[3000]string) {
            defer wg.Done()
            for i := 0; i < len(chunk); i++ {
                str := chunk[i]
                // fmt.Println(str)
                // parse the data (emulating)
                parsedData := str
                // send parsed data to the channel
                ch <- parsedData
            }
        }(ch, &wg, &chunk)
    }
    // wait for all the routines to finish and close the channel
    go func() {
        wg.Wait()
        close(ch)
    }()

    var counter int // adding to check that the right number of items was parsed
    // get the data from the channel
    for res := range ch {
        log.Println(res, counter)
        counter++
    }
}


问:
How to create IPA using terminal
I'm using XCode 8.3. if I fire this command in Terminal for making an archive as shown below. It shows this kind of error. Can you help me to find out the solution?</p>

```<code>xcodebuild -configuration Release -exportArchive -exportFormat ipa -archivePath "/Users/Desktop/Demo.xcarchive" -exportPath "/Users/Desktop/Demo.ipa" -exportProvisioningProfile "Demo Development"

xcodebuild: error: invalid option '-exportFormat'

Usage: xcodebuild [-project <projectname>] [[-target <targetname>]...|-alltargets] [-configuration <configurationname>] [-arch <architecture>]... [-sdk [<sdkname>|<sdkpath>]] [-showBuildSettings] [<buildsetting>=<value>]... [<buildaction>]...
  xcodebuild [-project <projectname>] -scheme <schemeName> [-destination <destinationspecifier>]... [-configuration <configurationname>] [-arch <architecture>]... [-sdk [<sdkname>|<sdkpath>]] [-showBuildSettings] [<buildsetting>=<value>]... [<buildaction>]...
  xcodebuild -workspace <workspacename> -scheme <schemeName> [-destination <destinationspecifier>]... [-configuration <configurationname>] [-arch <architecture>]... [-sdk [<sdkname>|<sdkpath>]] [-showBuildSettings] [<buildsetting>=<value>]... [<buildaction>]...
  xcodebuild -version [-sdk [<sdkfullpath>|<sdkname>] [<infoitem>] ]
  xcodebuild -list [[-project <projectname>]|[-workspace <workspacename>]] [-json]
  xcodebuild -showsdks
  xcodebuild -exportArchive -archivePath <xcarchivepath> -exportPath <destinationpath> -exportOptionsPlist <plistpath>
  xcodebuild -exportLocalizations -localizationPath <path> -project <projectname> [-exportLanguage <targetlanguage>...]
  xcodebuild -importLocalizations -localizationPath <path> -project <projectname>
</code>```

答:
A few things changed: -exportFormat and -exportProvisioningProfile don't exist anymore. Also, -exportPath now point to an actual path, not to a file.

You will have to create a plist file with your export options. This is an easy command-line way to do this:

```<code>echo "{\"method\":\"app-store\"}" | plutil -convert xml1 -o /tmp/exportOptions.plist -- -
</code>```

Then use -exportOptionsPlist /tmp/exportOptions.plist in your call to xcodebuild.

Title: How to create IPA using terminal

Body:
I'm using XCode 8.3. if I fire this command in Terminal for making an archive as shown below. It shows this kind of error. Can you help me to find out the solution?

xcodebuild -configuration Release -exportArchive -exportFormat ipa -archivePath "/Users/Desktop/Demo.xcarchive" -exportPath "/Users/Desktop/Demo.ipa" -exportProvisioningProfile "Demo Development"

xcodebuild: error: invalid option '-exportFormat'

Usage: xcodebuild [-project <projectname>] [[-target <targetname>]...|-alltargets] [-configuration <configurationname>] [-arch <architecture>]... [-sdk [<sdkname>|<sdkpath>]] [-showBuildSettings] [<buildsetting>=<value>]... [<buildaction>]...
  xcodebuild [-project <projectname>] -scheme <schemeName> [-destination <destinationspecifier>]... [-configuration <configurationname>] [-arch <architecture>]... [-sdk [<sdkname>|<sdkpath>]] [-showBuildSettings] [<buildsetting>=<value>]... [<buildaction>]...
  xcodebuild -workspace <workspacename> -scheme <schemeName> [-destination <destinationspecifier>]... [-configuration <configurationname>] [-arch <architecture>]... [-sdk [<sdkname>|<sdkpath>]] [-showBuildSettings] [<buildsetting>=<value>]... [<buildaction>]...
  xcodebuild -version [-sdk [<sdkfullpath>|<sdkname>] [<infoitem>] ]
  xcodebuild -list [[-project <projectname>]|[-workspace <workspacename>]] [-json]
  xcodebuild -showsdks
  xcodebuild -exportArchive -archivePath <xcarchivepath> -exportPath <destinationpath> -exportOptionsPlist <plistpath>
  xcodebuild -exportLocalizations -localizationPath <path> -project <projectname> [-exportLanguage <targetlanguage>...]
  xcodebuild -importLocalizations -localizationPath <path> -project <projectname>

Body:
A few things changed: -exportFormat and -exportProvisioningProfile don't exist anymore. Also, -exportPath now point to an actual path, not to a file.

You will have to create a plist file with your export options. This is an easy command-line way to do this:

echo "{\"method\":\"app-store\"}" | plutil -convert xml1 -o /tmp/exportOptions.plist -- -

Then use -exportOptionsPlist /tmp/exportOptions.plist in your call to xcodebuild.


问:
Angular 2 routerlink with multiple routes?
I want to remove a class only one ONE route, (Or add a class on all BUT one route.)  How is that possible?  I have tried [routerLink] with multiple parameters to no avail:

```<code> <div class='body-content' [routerLink]="['/fetch-data', '/counter']" [routerLinkActive]="['col-sm-9']"  >
        <router-outlet></router-outlet>
    </div>
</code>```

Or, is there such a thing as     [routerLinkNOTActive] or something similar like so:

```<code><div class='body-content' [routerLink]="['/home']" [routerLinkNotActive]="['col-sm-9']">
</code>```

so, then it would add the 'col-sm-9' class on all routes that are not '/home'.  Seems very simple, but can't find anything to do it.

答:
I don't know if there is a built in directive to do what you want but you can always add some logic to your component.

In your template,

```<code><div class='body-content' [routerLink]="['/fetch-data', '/counter']" [class]="bodyContentClass()">
</code>```

And in your component,

```<code>bodyContentClass() {
  // router  is an instance of Router, injected in the constructor
  return this.router.isActive('/url-to-make-body-active') || this.router.isActive('/other-url-to-make-body-active') ? 'col-sm-9' : '';
}
</code>```

You can have fun and test against whatever combination of routes you wish.

Body:
I want to remove a class only one ONE route, (Or add a class on all BUT one route.)  How is that possible?  I have tried [routerLink] with multiple parameters to no avail:

        <router-outlet></router-outlet>

Or, is there such a thing as     [routerLinkNOTActive] or something similar like so:

so, then it would add the 'col-sm-9' class on all routes that are not '/home'.  Seems very simple, but can't find anything to do it.

Body:
I don't know if there is a built in directive to do what you want but you can always add some logic to your component.

In your template,

<div class='body-content' [routerLink]="['/fetch-data', '/counter']" [class]="bodyContentClass()">

And in your component,

bodyContentClass() {
  // router  is an instance of Router, injected in the constructor
  return this.router.isActive('/url-to-make-body-active') || this.router.isActive('/other-url-to-make-body-active') ? 'col-sm-9' : '';
}

You can have fun and test against whatever combination of routes you wish.


问:
HTML inside XML CDATA being converted with < and > brackets
I have some sample XML:

```<code><sample><![CDATA[Line 1<br />Line 2<br />Line 3<br />]]></sample>
</code>```

I'm using ASP to output this XML using a stylesheet like so:

```<code>Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
xmlHttp.open "GET", URLxml, false
xmlHttp.send()

Set xslHttp = Server.CreateObject("Microsoft.XMLHTTP")
xslHttp.open "GET", xXsl, false
xslHttp.send()

Set xmlDoc = Server.CreateObject("MICROSOFT.XMLDOM")
Set xslDoc = Server.CreateObject("MICROSOFT.XMLDOM")
xmlDoc.async = false
xslDoc.async = false
xmlDoc.Load xmlHttp.responseXML
xslDoc.Load xslHttp.responseXML

Response.Write xmlDoc.transformNode(xslDoc)
</code>```

However, once this is getting written, the HTML output is showing up as:

```<code>Line 1<br />Line 2<br />Line 3
</code>```

I can see that ASP is converting the brackets in the code, but I'm not sure why.  Any thoughts?

答:
Think it's the XSL transformation that's causing you problems. You should be able to edit your .xsl document to correct this as such:

```<code><xsl:template match=".">
  <xsl:value-of select="." disable-output-escaping="yes" />
  <!-- ... other XSL business here ... -->
</xsl:template>
</code>```

I'm stealing from this page about disable output escaping.

For the record I hate XML/XSL - a solution in search of a problem. Generally speaking if you need to deal with markup I've found XML/XSL only introduces problems because frequently you want to deal with markup fragments, which are often not valid XML, so you wrap CDATA around it and then hilarity ensues as you're experiencing.

Update

OK, so the above didn't work. Of course didn't know what XSL looked like until comment on question was added. The following does work (idea from this forum thread):

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />
    <xsl:template match=".">
        <xsl:value-of select="sample"  />
    </xsl:template>
</xsl:stylesheet>
</code>```

Key is the <xsl:output method="text" />.

ContentLicense: CC BY-SA 2.5

Body:
I have some sample XML:

<sample><![CDATA[Line 1
Line 2
Line 3
]]></sample>

I'm using ASP to output this XML using a stylesheet like so:

Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
xmlHttp.open "GET", URLxml, false
xmlHttp.send()

Set xslHttp = Server.CreateObject("Microsoft.XMLHTTP")
xslHttp.open "GET", xXsl, false
xslHttp.send()

Set xmlDoc = Server.CreateObject("MICROSOFT.XMLDOM")
Set xslDoc = Server.CreateObject("MICROSOFT.XMLDOM")
xmlDoc.async = false
xslDoc.async = false
xmlDoc.Load xmlHttp.responseXML
xslDoc.Load xslHttp.responseXML

Response.Write xmlDoc.transformNode(xslDoc)

However, once this is getting written, the HTML output is showing up as:

Line 1
Line 2
Line 3

I can see that ASP is converting the brackets in the code, but I'm not sure why.  Any thoughts?

Body:
Think it's the XSL transformation that's causing you problems. You should be able to edit your .xsl document to correct this as such:

<xsl:template match=".">
  <xsl:value-of select="." disable-output-escaping="yes" />
  <!-- ... other XSL business here ... -->
</xsl:template>

I'm stealing from this page about disable output escaping.

For the record I hate XML/XSL - a solution in search of a problem. Generally speaking if you need to deal with markup I've found XML/XSL only introduces problems because frequently you want to deal with markup fragments, which are often not valid XML, so you wrap CDATA around it and then hilarity ensues as you're experiencing.

Update

OK, so the above didn't work. Of course didn't know what XSL looked like until comment on question was added. The following does work (idea from this forum thread):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />
    <xsl:template match=".">
        <xsl:value-of select="sample"  />
    </xsl:template>
</xsl:stylesheet>

Key is the <xsl:output method="text" />.

ContentLicense: CC BY-SA 4.0


问:
Set Child width maximum of Screen width having absolute position
I have 3 drop down menus with dynamic width and position like these

I want to make each drop down width to maximum of Screen width starting from the current position leaving 10px from right side like this.

The drop down list is positioned absolute to its parent container. I want to make a single css class and apply the each drop down list so it can act like the above one which can have maximum of screen width subtracting 10px from it.

By searching SO, I found many questions but could not get it work in my problem. I don't want to do anything with Javascript but with pure CSS only.

Many of SO Questions suggest using vw unit of css but I don't understand how to use vw in this problem. Any help from you experts will be really appreciated. Thanks.

Some suggest this but does not work

```<code>width:100vw;
margin-left:100%;
transform: translate(-50vw);
</code>```

Because above could is good if I want to make drop down in center of screen but here the situation is starting from parent position. I have tried replacing it with margin-right and tried as much I could but no use.

答:
i don't think this can be made with a single class, you should be using a single class for each menu item.

You can first set a fixed width to top menu item, something like 100px. So each item next will be 100px further from the left side of the page.

Now you have to make a calculation of 100% of the viewport with 100vw, and then subtract the pixels from the previous items, if the item menu has 2 items before then it will be 200 pixels.

This substraction can be made with calc like this: width: calc(100vw - 200px);

The result with this technique would be something like this:

`

Here is an example: https://jsfiddle.net/52jab0t9/

I hope this help you, excuse me by my bad english :)

PD: I took the code for the menu from here: http://www.cssscript.com/demo/simple-clean-pure-css3-dropdown-menu/

Body:
I have 3 drop down menus with dynamic width and position like these

I want to make each drop down width to maximum of Screen width starting from the current position leaving 10px from right side like this.

The drop down list is positioned absolute to its parent container. I want to make a single css class and apply the each drop down list so it can act like the above one which can have maximum of screen width subtracting 10px from it.

By searching SO, I found many questions but could not get it work in my problem. I don't want to do anything with Javascript but with pure CSS only.

Many of SO Questions suggest using vw unit of css but I don't understand how to use vw in this problem. Any help from you experts will be really appreciated. Thanks.

Some suggest this but does not work

width:100vw;
margin-left:100%;
transform: translate(-50vw);

Because above could is good if I want to make drop down in center of screen but here the situation is starting from parent position. I have tried replacing it with margin-right and tried as much I could but no use.


问:
Rails 4+, ordering list of parent records by children
I have a page that displays a lot of data and I'm working on optimizing it and I'm struggling with balancing reducing DB queries with getting the proper data in the order I need.

A Transaction is the top-level element, and each transaction has multiple workflows and each workflow has many milestones.  I order the workflows and milestones by a position:integer attribute.

```<code># Top-level element
class Transaction < ApplicationRecord
  has_many :workflows
  has_many :team_members
end

# Parent element for milestones
class Workflow < ApplicationRecord
  belongs_to :transaction
  has_many :milestones
end

# Unique individual
class Person < ApplicationRecord
  has_many :team_members
end

# Acts as a join between Transactions and Persons
class TeamMember < ApplicationRecord
  belongs_to :transaction
  belongs_to :person
  belongs_to :team_member_type
end

class TeamMemberType < ApplicationRecord
  has_many :team_members
end
</code>```

In my controller this is what I have:

```<code>def show
  @transaction = Transaction.includes(
    team_members: [:person, :team_member_type],
    workflows: [:milestones]
  ).find(params[id])
end
</code>```

This gathers all the data I need in 1 DB query, but the problem is when I iterate over the milestones for a workflow, I need it to be sorted by the position attribute.

I can grab the data from the DB and then sort it with Ruby, but that seems inefficient and I would prefer to get it all done in the DB properly (if possible).

If I were to write it with an N+1 issue, it would look like this:

```<code><% @workflows.order(:position).each do |workflow| %>
  <%= workflow.name %>
  <% workflow.milestones.order(:position).each do |milestone| %>
    <%= milestone.name %>
  <% end %>
<% end %>
</code>```

I think everyone agrees that's a bad idea, but I'm struggling to figure out how to sort the data and optimize my DB calls at the same time.

I also sort the team_members by the team_member_type.value attribute, but that's the same question as above.

```<code><% @team_members.includes(:team_member_type, :person).order("team_member_types.value").each do |team_member| %>
  ...
<% end %>
</code>```

My main objective is efficiency.  If I need to use some Query objects to clean it up and raw SQL, I'm ok with that, I'm just not extremely proficient at SQL and would prefer using ActiveRecord if reasonable.

答:
You could create associations that include the order_by, but my experience has been that that can silently fail when eager loading, leaving you with an unordered result.

Although you believe, probably correctly, that ordering in Ruby would be less efficient, I would at least benchmark it. The major performance problem is in the n + 1 query situation, and I would be optimistic that you'll find sorting in Ruby to be performant enough.

Body:
I have a page that displays a lot of data and I'm working on optimizing it and I'm struggling with balancing reducing DB queries with getting the proper data in the order I need.

A Transaction is the top-level element, and each transaction has multiple workflows and each workflow has many milestones.  I order the workflows and milestones by a position:integer attribute.

# Top-level element
class Transaction < ApplicationRecord
  has_many :workflows
  has_many :team_members
end

# Parent element for milestones
class Workflow < ApplicationRecord
  belongs_to :transaction
  has_many :milestones
end

# Unique individual
class Person < ApplicationRecord
  has_many :team_members
end

# Acts as a join between Transactions and Persons
class TeamMember < ApplicationRecord
  belongs_to :transaction
  belongs_to :person
  belongs_to :team_member_type
end

class TeamMemberType < ApplicationRecord
  has_many :team_members
end

In my controller this is what I have:

def show
  @transaction = Transaction.includes(
    team_members: [:person, :team_member_type],
    workflows: [:milestones]
  ).find(params[id])
end

This gathers all the data I need in 1 DB query, but the problem is when I iterate over the milestones for a workflow, I need it to be sorted by the position attribute.

I can grab the data from the DB and then sort it with Ruby, but that seems inefficient and I would prefer to get it all done in the DB properly (if possible).

If I were to write it with an N+1 issue, it would look like this:

<% @workflows.order(:position).each do |workflow| %>
  <%= workflow.name %>
  <% workflow.milestones.order(:position).each do |milestone| %>
    <%= milestone.name %>
  <% end %>
<% end %>

I think everyone agrees that's a bad idea, but I'm struggling to figure out how to sort the data and optimize my DB calls at the same time.

I also sort the team_members by the team_member_type.value attribute, but that's the same question as above.

<% @team_members.includes(:team_member_type, :person).order("team_member_types.value").each do |team_member| %>
  ...
<% end %>

My main objective is efficiency.  If I need to use some Query objects to clean it up and raw SQL, I'm ok with that, I'm just not extremely proficient at SQL and would prefer using ActiveRecord if reasonable.


问:
How to keep two databases with different schemas up-to-date
Our company has really old legacy system with such a bad database design (no foreign keys, columns with serialized PHP arrays, etc. :(). We decided to rewrite a system from a scratch with new database schema.

We want to rewrite a system by parts. So we will split old monolithic application to many smaller ones.

Problem is: we want to have live data in two databases. Old and New schema.
I'd like to ask you if anyone of you knows best practices how to do this.

What we think of:

asynchronous data synchronization with message queue

make a REST API in new system and make legacy application to use
    it instead of db calls

some kind of table replication

Thank you very much

答:
I would start by adding a database layer to accept API calls from the business layer, then write to both the old schema and the new.  This adds complexity up front, but it lets you guarantee that the data stays in sync.

This would require changing the legacy system to call an API instead of issuing SQL statements.  If they did not have the foresight to do that originally, you may not be able to take my approach.  But, you should do it going forward.

Triggers may or may not work out.  In older versions of MySQL, there can be only one trigger of a given type on a given table.  This forces you to lump unrelated things into a single trigger.

Replication can solve some changes -- Engine, datatypes, etc.  But it cannot help with splitting one table into two.  Be careful of the replication of Triggers and where the Trigger has effect (between Master and Slave).  In general, a stored routine should be performed on the Master, letting the effect be replicated to the slave.  But it may be worth considering how to have the trigger run in the Slave instead.  Or different triggers in the two servers.

Another thought is to do the transformation in stages.  By careful planning of schema changes versus application of triggers versus code changes versus database layer, you can do partial transformations one at a time, sometimes without having a big outage to update everything simultaneously (with your fingers crossed).  A simple example:  (1) change code to dynamically handle either new or old schema, (2) change the schema, (3) clean up the code (remove handling of old schema).


问:
Android programming : exception with button listener in controller class
I have an activity and a button on it by clicking on which I want to open another activity. I want to perform the button click event in my controller class so I use

Inside my MainActivity.java

```<code>MainController mainController = new MainController(btn_secondpage);
btn_secondpage.setOnClickListener(mainController);
</code>```

and in MainController class I used these methods-

Inside MainController class..

```<code>public MainController(Button btn_secondpage) {

    this.btn_secondpage=btn_secondpage;

    }

@Override
public void onClick(View v) {
    Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
    startActivity(intent);

}
</code>```

But whenever I click on the button a dialogue box opens and shows that my app has stopped working...
I am using eclipse mars2
I have provided all of my classes, xml, manifest.xml

activity_main.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_id"
    style="@style/AppTheme"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.testandroidproject.view.MainActivity" >

    <Button
        android:id="@+id/btn_secondpage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Second page" />

</RelativeLayout>
</code>```

activity_second.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.testandroidproject.view.SecondActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Welcome to second page" />

</RelativeLayout>
</code>```

MainActivity.java

```<code>package com.testandroidproject.view;

import com.example.testandroidproject.R;
import com.testandroidproject.controller.MainController;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    public Button btn_secondpage;
    public static final String TAG = "abcd";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(TAG, "inside oncreate");             // printing (1st)
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        MainController mainController = new MainController(btn_secondpage);
        btn_secondpage.setOnClickListener(mainController);

        //      onButtonClick();  // this is working properly
    }

    ////////////// this method is working properly.......
    public void onButtonClick(){
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        btn_secondpage.setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
                        startActivity(intent);

                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //  Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        //  automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</code>```

SecondActivity.java

```<code>package com.testandroidproject.view;

import com.example.testandroidproject.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    //  Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</code>```

MainController.java

```<code>package com.testandroidproject.controller;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainController extends Activity implements OnClickListener {
    Button btn_secondpage;
    public static final String TAG = "abcd";

    public MainController(Button btn_secondpage) {
        this.btn_secondpage=btn_secondpage;
        Log.i(TAG, "inside mainController constructor"); // printing (2nd)
    }

    @Override
    public void onClick(View v) {
        Log.i(TAG, "inside public void onClick before intent");                     // printing(3rd)
        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
        Log.i(TAG, "inside public void onClick after intent");                      // printing(4th)
        startActivity(intent);
        Log.i(TAG, "inside public void onClick after startActivity");               //  NOT printing

    }

}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testandroidproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="21"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.testandroidproject.view.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.testandroidproject.view.SecondActivity"
            android:label="@string/title_activity_second" >
            <intent-filter>
                <action android:name="com.testandroidproject.view.SecondActivity" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

logcat

```<code>04-01 00:10:38.344: I/abcd(1764): inside oncreate
04-01 00:10:38.345: I/abcd(1764): inside mainController constructor
04-01 00:10:38.370: D/OpenGLRenderer(1764): Render dirty regions requested:     true
04-01 00:10:38.374: D/(1764): HostConnection::get() New Host Connection   established 0xa5f43380, tid 1764
04-01 00:10:38.375: D/Atlas(1764): Validating map...
04-01 00:10:38.399: D/(1764): HostConnection::get() New Host Connection established 0xad480dc0, tid 1780
04-01 00:10:38.401: I/OpenGLRenderer(1764): Initialized EGL, version 1.4
04-01 00:10:38.446: D/OpenGLRenderer(1764): Enabling debug mode 0
04-01 00:10:38.546: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:10:38.546: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:51.749: I/abcd(1764): inside oncreate
04-01 00:11:51.754: I/abcd(1764): inside mainController constructor
04-01 00:11:51.896: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:11:51.896: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:55.658: I/abcd(1764): inside public void onClick before intent
04-01 00:11:55.658: I/abcd(1764): inside public void onClick after intent
04-01 00:11:55.658: D/AndroidRuntime(1764): Shutting down VM
04-01 00:11:55.658: D/AndroidRuntime(1764): --------- beginning of crash
04-01 00:11:55.658: E/AndroidRuntime(1764): FATAL EXCEPTION: main
04-01 00:11:55.658: E/AndroidRuntime(1764): Process:   com.example.testandroidproject, PID: 1764
04-01 00:11:55.658: E/AndroidRuntime(1764): java.lang.NullPointerException:   Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
04-01 00:11:55.658: E/AndroidRuntime(1764):     at   android.app.Activity.startActivityForResult(Activity.java:3736)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android. app.Activity.startActivityForResult(Activity.java:3697)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:4007)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:3975)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.testandroidproject.controller.MainController.onClick(MainController.java:24)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View.performClick(View.java:4756)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View$PerformClick.run(View.java:19749)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.handleCallback(Handler.java:739)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Looper.loop(Looper.java:135)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.ActivityThread.main(ActivityThread.java:5221)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Native Method)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Method.java:372)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.and  roid.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-01 00:11:55.857: I/art(1764): Background sticky concurrent mark sweep GC freed 2383(175KB) AllocSpace objects, 1(81KB) LOS objects, 29% free,    794KB/1135KB, paused 1.621ms total 150.498ms
04-01 00:12:09.406: I/Process(1764): Sending signal. PID: 1764 SIG: 9
</code>```

enter image description here

答:
in your MainController class in onClick() you are wrong when create Intent object, change with this Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class);

be sure your MainController is not subclass of an Activity, that's causes error. Because now your activity is not subclass of Context, so could not be able to call startActivity(). To start an activity use context from passed Button

```<code>public class MainController implements OnClickListener{
    //............
@Override
public void onClick(View v) {
    Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class);
    btn_secondpage.getContext().startActivity(intent);
}
</code>```

Body:
I have an activity and a button on it by clicking on which I want to open another activity. I want to perform the button click event in my controller class so I use

Inside my MainActivity.java

MainController mainController = new MainController(btn_secondpage);
btn_secondpage.setOnClickListener(mainController);

and in MainController class I used these methods-

Inside MainController class..

public MainController(Button btn_secondpage) {

    this.btn_secondpage=btn_secondpage;

    }

@Override
public void onClick(View v) {
    Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
    startActivity(intent);

}

But whenever I click on the button a dialogue box opens and shows that my app has stopped working...
I am using eclipse mars2
I have provided all of my classes, xml, manifest.xml

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_id"
    style="@style/AppTheme"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.testandroidproject.view.MainActivity" >

    <Button
        android:id="@+id/btn_secondpage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Second page" />

</RelativeLayout>

activity_second.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.testandroidproject.view.SecondActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Welcome to second page" />

</RelativeLayout>

MainActivity.java

package com.testandroidproject.view;

import com.example.testandroidproject.R;
import com.testandroidproject.controller.MainController;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    public Button btn_secondpage;
    public static final String TAG = "abcd";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(TAG, "inside oncreate");             // printing (1st)
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        MainController mainController = new MainController(btn_secondpage);
        btn_secondpage.setOnClickListener(mainController);

        //      onButtonClick();  // this is working properly
    }

    ////////////// this method is working properly.......
    public void onButtonClick(){
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        btn_secondpage.setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
                        startActivity(intent);

                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //  Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        //  automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

SecondActivity.java

package com.testandroidproject.view;

import com.example.testandroidproject.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    //  Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

MainController.java

package com.testandroidproject.controller;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainController extends Activity implements OnClickListener {
    Button btn_secondpage;
    public static final String TAG = "abcd";

    public MainController(Button btn_secondpage) {
        this.btn_secondpage=btn_secondpage;
        Log.i(TAG, "inside mainController constructor"); // printing (2nd)
    }

    @Override
    public void onClick(View v) {
        Log.i(TAG, "inside public void onClick before intent");                     // printing(3rd)
        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
        Log.i(TAG, "inside public void onClick after intent");                      // printing(4th)
        startActivity(intent);
        Log.i(TAG, "inside public void onClick after startActivity");               //  NOT printing

    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testandroidproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="21"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.testandroidproject.view.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.testandroidproject.view.SecondActivity"
            android:label="@string/title_activity_second" >
            <intent-filter>
                <action android:name="com.testandroidproject.view.SecondActivity" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

logcat

04-01 00:10:38.344: I/abcd(1764): inside oncreate
04-01 00:10:38.345: I/abcd(1764): inside mainController constructor
04-01 00:10:38.370: D/OpenGLRenderer(1764): Render dirty regions requested:     true
04-01 00:10:38.374: D/(1764): HostConnection::get() New Host Connection   established 0xa5f43380, tid 1764
04-01 00:10:38.375: D/Atlas(1764): Validating map...
04-01 00:10:38.399: D/(1764): HostConnection::get() New Host Connection established 0xad480dc0, tid 1780
04-01 00:10:38.401: I/OpenGLRenderer(1764): Initialized EGL, version 1.4
04-01 00:10:38.446: D/OpenGLRenderer(1764): Enabling debug mode 0
04-01 00:10:38.546: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:10:38.546: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:51.749: I/abcd(1764): inside oncreate
04-01 00:11:51.754: I/abcd(1764): inside mainController constructor
04-01 00:11:51.896: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:11:51.896: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:55.658: I/abcd(1764): inside public void onClick before intent
04-01 00:11:55.658: I/abcd(1764): inside public void onClick after intent
04-01 00:11:55.658: D/AndroidRuntime(1764): Shutting down VM
04-01 00:11:55.658: D/AndroidRuntime(1764): --------- beginning of crash
04-01 00:11:55.658: E/AndroidRuntime(1764): FATAL EXCEPTION: main
04-01 00:11:55.658: E/AndroidRuntime(1764): Process:   com.example.testandroidproject, PID: 1764
04-01 00:11:55.658: E/AndroidRuntime(1764): java.lang.NullPointerException:   Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
04-01 00:11:55.658: E/AndroidRuntime(1764):     at   android.app.Activity.startActivityForResult(Activity.java:3736)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android. app.Activity.startActivityForResult(Activity.java:3697)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:4007)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:3975)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.testandroidproject.controller.MainController.onClick(MainController.java:24)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View.performClick(View.java:4756)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View$PerformClick.run(View.java:19749)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.handleCallback(Handler.java:739)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Looper.loop(Looper.java:135)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.ActivityThread.main(ActivityThread.java:5221)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Native Method)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Method.java:372)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.and  roid.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-01 00:11:55.857: I/art(1764): Background sticky concurrent mark sweep GC freed 2383(175KB) AllocSpace objects, 1(81KB) LOS objects, 29% free,    794KB/1135KB, paused 1.621ms total 150.498ms
04-01 00:12:09.406: I/Process(1764): Sending signal. PID: 1764 SIG: 9

enter image description here

Body:
in your MainController class in onClick() you are wrong when create Intent object, change with this Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class);

be sure your MainController is not subclass of an Activity, that's causes error. Because now your activity is not subclass of Context, so could not be able to call startActivity(). To start an activity use context from passed Button

public class MainController implements OnClickListener{
    //............
@Override
public void onClick(View v) {
    Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class);
    btn_secondpage.getContext().startActivity(intent);
}


问:
How to output only the first n lines based on occurrences of a column string
I have a large file that contains ID numbers in the first column, followed by additional unique information in subsequent columns. Each ID number occurs multiple times in the file:

```<code>000112 3489 A-8 40984
000112 4743 A-7 94587
000112 5894 A-1 45795
000177 8347 A-2 54575
000177 5843 B-5 94342
000177 5684 A-4 76544
000177 6586 C-2 65834
000226 5679 C-2 85795
000226 5456 C-1 45876
000226 9899 A-2 56834
</code>```

I would like to output a file containing lines for only the first two occurrences of each ID number:

```<code>000112 3489 A-8 40984
000112 4743 A-7 94587
000177 8347 A-2 54575
000177 5843 B-5 94342
000226 5679 C-2 85795
000226 5456 C-1 45876
</code>```

Note that this data represents only a small portion of the input file, so a command that requires entering specific strings (ID numbers) is not what I'm looking for. Thanks!

答:
```<code>awk 'a[$1]++ < 2' input-file
</code>```

should do the trick.  Just read the file and increment an array indexed by the value in the first column.  If that value is less than 2, print the line.  When you see the same id the 3rd time, the index in the array will be two and the output of that line will be suppressed.

Body:
I have a large file that contains ID numbers in the first column, followed by additional unique information in subsequent columns. Each ID number occurs multiple times in the file:

000112 3489 A-8 40984
000112 4743 A-7 94587
000112 5894 A-1 45795
000177 8347 A-2 54575
000177 5843 B-5 94342
000177 5684 A-4 76544
000177 6586 C-2 65834
000226 5679 C-2 85795
000226 5456 C-1 45876
000226 9899 A-2 56834

I would like to output a file containing lines for only the first two occurrences of each ID number:

000112 3489 A-8 40984
000112 4743 A-7 94587
000177 8347 A-2 54575
000177 5843 B-5 94342
000226 5679 C-2 85795
000226 5456 C-1 45876

Note that this data represents only a small portion of the input file, so a command that requires entering specific strings (ID numbers) is not what I'm looking for. Thanks!

Body:
awk 'a[$1]++ < 2' input-file

should do the trick.  Just read the file and increment an array indexed by the value in the first column.  If that value is less than 2, print the line.  When you see the same id the 3rd time, the index in the array will be two and the output of that line will be suppressed.


问:
javax.mail.MessagingException: Could not convert socket to TLS exception in JAVA
I want to send a mail from my email address to another email address via clicking a button in JFrame netbeans.Here is the code,

```<code>import java.awt.HeadlessException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;
import com.sun.mail.util.MailSSLSocketFactory;
import java.io.File;
import javax.mail.PasswordAuthentication;
import javax.mail.*;
import javax.swing.JFileChooser;

    private void btn_sendActionPerformed(java.awt.event.ActionEvent evt) {
    final String From = txt_from.getText();
    final String password = txt_password.getText();
    String To = txt_to.getText();
    String subject = txt_sub.getText();
    String txtmessage = txt_body.getText();

    Properties props = new Properties();

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "587");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLsocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.fallback", "true");
    props.put("mail.smtp.ssl.socketFactory", "true");
    props.put("mail.smtp.EnableSSL.enable","true");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(From, password);
                }
            }
    );

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(From));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));
        message.setSubject(subject);

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(txtmessage);
        Multipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachment_path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(txt_DocAttach.getText());
        multiPart.addBodyPart(messageBodyPart);

        message.setContent(multiPart);

        Transport.send(message);
        JOptionPane.showMessageDialog(rootPane, "Message is sent");
    } catch (MessagingException | HeadlessException e) {
        JOptionPane.showMessageDialog(rootPane, e);
    }

}
</code>```

But it is giving me following error,

javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: java.io.lOException: Exception in startTLS using SSL socket factory class null: host, port smtp.gmail.com, 587; Exception: java.lang.ClassNotFoundException: javax.netssl.SSLsocketFactory

Tried a lot but can't figure out what to do to solve it? Help please.

答:
As others have pointed out, your socket factory settings were wrong.

More importantly, you never needed to set them at all!

Body:
I want to send a mail from my email address to another email address via clicking a button in JFrame netbeans.Here is the code,

import java.awt.HeadlessException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;
import com.sun.mail.util.MailSSLSocketFactory;
import java.io.File;
import javax.mail.PasswordAuthentication;
import javax.mail.*;
import javax.swing.JFileChooser;

    private void btn_sendActionPerformed(java.awt.event.ActionEvent evt) {
    final String From = txt_from.getText();
    final String password = txt_password.getText();
    String To = txt_to.getText();
    String subject = txt_sub.getText();
    String txtmessage = txt_body.getText();

    Properties props = new Properties();

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "587");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLsocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.fallback", "true");
    props.put("mail.smtp.ssl.socketFactory", "true");
    props.put("mail.smtp.EnableSSL.enable","true");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(From, password);
                }
            }
    );

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(From));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));
        message.setSubject(subject);

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(txtmessage);
        Multipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachment_path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(txt_DocAttach.getText());
        multiPart.addBodyPart(messageBodyPart);

        message.setContent(multiPart);

        Transport.send(message);
        JOptionPane.showMessageDialog(rootPane, "Message is sent");
    } catch (MessagingException | HeadlessException e) {
        JOptionPane.showMessageDialog(rootPane, e);
    }

}

But it is giving me following error,

javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: java.io.lOException: Exception in startTLS using SSL socket factory class null: host, port smtp.gmail.com, 587; Exception: java.lang.ClassNotFoundException: javax.netssl.SSLsocketFactory

Tried a lot but can't figure out what to do to solve it? Help please.


问:
Parsing JSON Name Pair in C#
Using C# to parse JSON URL I am facing some issues. As you know JSON data is written as name/value pairs. now in URL JSON I have  these data:

```<code>{
   "currentVersion":10.41,
   "serviceDescription":"There are some text here",
   "hasVersionedData":true,
   "supportsDisconnectedEditing":false,
   "syncEnabled":false,
   "supportedQueryFormats":"JSON",
   "maxRecordCount":1000
 }
</code>```

and I want to only print out the name part of the JSON data using this code

```<code>using (var wc = new WebClient())
{
    string json = wc.DownloadString("http://xxxxxxxxx?f=pjson");
    try
    {
        dynamic data = Json.Decode(json);
        for (int i = 0; i <= data.Length - 1; i++)
        {
            Console.WriteLine(data[0]);
        }

    }
    catch (Exception e)
    {

    }
}
</code>```

but this is  not printing any thing on the console! can you please let me know what I am doing wrong?

答:
Create an object to hold the results

```<code>public class RootObject
{
    public double currentVersion { get; set; }
    public string serviceDescription { get; set; }
    public bool hasVersionedData { get; set; }
    public bool supportsDisconnectedEditing { get; set; }
    public bool syncEnabled { get; set; }
    public string supportedQueryFormats { get; set; }
    public int maxRecordCount { get; set; }
}
</code>```

Use a JavaScriptSerializer to deserialize the result.

```<code>var serializer = new JavaScriptSerializer();
var rootObject= serializer.Deserialize<RootObject>(json);

Console.WriteLine(rootObject.currentVersion);
Console.WriteLine(rootObject.serviceDescription);
etc.
</code>```

Title: Parsing JSON Name Pair in C#

Body:
Using C# to parse JSON URL I am facing some issues. As you know JSON data is written as name/value pairs. now in URL JSON I have  these data:

{
   "currentVersion":10.41,
   "serviceDescription":"There are some text here",
   "hasVersionedData":true,
   "supportsDisconnectedEditing":false,
   "syncEnabled":false,
   "supportedQueryFormats":"JSON",
   "maxRecordCount":1000
 }

and I want to only print out the name part of the JSON data using this code

using (var wc = new WebClient())
{
    string json = wc.DownloadString("http://xxxxxxxxx?f=pjson");
    try
    {
        dynamic data = Json.Decode(json);
        for (int i = 0; i <= data.Length - 1; i++)
        {
            Console.WriteLine(data[0]);
        }

    }
    catch (Exception e)
    {

    }
}

but this is  not printing any thing on the console! can you please let me know what I am doing wrong?

Body:
Create an object to hold the results

public class RootObject
{
    public double currentVersion { get; set; }
    public string serviceDescription { get; set; }
    public bool hasVersionedData { get; set; }
    public bool supportsDisconnectedEditing { get; set; }
    public bool syncEnabled { get; set; }
    public string supportedQueryFormats { get; set; }
    public int maxRecordCount { get; set; }
}

Use a JavaScriptSerializer to deserialize the result.

var serializer = new JavaScriptSerializer();
var rootObject= serializer.Deserialize<RootObject>(json);

Console.WriteLine(rootObject.currentVersion);
Console.WriteLine(rootObject.serviceDescription);
etc.


问:
Correct order to write IF conditionals?
I realize this is a really simple and basic question.  I understand that in most programming languages, certainly all of them that I'm familiar with anyway, you can put your conditionals in any order.  However, I'm wondering what the rational would be to put them "backwards".

To explain, here are two examples:

```<code>if (x === 10) {}
if (10 === x) {}
</code>```

I've always done it the first way, and pretty much everything I've always seen does it the first way.  However, every so often, I see it written the second way.  Other than that perhaps the coder in question is dyslexic or something, I'm wondering if there is any particular reason for the second (as I call it, the "backwards") order?

The main reason I'm asking is, I've never seen code by anyone that uses the second style that's poorly done.  It's always excellent code, which makes me wonder if there's something to it that I'm simply not aware of.

Thanks in advance!

答:
This is called Yoda syntax or a Yoda Conditional. It is a matter of style mostly; however, its proponents use it as a way of avoiding assignment operations inside conditional statements. For instance: within an if statement, if one were to accidentally use a single equal sign instead of two, this would likely be a mistake and one which may be easily overlooked when debugging.

```<code>if( x = 7 )...
</code>```

In this case x is assigned the value 7.

```<code>if( 7 = x )...
</code>```

In this case it is a compilation error.

Here're more details: https://en.wikipedia.org/wiki/Yoda_conditions

Title: Correct order to write IF conditionals?

Body:
I realize this is a really simple and basic question.  I understand that in most programming languages, certainly all of them that I'm familiar with anyway, you can put your conditionals in any order.  However, I'm wondering what the rational would be to put them "backwards".

To explain, here are two examples:

if (x === 10) {}
if (10 === x) {}

I've always done it the first way, and pretty much everything I've always seen does it the first way.  However, every so often, I see it written the second way.  Other than that perhaps the coder in question is dyslexic or something, I'm wondering if there is any particular reason for the second (as I call it, the "backwards") order?

The main reason I'm asking is, I've never seen code by anyone that uses the second style that's poorly done.  It's always excellent code, which makes me wonder if there's something to it that I'm simply not aware of.

Thanks in advance!

Body:
This is called Yoda syntax or a Yoda Conditional. It is a matter of style mostly; however, its proponents use it as a way of avoiding assignment operations inside conditional statements. For instance: within an if statement, if one were to accidentally use a single equal sign instead of two, this would likely be a mistake and one which may be easily overlooked when debugging.

if( x = 7 )...

In this case x is assigned the value 7.

if( 7 = x )...

In this case it is a compilation error.

Here're more details: https://en.wikipedia.org/wiki/Yoda_conditions


问:
List get distorted on scrolling
I am using custom ListView and when i scroll my list the image field of each listitem get replaced by some other image of some other listitem.

Can you please tell me some property of listview to prevent this.

Actually when we scroll the list the items those are not visible will perhaps
needs to  be populated again by list adapter each time during scroll.

Thanks in Advance

答:
Check this article on the Android Developers blog, it gives you a good insight on how to implement this. Additionally to this article, I would cache the images in WeakReferences and files to avoid multiple downloads of the same item...

http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

Title: List get distorted on scrolling


问:
Javascript for loop array length
I am new to javascript and I am having this really simple problem.

```<code>    var counters = [];
    for (var i = 0; i < 3; i++) {
        counters.push[i];
    }
    alert(counters.length);
</code>```

This code is expected to alert 3, but the real result is 0. Can someone please this to me. I'm not really sure how to ask about this error. Thanks

Sorry for this question.. I have fixed it. Thanks for answering

I can't ask another quesition yet since not enough karma.. But My real problem is this

```<code>for (var i = 0; i < 2; i++) {
if (i == 1) {document.write(" <tr class='noBorder' onclick='alert(i)');}
if (i == 0){ document.write(" <tr class='noBorder' onclick='alert(i)');}
}
</code>```

Whenever I click on a row, the alert results in 2.
 It's basically this question, but in html
Passing parameter onclick, in a loop

答:
If you are pushing into an array then you need to push the value, The syntax is: array.push(value).

The correct way would be:

    var counters = [];
    for (var i = 0; i < 3; i++) {
        counters.push(i);
    }
    alert(counters.length);```

Title: Javascript for loop array length

Body:
I am new to javascript and I am having this really simple problem.

    var counters = [];
    for (var i = 0; i < 3; i++) {
        counters.push[i];
    }
    alert(counters.length);

This code is expected to alert 3, but the real result is 0. Can someone please this to me. I'm not really sure how to ask about this error. Thanks

Sorry for this question.. I have fixed it. Thanks for answering

I can't ask another quesition yet since not enough karma.. But My real problem is this

for (var i = 0; i < 2; i++) {
if (i == 1) {document.write(" <tr class='noBorder' onclick='alert(i)');}
if (i == 0){ document.write(" <tr class='noBorder' onclick='alert(i)');}
}

Whenever I click on a row, the alert results in 2.
 It's basically this question, but in html
Passing parameter onclick, in a loop


问:
Xhtml page mapping from ManagedBean
Here Is Managed Bean Class

```<code>        package Controller;

        import java.io.Serializable;

        import javax.faces.bean.ManagedBean;
        import javax.faces.bean.SessionScoped;
        import Model.Employee;

         @ManagedBean(name="employeeController")
        @SessionScoped
        public class Employeecontroller implements Serializable{

        public String show(){
          System.out.println("hello");

             return "Login";

            }

           }
</code>```

Here Is web.xml file

```<code>                    <?xml version="1.0" encoding="UTF-8"?>
                    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
                      <display-name>Secondproject</display-name>
                      <welcome-file-list>
                        <welcome-file>index.html</welcome-file>
                        <welcome-file>index.htm</welcome-file>
                        <welcome-file>index.jsp</welcome-file>
                        <welcome-file>default.html</welcome-file>
                        <welcome-file>default.htm</welcome-file>
                        <welcome-file>default.jsp</welcome-file>
                      </welcome-file-list>
                      <servlet>
                        <servlet-name>Faces Servlet</servlet-name>
                        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
                        <load-on-startup>1</load-on-startup>
                      </servlet>
                      <servlet-mapping>
                        <servlet-name>Faces Servlet</servlet-name>
                         <url-pattern>/faces/*</url-pattern>
                        <url-pattern>*.xhtml</url-pattern>
                      </servlet-mapping>
                      <context-param>
                        <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
                        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
                        <param-value>client</param-value>
                      </context-param>
                      <context-param>
                        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
                        <param-value>resources.application</param-value>
                      </context-param>
                      <listener>
                        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
                      </listener>
                       <welcome-file-list>
                       <welcome-file>homepage.xhtml</welcome-file>
                      </welcome-file-list>
                    </web-app>
</code>```

Here id home.xhtml page

```<code>                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                    <html xmlns="http://www.w3.org/1999/xhtml"
                        xmlns:rich="http://richfaces.org/rich"
                        xmlns:ui="http://java.sun.com/jsf/facelets"
                        xmlns:f="http://java.sun.com/jsf/core"
                        xmlns:a4j="http://richfaces.org/a4j"
                        xmlns:h="http://java.sun.com/jsf/html">

                    <h:head></h:head>
                    <body>
                        <rich:panel>
                            <f:facet name="header">
                            Write your own custom rich components with built-in AJAX support
                            </f:facet>
                            <h:outputText value="Panel Body" />
                            <h:form>
                                <h:commandButton action="#{employeeController.show()}" value="Login" />
                            </h:form>

                        </rich:panel>
                    </body>
                    </html>
</code>```

Here is the code for mapping xhtml page from ManagedBean.
  I just want when the button is clicked then the login page will show....But when the button is clicked there is only home.xhtml page reloading...Login page is not loading....

答:
The selection of the next view depends on the value of the action attribute of the UICommand components. If the navigation handler finds a navigation rule for this page with this outcome, the next view will be the  element content. If there is no any rule like this it looks for a page with the value (or it appended with ".xhtml" file extension).

The variations:

1., Direct view definition:

```<code><h:commandButton action="next_page_name"/>
</code>```

It must be a full qualified name (page names + file name), but the xhtml could be omitted.

2., Indirect view definition:
In this case the action value is contains a bean method invocation:

```<code><h:commandButton action="#{myBean.methodName}"/>
</code>```

This method should be a function without any parameter and passes back a String value. This result will be the income for the navigation handler. It could return a page name or a navigation rule.

Now let us see your problem. If the name of your current view is id_home.xhml and you want to navigate to the login.xhtml page (both are in the x package):

1., Direct view definition. Return value "x/login" or "x/login.xhtml" from the show() method:

```<code>public String show()
{
  //...
  return "x/login";
}
</code>```

2., Indirect view definition. Define a page navigation rule in the faces-config.xml like this:

```<code><navigation-rule>
  <from-view-id>/x/id_home.xhtml</from-view-id>
    <navigation-case>
      <from-outcome>go_to_login</from-outcome>
      <to-view-id>x/login.xhtml</to-view-id>
  </navigation-case>
</navigation-rule>
</code>```

In this case myBean.methodName passes back the content of the form-outcome element:

```<code>public String show()
{
  //...
  return "go_to_login";
}
</code>```

Title: Xhtml page mapping from ManagedBean

Body:
Here Is Managed Bean Class

        package Controller;

        import java.io.Serializable;

        import javax.faces.bean.ManagedBean;
        import javax.faces.bean.SessionScoped;
        import Model.Employee;

         @ManagedBean(name="employeeController")
        @SessionScoped
        public class Employeecontroller implements Serializable{

        public String show(){
          System.out.println("hello");

             return "Login";

            }

           }

Here Is web.xml file

                    <?xml version="1.0" encoding="UTF-8"?>
                    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
                      <display-name>Secondproject</display-name>
                      <welcome-file-list>
                        <welcome-file>index.html</welcome-file>
                        <welcome-file>index.htm</welcome-file>
                        <welcome-file>index.jsp</welcome-file>
                        <welcome-file>default.html</welcome-file>
                        <welcome-file>default.htm</welcome-file>
                        <welcome-file>default.jsp</welcome-file>
                      </welcome-file-list>
                      <servlet>
                        <servlet-name>Faces Servlet</servlet-name>
                        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
                        <load-on-startup>1</load-on-startup>
                      </servlet>
                      <servlet-mapping>
                        <servlet-name>Faces Servlet</servlet-name>
                         <url-pattern>/faces/*</url-pattern>
                        <url-pattern>*.xhtml</url-pattern>
                      </servlet-mapping>
                      <context-param>
                        <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
                        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
                        <param-value>client</param-value>
                      </context-param>
                      <context-param>
                        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
                        <param-value>resources.application</param-value>
                      </context-param>
                      <listener>
                        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
                      </listener>
                       <welcome-file-list>
                       <welcome-file>homepage.xhtml</welcome-file>
                      </welcome-file-list>
                    </web-app>

Here id home.xhtml page

                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

                    <h:head></h:head>

                        <rich:panel>
                            <f:facet name="header">
                            Write your own custom rich components with built-in AJAX support
                            </f:facet>
                            <h:outputText value="Panel Body" />
                            <h:form>
                                <h:commandButton action="#{employeeController.show()}" value="Login" />
                            </h:form>

                        </rich:panel>

Here is the code for mapping xhtml page from ManagedBean.
  I just want when the button is clicked then the login page will show....But when the button is clicked there is only home.xhtml page reloading...Login page is not loading....

Body:
The selection of the next view depends on the value of the action attribute of the UICommand components. If the navigation handler finds a navigation rule for this page with this outcome, the next view will be the  element content. If there is no any rule like this it looks for a page with the value (or it appended with ".xhtml" file extension).

The variations:

1., Direct view definition:

<h:commandButton action="next_page_name"/>

It must be a full qualified name (page names + file name), but the xhtml could be omitted.

2., Indirect view definition:
In this case the action value is contains a bean method invocation:

<h:commandButton action="#{myBean.methodName}"/>

This method should be a function without any parameter and passes back a String value. This result will be the income for the navigation handler. It could return a page name or a navigation rule.

Now let us see your problem. If the name of your current view is id_home.xhml and you want to navigate to the login.xhtml page (both are in the x package):

1., Direct view definition. Return value "x/login" or "x/login.xhtml" from the show() method:

public String show()
{
  //...
  return "x/login";
}

2., Indirect view definition. Define a page navigation rule in the faces-config.xml like this:

<navigation-rule>
  <from-view-id>/x/id_home.xhtml</from-view-id>
    <navigation-case>
      <from-outcome>go_to_login</from-outcome>
      <to-view-id>x/login.xhtml</to-view-id>
  </navigation-case>
</navigation-rule>

In this case myBean.methodName passes back the content of the form-outcome element:

public String show()
{
  //...
  return "go_to_login";
}


问:
Plotly graph misbehaving in Shiny
When I select options in my Shiny application, I expect it to produce a graph in plotly and it does. It look like this:

When I unselect the options, it SHOULD look like this:

However, the output is misbehaving in a way I don't understand why. This is output I get:

As you can see, the x and y axis still remains. If I hover over the plot with no options selected, the plot still shows the coordinates.
Here is my code:

```<code># UI
box(width = NULL, uiOutput("plotTitle"),
plotlyOutput('plot1', height="730px"), collapsed = F, title = "Figure",
status = "warning", solidHeader = T, height = "830px")

# SERVER
output$plot1 <- renderPlotly({
   validate(
      need(input$crops, "INSTRUCTIONS: \n\n1) Select Crops Of Interest.\n2)
        Use 'Farm' tab to refine results.\n3) Hover over graph to see values.")
   )

crop.data <- reactive({
crop.list <- input$crops
z.df <- dat
c.df <- subset(z.df, Crop %in% crop.list)
c.df <- unique(c.df)
})

output$plotTitle <- renderUI({
  if(length(crop.data()) > 0) {
    div(style='background-color:green; color:white; text-align:center;
          font-size:22px; font-family:"Open Sans",verdana,arial,sans-serif',
        input$metric)
  }
})

# s.df is the Dataframe
s.df <- subset(s.df, Crop %in% input$crops)

if(length(crop.data()) > 0) {

  if(input$metric == "Percentage") {
    p <- plot_ly(s.df, x = ~Farm, y = ~Percentage, color = ~Crop) %>%
      layout(barmode = 'stack', xaxis = list(title = ''), margin = list(b = 140))

  } else if(input$metric == "Acreage") {
    p <- plot_ly(s.df, x = ~Farm, y = ~Acreage, color = ~Crop) %>%
       layout(barmode = 'stack', xaxis = list(title = ''), margin = list(b = 140))

  } else {
    p <- plot_ly(s.df, x = ~Farm, y = ~Exposure_Costs, color = ~Crop) %>%
      layout(barmode = 'stack', xaxis = list(title = ''),
              yaxis = list(title = 'Exposure Costs'), margin = list(b = 140))
  }
  p
}
})
</code>```

Is there a specific reason as to why this happens? Also, this error doesn't exist on my local instance but occurs on the shiny server and another's local instance. How do I fix it?

答:
You're using length(crop.data()) to check whether or not to plot but this will return a value greater than 0 for an "empty" data.frame because it is counting the number of columns.

e.g.

```<code>> (x <- iris[0, ])
[1] Sepal.Length Sepal.Width  Petal.Length Petal.Width  Species
<0 rows> (or 0-length row.names)
> length(x)
[1] 5
</code>```

You really should untangle your mangling of the reactives, renderUI and renderPlotly but replacing length(crop.data()) with nrow(crop.data()) should solve your problem.

This reproducible example shows that your desired behavior does occur for a simple example:

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

set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]

ui <- fluidPage(

   titlePanel("Null Plotly Object"),

   sidebarLayout(
      sidebarPanel(
         checkboxGroupInput("cuts", "Cut", choices = sort(unique(d$cut)))
      ),

      mainPanel(
         plotlyOutput("distPlot")
      )
   )
)

server <- function(input, output) {

  plot_dat <- reactive({
    shiny::validate(
      need(input$cuts, "Select a cut")
    )
    d[d$cut %in% input$cuts, ]
  })

   output$distPlot <- renderPlotly({
     plot_ly(plot_dat(), x = ~carat, y = ~price, color = ~carat, type = "scatter",
             mode = "markers", size = ~carat, text = ~paste("Clarity: ", clarity))
   })
}

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

Title: Plotly graph misbehaving in Shiny

Body:
When I select options in my Shiny application, I expect it to produce a graph in plotly and it does. It look like this:

When I unselect the options, it SHOULD look like this:

However, the output is misbehaving in a way I don't understand why. This is output I get:

As you can see, the x and y axis still remains. If I hover over the plot with no options selected, the plot still shows the coordinates.
Here is my code:

# UI
box(width = NULL, uiOutput("plotTitle"),
plotlyOutput('plot1', height="730px"), collapsed = F, title = "Figure",
status = "warning", solidHeader = T, height = "830px")

# SERVER
output$plot1 <- renderPlotly({
   validate(
      need(input$crops, "INSTRUCTIONS: \n\n1) Select Crops Of Interest.\n2)
        Use 'Farm' tab to refine results.\n3) Hover over graph to see values.")
   )

crop.data <- reactive({
crop.list <- input$crops
z.df <- dat
c.df <- subset(z.df, Crop %in% crop.list)
c.df <- unique(c.df)
})

output$plotTitle <- renderUI({
  if(length(crop.data()) > 0) {
    div(style='background-color:green; color:white; text-align:center;
          font-size:22px; font-family:"Open Sans",verdana,arial,sans-serif',
        input$metric)
  }
})

# s.df is the Dataframe
s.df <- subset(s.df, Crop %in% input$crops)

if(length(crop.data()) > 0) {

  if(input$metric == "Percentage") {
    p <- plot_ly(s.df, x = ~Farm, y = ~Percentage, color = ~Crop) %>%
      layout(barmode = 'stack', xaxis = list(title = ''), margin = list(b = 140))

  } else if(input$metric == "Acreage") {
    p <- plot_ly(s.df, x = ~Farm, y = ~Acreage, color = ~Crop) %>%
       layout(barmode = 'stack', xaxis = list(title = ''), margin = list(b = 140))

  } else {
    p <- plot_ly(s.df, x = ~Farm, y = ~Exposure_Costs, color = ~Crop) %>%
      layout(barmode = 'stack', xaxis = list(title = ''),
              yaxis = list(title = 'Exposure Costs'), margin = list(b = 140))
  }
  p
}
})

Is there a specific reason as to why this happens? Also, this error doesn't exist on my local instance but occurs on the shiny server and another's local instance. How do I fix it?

Body:
You're using length(crop.data()) to check whether or not to plot but this will return a value greater than 0 for an "empty" data.frame because it is counting the number of columns.

e.g.

> (x <- iris[0, ])
[1] Sepal.Length Sepal.Width  Petal.Length Petal.Width  Species
<0 rows> (or 0-length row.names)
> length(x)
[1] 5

You really should untangle your mangling of the reactives, renderUI and renderPlotly but replacing length(crop.data()) with nrow(crop.data()) should solve your problem.

This reproducible example shows that your desired behavior does occur for a simple example:

library("shiny")
library("plotly")

set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]

ui <- fluidPage(

   titlePanel("Null Plotly Object"),

   sidebarLayout(
      sidebarPanel(
         checkboxGroupInput("cuts", "Cut", choices = sort(unique(d$cut)))
      ),

      mainPanel(
         plotlyOutput("distPlot")
      )
   )
)

server <- function(input, output) {

  plot_dat <- reactive({
    shiny::validate(
      need(input$cuts, "Select a cut")
    )
    d[d$cut %in% input$cuts, ]
  })

   output$distPlot <- renderPlotly({
     plot_ly(plot_dat(), x = ~carat, y = ~price, color = ~carat, type = "scatter",
             mode = "markers", size = ~carat, text = ~paste("Clarity: ", clarity))
   })
}

shinyApp(ui = ui, server = server)


问:
Embedding Google My Maps in an iframe with Phonegap
I'm trying to embed a map into my Phonegap app. It works well when I test it in a browser. Everything in the app is working perfectly in the Xcode iOS emulator as well. However, when I try to embed the map and view it in the emulator, the map doesn't appear at all. Attached is the relevant html:

```<code><div id="map-container">
    <iframe src="https://www.google.com/maps/d/embed?mid=1WVW2iTQgoHSU1Bm3DkQJtlVYSAU" width="640" height="480" frameborder="none"></iframe>
</div>
</code>```

This is a picture of the page working fine in Safari:

This is a picture of the page not loading the map in Xcode's iPhone emulator (after waiting some time):

答:
Try to add this to the config.xml file

```<code><allow-navigation href="*"/>
</code>```

If still not working add to "Content-Security-Policy" the frame rule

```<code>frame-src * gap://ready 'unsafe-inline' 'unsafe-eval';
</code>```

I am using it in this form with dynamic content

```<code>function AddMap() {
// The Url
var mapUrl = "http://www.google.com/maps/d/embed?mid=1WVW2iTQgoHSU1Bm3DkQJtlVYSAU";
// The iframe, don't forget to use the sandbox options
var iframe = '<iframe src="' + mapUrl + '&ll=38.66174332764711%2C-121.12734470700838&z=18" id="frameMap" width="640" height="480" sandbox="allow-same-origin allow-scripts"></iframe>';
var doc = '<!DOCTYPE html><html><body>' + iframe + '</body></html>';

// Assign it to the div
$("#map-container").html(doc);
// Write to log when is full loaded
$("#frameMap").load(function () {
    console.log("Frame loaded.");
});
}
</code>```

Body:
I'm trying to embed a map into my Phonegap app. It works well when I test it in a browser. Everything in the app is working perfectly in the Xcode iOS emulator as well. However, when I try to embed the map and view it in the emulator, the map doesn't appear at all. Attached is the relevant html:

This is a picture of the page working fine in Safari:

This is a picture of the page not loading the map in Xcode's iPhone emulator (after waiting some time):

Body:
Try to add this to the config.xml file

<allow-navigation href="*"/>

If still not working add to "Content-Security-Policy" the frame rule

frame-src * gap://ready 'unsafe-inline' 'unsafe-eval';

I am using it in this form with dynamic content

function AddMap() {
// The Url
var mapUrl = "http://www.google.com/maps/d/embed?mid=1WVW2iTQgoHSU1Bm3DkQJtlVYSAU";
// The iframe, don't forget to use the sandbox options
var iframe = '<iframe src="' + mapUrl + '&ll=38.66174332764711%2C-121.12734470700838&z=18" id="frameMap" width="640" height="480" sandbox="allow-same-origin allow-scripts"></iframe>';
var doc = '<!DOCTYPE html><html><body>' + iframe + '</body></html>';

// Assign it to the div
$("#map-container").html(doc);
// Write to log when is full loaded
$("#frameMap").load(function () {
    console.log("Frame loaded.");
});
}