问:
How to run multiple perl Dancer2 apps in same nginx server
I figured that I can manage multiple apps using location in nginx.

But it seems like I cannot run multiple dancer2 apps in same server with different ports (like localhost:3000, localhost:4000).

Anyway I'm putting this here with a hope that experts can show me some light.

答:
But it seems like I cannot run multiple dancer2 apps in same server with different ports (like localhost:3000, localhost:4000).

This isn't true. Dancer (and, obviously, Dancer2) apps know nothing about the port that they are listening to. That is all handled by your deployment environment. If, for example, you have two Dancer apps called app1.psgi and app2.psgi and you are starting them with plackup, then you can get them running on different ports using the -p command line option.

```<code>$ plackup -p 3000 app1.psgi
$ plackup -p 4000 app2.psgi
</code>```

Body:
But it seems like I cannot run multiple dancer2 apps in same server with different ports (like localhost:3000, localhost:4000).

This isn't true. Dancer (and, obviously, Dancer2) apps know nothing about the port that they are listening to. That is all handled by your deployment environment. If, for example, you have two Dancer apps called app1.psgi and app2.psgi and you are starting them with plackup, then you can get them running on different ports using the -p command line option.

$ plackup -p 3000 app1.psgi
$ plackup -p 4000 app2.psgi


来源: stackexchange

问:
Javascript scrollTop > offset only works on Edge
I am using javascript to change the class of a div once the div moves off screen. I'm using an if statement to only activate the change when the scrollTop is greater than the offset as seen in the code:

```<code>function stickyHeaderExtension() {
    var e = $(".block__header-extension"),
        t = (e.height(), $(e).offset().top);

        window.onscroll = function()
        {
            var i = $("body").scrollTop();
            if (i > t)
            {
                document.getElementById("ContactBlockid").setAttribute("class", "block__header-extension is-fixed");
            }

        };
}
</code>```

This however only works on Edge, Chrome does not respond to the if statement.

This is a similar code with the same result, once again only works in edge:

```<code>function stickyHeaderExtension() {
    var e = $(".block__header-extension"),
        t = (e.height(), $(e).offset().top);
    $(window).on("scroll", function() {
        var i = $("body").scrollTop();
        e.toggleClass("is-fixed", i > t)
    })
}
</code>```

Any idea how to fix this issue? I need it to work in all browsers, not just edge.

答:
Use $(window).scrollTop(); instead of $('body').scrollTop(); Check the demo.

function stickyHeaderExtension() {
    var e = $(".block__header-extension"),
        t = (e.height(), $(e).offset().top);
    $(window).on("scroll", function() {
        var i = $(window).scrollTop();
        e.toggleClass("is-fixed", i > t)
    })
}

stickyHeaderExtension();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.block__header-extension.is-fixed {
  color: red;
}</code>```

  What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

  What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

```

ContentLicense: CC BY-SA 3.0

Body:
I am using javascript to change the class of a div once the div moves off screen. I'm using an if statement to only activate the change when the scrollTop is greater than the offset as seen in the code:

function stickyHeaderExtension() {
    var e = $(".block__header-extension"),
        t = (e.height(), $(e).offset().top);

        window.onscroll = function()
        {
            var i = $("body").scrollTop();
            if (i > t)
            {
                document.getElementById("ContactBlockid").setAttribute("class", "block__header-extension is-fixed");
            }

        };
}

This however only works on Edge, Chrome does not respond to the if statement.

This is a similar code with the same result, once again only works in edge:

function stickyHeaderExtension() {
    var e = $(".block__header-extension"),
        t = (e.height(), $(e).offset().top);
    $(window).on("scroll", function() {
        var i = $("body").scrollTop();
        e.toggleClass("is-fixed", i > t)
    })
}

Any idea how to fix this issue? I need it to work in all browsers, not just edge.

Body:
Use $(window).scrollTop(); instead of $('body').scrollTop(); Check the demo.

function stickyHeaderExtension() {
    var e = $(".block__header-extension"),
        t = (e.height(), $(e).offset().top);
    $(window).on("scroll", function() {
        var i = $(window).scrollTop();
        e.toggleClass("is-fixed", i > t)
    })
}

stickyHeaderExtension();

.block__header-extension.is-fixed {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test-extension">
  What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
</div>
<div class="block__header-extension">
  What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
</div>


问:
How to unit test Request.Form[""]?
Below is my controller's method :-

```<code>   [HttpPost]
   public ActionResult Search(SearchViewModel model)
   {
       string selection = Request.Form["Options"];
       if (selection == "str1")
       {
           -----------------------------
       }
   }
</code>```

And it's based on the condition where its getting value from Request.Form.But Request.Form is only provide Get property and i can't set it's value on unit testing method.Is there any way to set it's value ?

答:
We can mock and Unit Test Request.Form objects by using moq. Please refer below code</p>

```<code>var controllercontext = new Mock<ControllerContext>();
        controllercontext.Setup(frm => frm.HttpContext.Request.Form.Set("Options", "1"));

Yourcontroller.ControllerContext = controllercontext.Object;
var response = YourController.Search(new SearchViewModel() {//Your Model Data..}) as ActionResult;
</code>```

Title: How to unit test Request.Form[""]?

Body:
Below is my controller's method :-

   [HttpPost]
   public ActionResult Search(SearchViewModel model)
   {
       string selection = Request.Form["Options"];
       if (selection == "str1")
       {
           -----------------------------
       }
   }

And it's based on the condition where its getting value from Request.Form.But Request.Form is only provide Get property and i can't set it's value on unit testing method.Is there any way to set it's value ?

Body:
We can mock and Unit Test Request.Form objects by using moq. Please refer below code

var controllercontext = new Mock<ControllerContext>();
        controllercontext.Setup(frm => frm.HttpContext.Request.Form.Set("Options", "1"));

Yourcontroller.ControllerContext = controllercontext.Object;
var response = YourController.Search(new SearchViewModel() {//Your Model Data..}) as ActionResult;


问:
MySQL - Get similarity score from where two different rows meet same condition from two columns
What I want to do is generate a similarity percentage amount by comparing a ratings column from one table with the ratings column from another table.

However, this needs to be limited to instances where an id from one table matches an id in another table, is for a specific user and a rating exists in the ratings column from both tables.

For example, table1 has the following columns and data:

```<code>   id   |   rate (out of 10)
=====================
   1    |    8
   2    |    10
   3    |    5
   4    |    4
   5    |    0
   6    |    9
   7    |    8
</code>```

And table2 has the following columns and data:

```<code> movid  |   userid   |   rating (out of 10)
================================
   1    |     3      |    6
   2    |     2      |    10
   3    |     1      |    4
   4    |     3      |    7
   5    |     3      |    6
   6    |     4      |    8
   7    |     3      |    5
</code>```

So lets say I want to use any rows where 'userid' = 3 and compare their 'rating' from table2 to the 'rate' column from table1 where 'rate' > 0 and id/movid from the two tables has the same number.

Using the example above, the results to compare should be limited to:

```<code>   id   |   rate
=====================
   1    |    8
   4    |    4
   7    |    8

 movid  |   userid   |   rating
================================
   1    |     3      |    6
   4    |     3      |    7
   7    |     3      |    5
</code>```

Even though userid 3 had a rating for movid 5 in table2, it had a 0 rate (no rating) for id 5 in table1, so it will not compare those.

This would compare the ratings for each id/movid and then put it into an overall total. As the rating numbers are based on a score out of 10, I'm guessing the best way to determine the similarity percentage is to take the difference between each id/movid, subtract it from 10 to get the percentage number.

For id/movid 1, 'rate' in table1 is 8 and 'rating' in table2 is 6. The difference between those numbers is 2. We subtract 2 from 10, to get 80% similarity score for id/movid 1.

That would need to happen for each comparison and then total it all together.

So by my calculation, the similarity score for id/movid 1, 4 and 7 all combined would be 73% (rounded without decimals).

This total percentage amount is the end result I am trying to achieve. Can anyone help me out? I'm now bald after all of the hair I've pulled out trying to get this to work.

答:
```<code>SELECT ROUND(SUM(10-ABS(table1.rate-table2.rating))*10/count(table1.id)) as per FROM table1 INNER JOIN table2 ON table1.id=table2.movieid WHERE userid=3 and table1.rate <> 0 GROUP BY userid
</code>```

this will gives you what you need.

Body:
What I want to do is generate a similarity percentage amount by comparing a ratings column from one table with the ratings column from another table.

However, this needs to be limited to instances where an id from one table matches an id in another table, is for a specific user and a rating exists in the ratings column from both tables.

For example, table1 has the following columns and data:

   id   |   rate (out of 10)
=====================
   1    |    8
   2    |    10
   3    |    5
   4    |    4
   5    |    0
   6    |    9
   7    |    8

And table2 has the following columns and data:

 movid  |   userid   |   rating (out of 10)
================================
   1    |     3      |    6
   2    |     2      |    10
   3    |     1      |    4
   4    |     3      |    7
   5    |     3      |    6
   6    |     4      |    8
   7    |     3      |    5

So lets say I want to use any rows where 'userid' = 3 and compare their 'rating' from table2 to the 'rate' column from table1 where 'rate' > 0 and id/movid from the two tables has the same number.

Using the example above, the results to compare should be limited to:

   id   |   rate
=====================
   1    |    8
   4    |    4
   7    |    8

 movid  |   userid   |   rating
================================
   1    |     3      |    6
   4    |     3      |    7
   7    |     3      |    5

Even though userid 3 had a rating for movid 5 in table2, it had a 0 rate (no rating) for id 5 in table1, so it will not compare those.

This would compare the ratings for each id/movid and then put it into an overall total. As the rating numbers are based on a score out of 10, I'm guessing the best way to determine the similarity percentage is to take the difference between each id/movid, subtract it from 10 to get the percentage number.

For id/movid 1, 'rate' in table1 is 8 and 'rating' in table2 is 6. The difference between those numbers is 2. We subtract 2 from 10, to get 80% similarity score for id/movid 1.

That would need to happen for each comparison and then total it all together.

So by my calculation, the similarity score for id/movid 1, 4 and 7 all combined would be 73% (rounded without decimals).

This total percentage amount is the end result I am trying to achieve. Can anyone help me out? I'm now bald after all of the hair I've pulled out trying to get this to work.

Body:
SELECT ROUND(SUM(10-ABS(table1.rate-table2.rating))*10/count(table1.id)) as per FROM table1 INNER JOIN table2 ON table1.id=table2.movieid WHERE userid=3 and table1.rate <> 0 GROUP BY userid

this will gives you what you need.


问:
SQL - AVG and Group by
I have the following table:

```<code>Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40
</code>```

I am having hard time finding a query in SQL Server that can give me this result:

```<code>Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30
</code>```

I want the average price for each product everyday

Product starting from 1.1 to 24.4

答:
Assuming every product value has a '.'(dot). Otherwise remove -1 from line 2.</p>

```<code>SELECT Date,
   LEFT(CAST(product AS VARCHAR),charindex ('.',product) - 1),
   AVG(price)
FROM TABLE
GROUP BY Date, LEFT(CAST(product AS VARCHAR),charindex ('.',product) - 1);
</code>```

Title: SQL - AVG and Group by

Body:
I have the following table:

Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40

I am having hard time finding a query in SQL Server that can give me this result:

Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30

I want the average price for each product everyday

Product starting from 1.1 to 24.4

Body:
Assuming every product value has a '.'(dot). Otherwise remove -1 from line 2.

SELECT Date,
   LEFT(CAST(product AS VARCHAR),charindex ('.',product) - 1),
   AVG(price)
FROM TABLE
GROUP BY Date, LEFT(CAST(product AS VARCHAR),charindex ('.',product) - 1);


问:
Setting LayoutParams but its not working android
Trying to create a linear layout programmatically and setting its width and height by layout params. But it seems layout params isn't working.

this is the code:

```<code> // CREATING A NEW LINEAR LAYOUT PROGRAMMATICALLY
    LinearLayout linearLayout = new LinearLayout(getActivity());
    ViewGroup.LayoutParams layoutParams = new
 ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
 ViewGroup.LayoutParams.WRAP_CONTENT);
    linearLayout.setLayoutParams(layoutParams);
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);

    // CREATING CHILDDRENS (TEXT VIEWS)
    TextView name = new TextView(getContext(), null, 0, R.style.item_layout_style);
    name.setText("Pine");
    TextView qty = new TextView(getContext(), null, 0, R.style.item_layout_style);
    qty.setText("10");
    TextView cost = new TextView(getContext(), null, 0, R.style.item_layout_style);
    cost.setText("785");
    TextView tCost = new TextView(getContext(), null, 0, R.style.item_layout_style);
    tCost.setText("1000");

    // SET TEXT VIEW TO LINEAR LAYOUT
    linearLayout.addView(name);
    linearLayout.addView(qty);
    linearLayout.addView(cost);
    linearLayout.addView(tCost);

    // SET LINEAR LAYOUT TO PINE LAYOUT
    LinearLayout daddy= (LinearLayout) view.findViewById(R.id.layout);
    daddy.addView(linearLayout, 2);

    // Return the view
    return view;
</code>```

I have root layout (daddy) which has many linear layouts (vertically oriented), but I need to create a linear layout programmatically and add that to "daddy". But the text views are sticked together, they aren't getting the entire space horizontally.

Do help me!

答: Everything is fine with the code. It is the style that I tried to give to text views, they weren't getting layout weight, width and height. How did I find this out? Well I set the linear layout's background-color to black to see if it's really not getting width and height set by LayoutParams. And I wasn't wrong! Width was set to match parent. So what I did was create a new layout param for text views and set it to them. </p>

Body:
Trying to create a linear layout programmatically and setting its width and height by layout params. But it seems layout params isn't working.

this is the code:

 // CREATING A NEW LINEAR LAYOUT PROGRAMMATICALLY
    LinearLayout linearLayout = new LinearLayout(getActivity());
    ViewGroup.LayoutParams layoutParams = new
 ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
 ViewGroup.LayoutParams.WRAP_CONTENT);
    linearLayout.setLayoutParams(layoutParams);
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);

    // CREATING CHILDDRENS (TEXT VIEWS)
    TextView name = new TextView(getContext(), null, 0, R.style.item_layout_style);
    name.setText("Pine");
    TextView qty = new TextView(getContext(), null, 0, R.style.item_layout_style);
    qty.setText("10");
    TextView cost = new TextView(getContext(), null, 0, R.style.item_layout_style);
    cost.setText("785");
    TextView tCost = new TextView(getContext(), null, 0, R.style.item_layout_style);
    tCost.setText("1000");

    // SET TEXT VIEW TO LINEAR LAYOUT
    linearLayout.addView(name);
    linearLayout.addView(qty);
    linearLayout.addView(cost);
    linearLayout.addView(tCost);

    // SET LINEAR LAYOUT TO PINE LAYOUT
    LinearLayout daddy= (LinearLayout) view.findViewById(R.id.layout);
    daddy.addView(linearLayout, 2);

    // Return the view
    return view;

I have root layout (daddy) which has many linear layouts (vertically oriented), but I need to create a linear layout programmatically and add that to "daddy". But the text views are sticked together, they aren't getting the entire space horizontally.

Do help me!

ContentLicense: CC BY-SA 4.0


问:
Complicated join in ActiveRecord
I'm having an issue with a tricky ActiveRecord query.

I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

```<code>class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false
</code>```

I'm trying to write a query that says, given a user_id, get all tasks where there is no Response from that User linked to it.

So if User 1 is querying, and he only has a Response to task 1, he should see all tasks except task 1.

答:
Try this:

```<code>Task.where('user_id != (?)', User.find(user_id).responses)
</code>```

or

```<code>Task.joins(:responses).where('responses.user_id != (?)', User.find(user_id))
</code>```

Title: Complicated join in ActiveRecord

Body:
I'm having an issue with a tricky ActiveRecord query.

I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false

I'm trying to write a query that says, given a user_id, get all tasks where there is no Response from that User linked to it.

So if User 1 is querying, and he only has a Response to task 1, he should see all tasks except task 1.

Body:
Try this:

Task.where('user_id != (?)', User.find(user_id).responses)

or

Task.joins(:responses).where('responses.user_id != (?)', User.find(user_id))


问:
Swift How to fix errors with Target Membership?
I am beginner to Swift and I am not aware of all the little details, so please forgive if it's a stupid question

My app is in quite advanced stage of development, so I would like to not mess with the existing code as little as possible. My problem is that I want to implement Today Extension in my app, in it I want to display a tableView that will display data from a single array from my "Plum" class and I need one method from the class to handle the selection. Unfortunately when I change the Plum's target membership to TodayExtension a whole bunch of errors are shown because many APIs from that class aren't available to TodayExtension. The class inherits from AVAudioPlayer so most essential methods aren't available in Extension.
I tried to create a helper class that would get the array from Plum and return it in method to my TableView but that still doesn't work because of "Use of unresolved identifier 'Plum'"

How can I obtain the array and use the method?

答:
I think while adding Today Extension you might have got some classes for today extension,

You can use App Group with User Defaults functionality to transfer data from iOS app to today Extension classes

1) To set data you can use

```<code>var defaults: NSUserDefaults = NSUserDefaults(suiteName: <GroupID>)!
defaults.setObject(<YourArray, forKey:<KeyName>)
</code>```

2) In Today Extension target's Class you can fetch that array like this

```<code>var defaults: NSUserDefaults = NSUserDefaults(suiteName: <GroupID>)!
var <YourArray> = defaults.stringForKey(<KeyName>)
</code>```

Note : This is just pseudo code might contain error

Body:
I think while adding Today Extension you might have got some classes for today extension,

You can use App Group with User Defaults functionality to transfer data from iOS app to today Extension classes

1) To set data you can use

var defaults: NSUserDefaults = NSUserDefaults(suiteName: <GroupID>)!
defaults.setObject(<YourArray, forKey:<KeyName>)

2) In Today Extension target's Class you can fetch that array like this

var defaults: NSUserDefaults = NSUserDefaults(suiteName: <GroupID>)!
var <YourArray> = defaults.stringForKey(<KeyName>)

Note : This is just pseudo code might contain error


问:
How do you create a COM DLL in Visual Studio 2008?
It's been ages since I've written a COM dll. I've made a couple of classes now, that inherit from some COM interfaces, but I want to test it out. I know I have to put a GUID somewhere and then register it with regsvr32, but what are the steps involved?

Edit: Sorry, forgot to mention I'm using C++.

答:
You need to write a function called DllGetClassObject and export it. That function is responsible for allocating a "class factory", which you also have to write, and which is in turn capable of allocating instances of your COM object. It has to implement IClassFactory.

It's not too hard to do. The alternative is to use ATL (see xhantt's answer) which in theory does this for you, but in practice it's a real mess. Somehow it manages to encapsulate the complexity of COM inside an abstraction layer that is even more complicated. Good luck trying to move an object between DLLs for example.

But you could run the ATL wizard just to see an example of how to declare DllGetClassObject. Implementing IClassFactory is very easy - just one method that news-up an object.

Then you need to register your DLL - i.e. put keys into the registry. The regsvr32 tool cannot do this without further help from you. You have to write and export another function called DllRegisterServer, which does all the hard work. All that regsvr32 does is load the DLL, look up DllRegisterServer and call it.

Again, ATL has a way of implementing this for you, but it does it by reading a kind of script full of registry modification instructions, stored in an .rgs file that gets embedded into your DLL's resources. If you accidentally put any kind of syntax error into this file, the registration fails silently.

So again, you may actually find it simpler to write a few lines of code to tweak the registry yourself. Here are the details.

If you used C# instead, you wouldn't have any of these problems. Everything is encapsulated very cleanly. It actually works much better than C++ as a tool for developing COM objects.

OwnerDisplayName: Mark Ingram

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mark Ingram

OwnerDisplayName: Earwicker


问:
How to use skpsmtpmessage?
Im trying implement an email functionality in my app without presenting a modal view. Many people have suggested using skpsmtpmessage library. Iv downloaded this library and started a new project with it just to test it, but im not having any idea on how to start out with it. What do i need to do to test this library?</p>

答:
http://mhmethun.wordpress.com/iphone/send-email-with-attaching-file-using-smtp-server/

follow above link ....i have followed above one and got result

Title: How to use skpsmtpmessage?


问:
How can I run script automatically after Docker container startup
I'm using Search Guard plugin to secure an elasticsearch cluster composed of multiple nodes.
Here is my Dockerfile:

```<code>#!/bin/sh
FROM docker.elastic.co/elasticsearch/elasticsearch:5.6.3

USER root

# Install search guard
RUN bin/elasticsearch-plugin install --batch com.floragunn:search-guard-5:5.6.3-16 \
    && chmod +x \
        plugins/search-guard-5/tools/hash.sh \
        plugins/search-guard-5/tools/sgadmin.sh \
        bin/init_sg.sh \
    && chown -R elasticsearch:elasticsearch /usr/share/elasticsearch

USER elasticsearch
</code>```

To initialize SearchGuard (create internal users and assign roles). I need to run the script init_sg.sh after the container startup.
Here is the problem: Unless elasticsearch is running, the script will not initialize any security index.

The script's content is :

```<code>sleep 10
plugins/search-guard-5/tools/sgadmin.sh -cd config/ -ts config/truststore.jks -ks config/kirk-keystore.jks -nhnv -icl
</code>```

Now, I just run the script manually after the container startup but since I'm running it on Kubernetes.. Pods may get killed or fail and get recreated automatically for some reason. In this case, the plugin have to be initialized automatically after the container startup!

So how to accomplish this? Any help or hint would be really appreciated.

答:
I would suggest to put the CMD in you docker file to execute the script when the container start

```<code>FROM debian
RUN apt-get update && apt-get install -y nano && apt-get clean
EXPOSE 8484
CMD ["/bin/bash", "/opt/your_app/init.sh"]
</code>```

There is other way , but before using this look at your requirement,

```<code>    ENTRYPOINT "put your code here" && /bin/bash
    #exemple ENTRYPOINT service nginx start && service ssh start &&/bin/bash "use && to separate your code"
</code>```

Body:
I'm using Search Guard plugin to secure an elasticsearch cluster composed of multiple nodes.
Here is my Dockerfile:

#!/bin/sh
FROM docker.elastic.co/elasticsearch/elasticsearch:5.6.3

USER root

# Install search guard
RUN bin/elasticsearch-plugin install --batch com.floragunn:search-guard-5:5.6.3-16 \
    && chmod +x \
        plugins/search-guard-5/tools/hash.sh \
        plugins/search-guard-5/tools/sgadmin.sh \
        bin/init_sg.sh \
    && chown -R elasticsearch:elasticsearch /usr/share/elasticsearch

USER elasticsearch

To initialize SearchGuard (create internal users and assign roles). I need to run the script init_sg.sh after the container startup.
Here is the problem: Unless elasticsearch is running, the script will not initialize any security index.

The script's content is :

sleep 10
plugins/search-guard-5/tools/sgadmin.sh -cd config/ -ts config/truststore.jks -ks config/kirk-keystore.jks -nhnv -icl

Now, I just run the script manually after the container startup but since I'm running it on Kubernetes.. Pods may get killed or fail and get recreated automatically for some reason. In this case, the plugin have to be initialized automatically after the container startup!

So how to accomplish this? Any help or hint would be really appreciated.

Body:
I would suggest to put the CMD in you docker file to execute the script when the container start

FROM debian
RUN apt-get update && apt-get install -y nano && apt-get clean
EXPOSE 8484
CMD ["/bin/bash", "/opt/your_app/init.sh"]

There is other way , but before using this look at your requirement,

    ENTRYPOINT "put your code here" && /bin/bash
    #exemple ENTRYPOINT service nginx start && service ssh start &&/bin/bash "use && to separate your code"


问:
how to detect collision of image views in a puzzle game
i am doing a simple  jigsaw puzzle game.

for that i crop a single image into 9 pieces and display it on 9 image views.

Now i need to detect collision when one image view is comes over the half of another image view frame,

and replace image or image view each other.

how can i done can any one please help me.

答:
You can use the CGRectIntersectsRect() function, it takes to CGRect's and returns YES if the rects intersect, otherwise NO.

Here is a short example:

```<code>if(CGRectIntersectsRect(image1.frame, image2.frame))
{
   UIImage *temp = [[image1 image] retain];
   [image1 setImage:image2.image];
   [image2 setIamge:[temp autorelease]];
}
</code>```

(It works of course easier if you have an array to iterate through)

Body:
You can use the CGRectIntersectsRect() function, it takes to CGRect's and returns YES if the rects intersect, otherwise NO.

Here is a short example:

if(CGRectIntersectsRect(image1.frame, image2.frame))
{
   UIImage *temp = [[image1 image] retain];
   [image1 setImage:image2.image];
   [image2 setIamge:[temp autorelease]];
}

(It works of course easier if you have an array to iterate through)


问:
Macro name from shape click
I have numerous sheets, all with a button which activates a macro.

With VBA, how can I pick up the name of the macro attached to the shape on each sheet?

I have the code to look at each sheet, but can't see how to get the macro name from the shape properties.

答:
```<code>Sub LoopandExamine()
Dim ws As Worksheet
Dim s As Shape
For Each ws In Worksheets
    For Each s In ws.Shapes
        If s.OnAction <> "" Then
            Debug.Print s.Name & ";" & s.OnAction
        End If
    Next s
Next ws

End Sub
</code>```

Title: Macro name from shape click


问:
what do texture2D().r and texture2D().a mean?
I am using OpenGL ES in Android programming, when I transform YUV(NV21) to RGB in shader, like:

```<code>vec3 yuv = vec3(
        (texture2D(u_TextureY, vTextureCoord).r - 0.0625),
        texture2D(u_TextureUV, vTextureCoord).a - 0.5,
        texture2D(u_TextureUV, vTextureCoord).r - 0.5
    );
</code>```

then I'll get YUV data that seperating from u_TextureY and u_TextureUV.

I know that NV21 format is like: YYYYYY...UVUV... BUT how can I transform YUYV422 to RGB?
So, my problem is what do "r" and "a" mean in texture2D(u_TextureY, vTextureCoord).r and .a ? then I can find the way to do YUYV422->RGB.

答:
The return type of texture2D is vec4. In GLSL the components of the vector can be separately accessed:

See the The OpenGL Shading Language specification:

5.5 Vector and Scalar Components and Length

The names of the components of a vector or scalar are denoted by a single letter. As a notational convenience, several letters are associated with each component based on common usage of position, color or texture coordinate vectors. The individual components can be selected by following the variable
  name with period ( . ) and then the component name.

The component names supported are:

{x, y, z, w} Useful when accessing vectors that represent points or normals

{r, g, b, a} Useful when accessing vectors that represent colors

{s, t, p, q} Useful when accessing vectors that represent texture coordinates

The order of the components can be different to swizzle them, or replicated:

```<code>vec4 pos = vec4(1.0, 2.0, 3.0, 4.0);
vec4 swiz= pos.wzyx; // swiz = (4.0, 3.0, 2.0, 1.0)
vec4 dup = pos.xxyy; // dup = (1.0, 1.0, 2.0, 2.0)
float f = 1.2;
vec4 dup = f.xxxx; // dup = (1.2, 1.2, 1.2, 1.2)
</code>```

This means, that .r gives the 1st component of the vec4 and .a gives the 4th component of the vec4.

Body:
I am using OpenGL ES in Android programming, when I transform YUV(NV21) to RGB in shader, like:

vec3 yuv = vec3(
        (texture2D(u_TextureY, vTextureCoord).r - 0.0625),
        texture2D(u_TextureUV, vTextureCoord).a - 0.5,
        texture2D(u_TextureUV, vTextureCoord).r - 0.5
    );

then I'll get YUV data that seperating from u_TextureY and u_TextureUV.

I know that NV21 format is like: YYYYYY...UVUV... BUT how can I transform YUYV422 to RGB?
So, my problem is what do "r" and "a" mean in texture2D(u_TextureY, vTextureCoord).r and .a ? then I can find the way to do YUYV422->RGB.

Body:
The return type of texture2D is vec4. In GLSL the components of the vector can be separately accessed:

See the The OpenGL Shading Language specification:

5.5 Vector and Scalar Components and Length

The names of the components of a vector or scalar are denoted by a single letter. As a notational convenience, several letters are associated with each component based on common usage of position, color or texture coordinate vectors. The individual components can be selected by following the variable
  name with period ( . ) and then the component name.

The component names supported are:

{x, y, z, w} Useful when accessing vectors that represent points or normals

{r, g, b, a} Useful when accessing vectors that represent colors

{s, t, p, q} Useful when accessing vectors that represent texture coordinates

The order of the components can be different to swizzle them, or replicated:

vec4 pos = vec4(1.0, 2.0, 3.0, 4.0);
vec4 swiz= pos.wzyx; // swiz = (4.0, 3.0, 2.0, 1.0)
vec4 dup = pos.xxyy; // dup = (1.0, 1.0, 2.0, 2.0)
float f = 1.2;
vec4 dup = f.xxxx; // dup = (1.2, 1.2, 1.2, 1.2)

This means, that .r gives the 1st component of the vec4 and .a gives the 4th component of the vec4.


问:
Disable Discount Coupon on Products with Promotional Price
Personal is there any way of not letting a discount coupon be used on products that already have a promotional price since I needed to create a discount coupon where it will give a 20% discount on my entire site but it can not be used on products that have one promotional discount on my site can someone help me please

Here are the options I currently have in my coupon:

This is a product with a promotional price:

Is there a free module or some solution via source code or directly in the database?

答:
In catalog/model/total/coupon.php

before the line with 'if ($status) {' add this code

```<code>foreach ($this->cart->getProducts() as $product) {
        $product_special_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "product_special_category` WHERE `product_id` = '" . (int)$product['product_id'] . "'");

        if ($product_special_query->row['total']) {
            $status = false;
            break;
        }
    }
</code>```

try it, the file path may change based on the version you're using.

Body:
In catalog/model/total/coupon.php

before the line with 'if ($status) {' add this code

foreach ($this->cart->getProducts() as $product) {
        $product_special_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "product_special_category` WHERE `product_id` = '" . (int)$product['product_id'] . "'");

        if ($product_special_query->row['total']) {
            $status = false;
            break;
        }
    }

try it, the file path may change based on the version you're using.


问:
Hyperlink combined with pseudo code
In the code below, how can I have the same font color for the hyperlinks as for the other text? It now seems to morph with the color as defined in the pseudo code.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="header-logo">
    <img src="http://via.placeholder.com/50x50" alt="" />
  </div>
  <ul>
    <li>Option1</li>
    <li>Option2</li>
    <li class="header-button">Option3</li>
    <li class="header-button">Option4</li>
  </ul>
</nav></code>```

答:
Just add this to your css, so your element would be under your text.</p>

```<code>nav>ul>li.header-button::before {
    z-index: -1;
}
</code>```

Title: Hyperlink combined with pseudo code

Body:
In the code below, how can I have the same font color for the hyperlinks as for the other text? It now seems to morph with the color as defined in the pseudo code.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}

Option1

Option2

Option3

Option4

Body:
Just add this to your css, so your element would be under your text.

nav>ul>li.header-button::before {
    z-index: -1;
}


问:
Asp.net mvc3: How to pull data from database and fill view model in one goal?
I need to pull the data from DB and fill the view model, is there any better way to do this?
Currently I'm doing something like this.</p>

```<code>ViewModel vm = new ViewModel();
var recentBill = context.Money.Take(10);
foreach (var r in recnetBill)
{
    vm.lst.Add(r);
}
</code>```

答:
I would recommend you to prevent possibility of changing ViewModel.lst, i.e. lst's type should be IEnumerable instead of List/IList (of course if your further code doesn't require List functionality).

Furthermore, I suppose you don't modify lst reference, so you could remove setter and initialize lst via constructor.

```<code>    public class ViewModel
    {
        public ViewModel(IEnumerable<Money> lst)
        {
            this._lst = lst;
        }

        private readonly IEnumerable<Money> _lst;
        IEnumerable<Money> Lst
        {
            get
            {
                return this._lst;
            }
        }
        // other properties
    }

    public ActionResult GetMonies()
    {
        var model = new ViewModel(context.Money.Take(10).ToArray());
        return View(model);
    }
</code>```

This approach guarantees that consumers of your code will not modify your ViewModel.Lst accidentally.

Body:
I need to pull the data from DB and fill the view model, is there any better way to do this?
Currently I'm doing something like this.

ViewModel vm = new ViewModel();
var recentBill = context.Money.Take(10);
foreach (var r in recnetBill)
{
    vm.lst.Add(r);
}

Body:
I would recommend you to prevent possibility of changing ViewModel.lst, i.e. lst's type should be IEnumerable instead of List/IList (of course if your further code doesn't require List functionality).

Furthermore, I suppose you don't modify lst reference, so you could remove setter and initialize lst via constructor.

    public class ViewModel
    {
        public ViewModel(IEnumerable<Money> lst)
        {
            this._lst = lst;
        }

        private readonly IEnumerable<Money> _lst;
        IEnumerable<Money> Lst
        {
            get
            {
                return this._lst;
            }
        }
        // other properties
    }

    public ActionResult GetMonies()
    {
        var model = new ViewModel(context.Money.Take(10).ToArray());
        return View(model);
    }

This approach guarantees that consumers of your code will not modify your ViewModel.Lst accidentally.


问:
Android Studio 3.0 shortcut SHIFT + ESCAPE not closing run view?
I'm using Android Studio 3.0 and operating system version is MacOs High Sierra Version 10.13.1.

I have an issue where SHIFT+ESCAPE command is not a closing Run window in Android Studio. I tried different key mappings, but it also doesn't work. Click on the close button does work.

Other AS setup params that might clarify the situation:

Android Studio keymaps: Mac OS X 10.5+

Run window is in floating mode.

Is this some known Android Studio bug or it might be that my OS is intercepting commands?

Any help appreciated, thanks in advance.

答: So, the keystroke from Android Studio 2.x stopped working in 3.0. Looks like a bug in Android Studio 3.0 as it works for me in Android Studio 2.3.2 on the same macOS version.</p>


问:
How to get List of Audio Soundcards and Drivers of PC using Java
How can I get the list of Soundcards and Audio Drivers of PC in java. OS, I am currently using is Windows.
I would be grateful if I could get some assistance in this regards.</p>

答:
May be here... https://docs.oracle.com/javase/tutorial/sound/accessing.html</p>

```<code>Mixer.Info[] infos = AudioSystem.getMixerInfo();
    for (int i = 0; i < infos.length; i++) {
        Mixer.Info info = infos[i];

        System.out.println(String.format("Name [%s], description - [%s]\n", info.getName(), info.getDescription()));
        System.out.println(info.getDescription());
    }
</code>```

Body:
May be here... https://docs.oracle.com/javase/tutorial/sound/accessing.html

Mixer.Info[] infos = AudioSystem.getMixerInfo();
    for (int i = 0; i < infos.length; i++) {
        Mixer.Info info = infos[i];

        System.out.println(String.format("Name [%s], description - [%s]\n", info.getName(), info.getDescription()));
        System.out.println(info.getDescription());
    }


问:
unexpected token error in hibernate with Java
I have Route Entity class and when I'm going to fetch all the data from that table in HQL query I get an error for a only one column.

Route.class :-

```<code>@Entity
public class Route {

    @Id
    private long routeID;

    private String start;
    private String end;
    private String routeNo;
    private double startLat;
    private double startLon;
    private double endLat;
    private double endLon;
}
</code>```

DataFetch.Class :-

```<code>public class DataFetch{

    public void FetchRoutes(){

        Query q = session.createQuery("select routeID,routeNo,start,end from Route ");
        List<Object[]> routes = (List<Object[]>) q.list();

        for (Object[] r : routes) {
            System.out.println("id: "+r[0]);
            System.out.println("No: "+r[1]);
            System.out.println("start: "+r[2]);
            System.out.println("end: "+r[3]);
        }
    }
}
</code>```

In DataFetch.class if i remove "end" column from the query q there are no errors. but if i add end again as shown this question,it will give an error.
below I show my error as a screen shot.

Click here to see my Error

What is the problem?

答:
End is probably a reserved word.

But, why not just use Hibernate for what it's worth, and skip the whole manual row mapping thing:

```<code>TypedQuery q = em.createQuery("select r from Route r", Route.class);
List<Route> routes = q.getResultList();
</code>```

Example with em and typed query, since it gives a prettier result. The same can be done with session and a cast..

Body:
I have Route Entity class and when I'm going to fetch all the data from that table in HQL query I get an error for a only one column.

Route.class :-

@Entity
public class Route {

    @Id
    private long routeID;

    private String start;
    private String end;
    private String routeNo;
    private double startLat;
    private double startLon;
    private double endLat;
    private double endLon;
}

DataFetch.Class :-

public class DataFetch{

    public void FetchRoutes(){

        Query q = session.createQuery("select routeID,routeNo,start,end from Route ");
        List<Object[]> routes = (List<Object[]>) q.list();

        for (Object[] r : routes) {
            System.out.println("id: "+r[0]);
            System.out.println("No: "+r[1]);
            System.out.println("start: "+r[2]);
            System.out.println("end: "+r[3]);
        }
    }
}

In DataFetch.class if i remove "end" column from the query q there are no errors. but if i add end again as shown this question,it will give an error.
below I show my error as a screen shot.

Click here to see my Error

What is the problem?

Body:
End is probably a reserved word.

But, why not just use Hibernate for what it's worth, and skip the whole manual row mapping thing:

TypedQuery q = em.createQuery("select r from Route r", Route.class);
List<Route> routes = q.getResultList();

Example with em and typed query, since it gives a prettier result. The same can be done with session and a cast..


问:
How to get the JSON error response and toast it?
Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.

```<code>public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;

Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    signupInputName = (EditText) findViewById(R.id.signup_input_name);
    signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
    signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
    retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);

    btnSignUp = (Button) findViewById(R.id.btn_signup);
    btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

    btnSignUp.setOnClickListener(this);

    btnLinkLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getApplicationContext(),LoginActivity.class);
            startActivity(i);
        }
    });
}

public String POST(String url, Person person)
{
    InputStream inputStream = null;
    String result = "";

    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httppost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("user_name", person.getUsername());
        jsonObject.accumulate("email", person.getEmail());
        jsonObject.accumulate("password", person.getPassword());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httppost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httppost.setHeader("Accept", "application/json");
        httppost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httppost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Error! email exist";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

@Override
public void onClick(View view) {
    if(validate() == 1)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 2)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 3)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 4)
    {
        //Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
        new HttpAsyncTask().execute("http://ip-addressses/api/register");
    }

}

private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... urls) {

        person = new Person();
        person.setUsername(signupInputName.getText().toString());
        person.setEmail(signupInputEmail.getText().toString());
        person.setPassword(signupInputPassword.getText().toString());

        return POST(urls[0],person);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        JSONObject jObject;

        try {
            jObject = new JSONObject(result);
            if (jObject.has("error")) {
                String aJsonString = jObject.getString("error");
                Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
}

private int validate() {
    if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
    {
        code = 1;
        message = "Complete the form!";
    }
    else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
    {
        code = 2;
        message = "Re-check password";
    }
    else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
        code = 3;
        message = "Invalid email";
    }
    else
        code = 4;

    return code;
}

public final static boolean isValidEmail(String target)
{
    if (target == null) {
        return false;
    } else {
        Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
        return match.matches();
    }
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}
}
</code>```

Postman response when email exist

答:
Just change this code:

```<code>  jObject = new JSONObject(result);
  if (jObject.has("error"))
  {
      String aJsonString = jObject.getString("error");
      Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
  }
  else
  {
      Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
  }
  }
  catch (JSONException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
      Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
   }
</code>```

So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.

Body:
Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;

Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    signupInputName = (EditText) findViewById(R.id.signup_input_name);
    signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
    signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
    retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);

    btnSignUp = (Button) findViewById(R.id.btn_signup);
    btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

    btnSignUp.setOnClickListener(this);

    btnLinkLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getApplicationContext(),LoginActivity.class);
            startActivity(i);
        }
    });
}

public String POST(String url, Person person)
{
    InputStream inputStream = null;
    String result = "";

    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httppost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("user_name", person.getUsername());
        jsonObject.accumulate("email", person.getEmail());
        jsonObject.accumulate("password", person.getPassword());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httppost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httppost.setHeader("Accept", "application/json");
        httppost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httppost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Error! email exist";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

@Override
public void onClick(View view) {
    if(validate() == 1)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 2)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 3)
    {
        Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
    }
    else if (validate() == 4)
    {
        //Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
        new HttpAsyncTask().execute("http://ip-addressses/api/register");
    }

}

private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... urls) {

        person = new Person();
        person.setUsername(signupInputName.getText().toString());
        person.setEmail(signupInputEmail.getText().toString());
        person.setPassword(signupInputPassword.getText().toString());

        return POST(urls[0],person);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        JSONObject jObject;

        try {
            jObject = new JSONObject(result);
            if (jObject.has("error")) {
                String aJsonString = jObject.getString("error");
                Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
}

private int validate() {
    if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
    {
        code = 1;
        message = "Complete the form!";
    }
    else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
    {
        code = 2;
        message = "Re-check password";
    }
    else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
        code = 3;
        message = "Invalid email";
    }
    else
        code = 4;

    return code;
}

public final static boolean isValidEmail(String target)
{
    if (target == null) {
        return false;
    } else {
        Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
        return match.matches();
    }
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}
}

Postman response when email exist

Body:
Just change this code:

  jObject = new JSONObject(result);
  if (jObject.has("error"))
  {
      String aJsonString = jObject.getString("error");
      Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
  }
  else
  {
      Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
  }
  }
  catch (JSONException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
      Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
   }

So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.


答:
End is a reserved keyword so you either escape it or use table alias in select</p>

```<code>"select r.routeID, r.routeNo, r.start, r.end from Route r"
</code>```

Title: unexpected token error in hibernate with Java

Body:
End is a reserved keyword so you either escape it or use table alias in select

"select r.routeID, r.routeNo, r.start, r.end from Route r"


问:
Php - format double-quoted string from a class
I have a class that build my main navigation. Everything works fine except for the html output i get in the source code. In my class i got something like this:

```<code>public function getNav(){
   $output = "";
   foreach($nav as $key=>$value){
       $output .= "<li><a href='$value'>$key</a></li>\n";
   }
   return $output;
}
</code>```

Then i show navigation in my template...

```<code>    <ul class="nav">
    <?php echo $site->getNav(); ?>
    </ul>
</code>```

... and the html source look like this:

```<code>     <ul id="nav">
           <li><a href='index.php'><span>HOME</span></a></li>
<li><a href='page2.php'><span>PAGE 2</span></a></li>
<li><a href='page3.php'><span>PAGE 3</span></a></li>
     </ul>
</code>```

This is probably irrelevant, i'm just trying to understand if i get this due to the double quoted or what...

答:
This output has nothing to do with the doublequotes(except the linebreak, which you wouldn't have without them).

Are you sure that your template is

```<code>    <ul class="nav">
    <?php echo $site->getNav(); ?>
    </ul>
</code>```

...and not

```<code>    <ul class="nav">
          <?php echo $site->getNav(); ?>
    </ul>
</code>```

?
That's the only mysterious thing I see.

Body:
I have a class that build my main navigation. Everything works fine except for the html output i get in the source code. In my class i got something like this:

public function getNav(){
   $output = "";
   foreach($nav as $key=>$value){
       $output .= "
$key
\n";
   }
   return $output;
}

Then i show navigation in my template...

    <?php echo $site->getNav(); ?>

... and the html source look like this:

HOME

PAGE 2

PAGE 3

This is probably irrelevant, i'm just trying to understand if i get this due to the double quoted or what...

Body:
This output has nothing to do with the doublequotes(except the linebreak, which you wouldn't have without them).

Are you sure that your template is

    <ul class="nav">
    <?php echo $site->getNav(); ?>
    </ul>

...and not

    <ul class="nav">
          <?php echo $site->getNav(); ?>
    </ul>

?
That's the only mysterious thing I see.