问:
How to process a github webhook payload in Jenkins?
I'm currently triggering my Jenkins builds through a GitHub webhook. How would I parse the JSON payload? If I try to parameterize my build and use the $payload variable, the GitHub webhook fails with the following error:

```<code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 400 This page expects a form submission</title>
</head>
<body><h2>HTTP ERROR 400</h2>
<p>Problem accessing /job/Jumph-CycleTest/build. Reason:
```    This page expects a form submission```</p><hr /><i><small>Powered by Jetty://</small></i><br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>

</body>
</html>
</code>```

How can I get my GitHub webhook to work with a parameterized Jenkins build, and how could I then parse the webhook payload to use certain lines, such as the username of the committer, as conditionals in the build?

答:
There is a Generic Webhook Trigger plugin that can contribute values from the post content to the build.

If the post content is:

```<code>{
   "app":{
      "name":"GitHub API",
      "url":"http://developer.github.com/v3/oauth/#oauth-authorizations-api"
   }
}
</code>```

You can configure it like this:

And when triggering with some post content:

```<code>curl -v -H "Content-Type: application/json" -X POST -d '{ "app":{ "name":"GitHub API", "url":"http://developer.github.com/v3/oauth/" }}' http://localhost:8080/jenkins/generic-webhook-trigger/invoke?token=sometoken
</code>```

It will resolv variables and make them available in the build job.

```<code>{
   "status":"ok",
   "data":{
      "triggerResults":{
         "free":{
            "id":2,
            "regexpFilterExpression":"",
            "regexpFilterText":"",
            "resolvedVariables":{
               "app_name":"GitHub API",
               "everything_app_url":"http://developer.github.com/v3/oauth/",
               "everything":"{\"app\":{\"name\":\"GitHub API\",\"url\":\"http://developer.github.com/v3/oauth/\"}}",
               "everything_app_name":"GitHub API"
            },
            "searchName":"",
            "searchUrl":"",
            "triggered":true,
            "url":"queue/item/2/"
         }
      }
   }
}
</code>```

Body:
I'm currently triggering my Jenkins builds through a GitHub webhook. How would I parse the JSON payload? If I try to parameterize my build and use the $payload variable, the GitHub webhook fails with the following error:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 400 This page expects a form submission</title>

HTTP ERROR 400

Problem accessing /job/Jumph-CycleTest/build. Reason:

    This page expects a form submission

Powered by Jetty://

How can I get my GitHub webhook to work with a parameterized Jenkins build, and how could I then parse the webhook payload to use certain lines, such as the username of the committer, as conditionals in the build?

Body:
There is a Generic Webhook Trigger plugin that can contribute values from the post content to the build.

If the post content is:

{
   "app":{
      "name":"GitHub API",
      "url":"http://developer.github.com/v3/oauth/#oauth-authorizations-api"
   }
}

You can configure it like this:

And when triggering with some post content:

curl -v -H "Content-Type: application/json" -X POST -d '{ "app":{ "name":"GitHub API", "url":"http://developer.github.com/v3/oauth/" }}' http://localhost:8080/jenkins/generic-webhook-trigger/invoke?token=sometoken

It will resolv variables and make them available in the build job.

{
   "status":"ok",
   "data":{
      "triggerResults":{
         "free":{
            "id":2,
            "regexpFilterExpression":"",
            "regexpFilterText":"",
            "resolvedVariables":{
               "app_name":"GitHub API",
               "everything_app_url":"http://developer.github.com/v3/oauth/",
               "everything":"{\"app\":{\"name\":\"GitHub API\",\"url\":\"http://developer.github.com/v3/oauth/\"}}",
               "everything_app_name":"GitHub API"
            },
            "searchName":"",
            "searchUrl":"",
            "triggered":true,
            "url":"queue/item/2/"
         }
      }
   }
}


来源: stackexchange

问:
Single point crossover
I have two array(matrix with one row) temp1 and temp2 as follow:

```<code>temp1=[1 2 3 4 5 6 7 8 9]
temp2=[10 11 12 13 14 15 16 17 18]
</code>```

and I have an index pn=3. I need output as follows:

```<code>tempNew=[1 2 3 13 14 15 16 17 18]
</code>```

i.e. how do I create tempNew such that all values on indices up to pn come from temp1 and all values beyond index pn come from temp2?

答:
```<code>temp1=[1 2 3 4 5 6 7 8 9]
temp2=[10 11 12 13 14 15 16 17 18]
pn=3;
tempNew = [temp1(1:pn),temp2(pn+1:end)]
tempNew =
     1     2     3    13    14    15    16    17    18
</code>```

You use pn to create two temporary arrays to index both of your tempX arrays. Then simply concatenate them using square brackets.

Indexing always starts at 1 in MATLAB, so 1:pn will give you the first pn values of an array. end signifies the end of an array, so pn+1:end will give you all values from index pn+1 up to the last one of an array.

ContentLicense: CC BY-SA 3.0

Title: Single point crossover

Body:
I have two array(matrix with one row) temp1 and temp2 as follow:

temp1=[1 2 3 4 5 6 7 8 9]
temp2=[10 11 12 13 14 15 16 17 18]

and I have an index pn=3. I need output as follows:

tempNew=[1 2 3 13 14 15 16 17 18]

i.e. how do I create tempNew such that all values on indices up to pn come from temp1 and all values beyond index pn come from temp2?

Body:
temp1=[1 2 3 4 5 6 7 8 9]
temp2=[10 11 12 13 14 15 16 17 18]
pn=3;
tempNew = [temp1(1:pn),temp2(pn+1:end)]
tempNew =
     1     2     3    13    14    15    16    17    18

You use pn to create two temporary arrays to index both of your tempX arrays. Then simply concatenate them using square brackets.

Indexing always starts at 1 in MATLAB, so 1:pn will give you the first pn values of an array. end signifies the end of an array, so pn+1:end will give you all values from index pn+1 up to the last one of an array.


问:
Split string into array in Python
I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

答:
Assuming your elements never end or start with spaces or square brackets, you could just strip them out (the bracket can be stripped out before splitting):

```<code>arr = [ x.strip() for x in string.strip('[]').split(',') ]
</code>```

It gives as expected

```<code>print (arr)
['abcd', 'abc', 'a', 'b', 'abc']
</code>```

The nice part with strip is that it leaves all inner characters untouched. With:

```<code>string = "[ab cd, a[b]c, a, b, abc]"
</code>```

You get: ['ab cd', 'a[b]c', 'a', 'b', 'abc']

Title: Split string into array in Python

Body:
Assuming your elements never end or start with spaces or square brackets, you could just strip them out (the bracket can be stripped out before splitting):

arr = [ x.strip() for x in string.strip('[]').split(',') ]

It gives as expected

print (arr)
['abcd', 'abc', 'a', 'b', 'abc']

The nice part with strip is that it leaves all inner characters untouched. With:

string = "[ab cd, a[b]c, a, b, abc]"

You get: ['ab cd', 'a[b]c', 'a', 'b', 'abc']


问:
How to prevent element from exceeding his container borders
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}</code>```

```

答:
With CSS calc, limit the position inside playSpace area (you can use different units, here % and px).

Then with offsetTop/offsetLeft, get the real position of the square and avoid negative positions (when positionTop < 100px or positionLeft < 100px).

function position() {
    var positionTop = Math.random() * 100;
    var positionLeft = Math.random() * 100;
    var position = "position:relative;top: calc(" + positionTop + "% - 100px);left: calc(" + positionLeft + "% - 100px);";
    return position;
}

document.getElementById("shape").onclick = function() {
    var shapeDiv = document.getElementById("shape");
    shapeDiv.style.cssText = position();
    var top = shapeDiv.offsetTop;// Result of calc(" + positionTop + "% - 100px) in px
    if(top < 0) {
        shapeDiv.style.top = '0px';
    }
    var left = shapeDiv.offsetLeft;// Result of calc(" + positionLeft + "% - 100px) in px
    if(left < 0) {
        shapeDiv.style.left = '0px';
    }
}
```

<p>Don't forget to add <code>position: relative</code> to <code>#playSpace</code>, to get offsetTop/left correct</p>

<pre class="lang-css prettyprint-override"><code>#playSpace {
    position:relative;/* mandatory */
}
</code>```

Body:
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}

#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}

Body:
With CSS calc, limit the position inside playSpace area (you can use different units, here % and px).

Then with offsetTop/offsetLeft, get the real position of the square and avoid negative positions (when positionTop < 100px or positionLeft < 100px).

function position() {
    var positionTop = Math.random() * 100;
    var positionLeft = Math.random() * 100;
    var position = "position:relative;top: calc(" + positionTop + "% - 100px);left: calc(" + positionLeft + "% - 100px);";
    return position;
}

document.getElementById("shape").onclick = function() {
    var shapeDiv = document.getElementById("shape");
    shapeDiv.style.cssText = position();
    var top = shapeDiv.offsetTop;// Result of calc(" + positionTop + "% - 100px) in px
    if(top < 0) {
        shapeDiv.style.top = '0px';
    }
    var left = shapeDiv.offsetLeft;// Result of calc(" + positionLeft + "% - 100px) in px
    if(left < 0) {
        shapeDiv.style.left = '0px';
    }
}

Don't forget to add position: relative to #playSpace, to get offsetTop/left correct

#playSpace {
    position:relative;/* mandatory */
}


问:
HTML slider with two inputs possible?
Is it possible to make a HTML5 slider with two input values, for example to select a price range? If so, how can it be done?</p>

答:
Sure you can simply use two sliders overlaying each other and add  a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.

Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.

It uses JQuery but a vanillajs version is no magic though.

@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.

    (function() {

        function addSeparator(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
            }
            return x1 + x2;
        }

        function rangeInputChangeEventHandler(e){
            var rangeGroup = $(this).attr('name'),
                minBtn = $(this).parent().children('.min'),
                maxBtn = $(this).parent().children('.max'),
                range_min = $(this).parent().children('.range_min'),
                range_max = $(this).parent().children('.range_max'),
                minVal = parseInt($(minBtn).val()),
                maxVal = parseInt($(maxBtn).val()),
                origin = $(this).context.className;

            if(origin === 'min' && minVal > maxVal-5){
                $(minBtn).val(maxVal-5);
            }
            var minVal = parseInt($(minBtn).val());
            $(range_min).html(addSeparator(minVal*1000) + ' €');

            if(origin === 'max' && maxVal-5 < minVal){
                $(maxBtn).val(5+ minVal);
            }
            var maxVal = parseInt($(maxBtn).val());
            $(range_max).html(addSeparator(maxVal*1000) + ' €');
        }

     $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
  width: 210px;
  height: 30px;
  overflow: hidden;
  cursor: pointer;
    outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
    background: none;
}
input[type='range']::-webkit-slider-runnable-track {
  width: 200px;
  height: 1px;
  background: #003D7C;
}

input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
  background: none;
}

input[type='range']::-webkit-slider-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

input[type='range']:nth-child(1)::-webkit-slider-thumb{
  z-index: 2;
}

.rangeslider{
    position: relative;
    height: 60px;
    width: 210px;
    display: inline-block;
    margin-top: -5px;
    margin-left: 20px;
}
.rangeslider input{
    position: absolute;
}
.rangeslider{
    position: absolute;
}

.rangeslider span{
    position: absolute;
    margin-top: 30px;
    left: 0;
}

.rangeslider .right{
   position: relative;
   float: right;
   margin-right: -5px;
}

/* Proof of concept for Firefox */
@-moz-document url-prefix() {
  .rangeslider::before{
    content:'';
    width:100%;
    height:2px;
    background: #003D7C;
    display:block;
    position: relative;
    top:16px;
  }

  input[type='range']:nth-child(1){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }

  input[type='range']:nth-child(2){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }
input[type='range']::-moz-range-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

  input[type='range']:nth-child(1)::-moz-range-thumb {
      transform: translateY(-20px);
  }
  input[type='range']:nth-child(2)::-moz-range-thumb {
      transform: translateY(-20px);
  }
}</code>```

                                <input class="min" name="range_1" type="range" min="1" max="100" value="10" />
                                <input class="max" name="range_1" type="range" min="1" max="100" value="90" />
                                10.000 €
                                90.000 €

```

ContentLicense: CC BY-SA 4.0

Title: HTML slider with two inputs possible?

Body:
Sure you can simply use two sliders overlaying each other and add  a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.

Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.

It uses JQuery but a vanillajs version is no magic though.

@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.

    (function() {

        function addSeparator(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
            }
            return x1 + x2;
        }

        function rangeInputChangeEventHandler(e){
            var rangeGroup = $(this).attr('name'),
                minBtn = $(this).parent().children('.min'),
                maxBtn = $(this).parent().children('.max'),
                range_min = $(this).parent().children('.range_min'),
                range_max = $(this).parent().children('.range_max'),
                minVal = parseInt($(minBtn).val()),
                maxVal = parseInt($(maxBtn).val()),
                origin = $(this).context.className;

            if(origin === 'min' && minVal > maxVal-5){
                $(minBtn).val(maxVal-5);
            }
            var minVal = parseInt($(minBtn).val());
            $(range_min).html(addSeparator(minVal*1000) + ' €');

            if(origin === 'max' && maxVal-5 < minVal){
                $(maxBtn).val(5+ minVal);
            }
            var maxVal = parseInt($(maxBtn).val());
            $(range_max).html(addSeparator(maxVal*1000) + ' €');
        }

     $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();

body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
  width: 210px;
  height: 30px;
  overflow: hidden;
  cursor: pointer;
    outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
    background: none;
}
input[type='range']::-webkit-slider-runnable-track {
  width: 200px;
  height: 1px;
  background: #003D7C;
}

input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
  background: none;
}

input[type='range']::-webkit-slider-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

input[type='range']:nth-child(1)::-webkit-slider-thumb{
  z-index: 2;
}

.rangeslider{
    position: relative;
    height: 60px;
    width: 210px;
    display: inline-block;
    margin-top: -5px;
    margin-left: 20px;
}
.rangeslider input{
    position: absolute;
}
.rangeslider{
    position: absolute;
}

.rangeslider span{
    position: absolute;
    margin-top: 30px;
    left: 0;
}

.rangeslider .right{
   position: relative;
   float: right;
   margin-right: -5px;
}

/* Proof of concept for Firefox */
@-moz-document url-prefix() {
  .rangeslider::before{
    content:'';
    width:100%;
    height:2px;
    background: #003D7C;
    display:block;
    position: relative;
    top:16px;
  }

  input[type='range']:nth-child(1){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }

  input[type='range']:nth-child(2){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }
input[type='range']::-moz-range-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

  input[type='range']:nth-child(1)::-moz-range-thumb {
      transform: translateY(-20px);
  }
  input[type='range']:nth-child(2)::-moz-range-thumb {
      transform: translateY(-20px);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
                                <input class="min" name="range_1" type="range" min="1" max="100" value="10" />
                                <input class="max" name="range_1" type="range" min="1" max="100" value="90" />
                                <span class="range_min light left">10.000 €</span>
                                <span class="range_max light right">90.000 €</span>
                            </div>


问:
Finding difference of two columns with where clause - MySQL
I'm trying to get the difference of two columns(OTHER AND SENIOR) with WHERE clause along with the Sum of their amount. The formulas are working fine, however, I'm not getting the result I want.

I tried to do it using INNER JOIN and unfortunately its not the result that I expected

Here's my query:

```<code>select a.ID as EMPLOYEE,
sum(a.amount) as other,
sum(b.amount) as senior,
(sum(a.amount) - sum(b.amount)) as result
from gndsale a
INNER join gndsale
b ON a.ID= b.ID
where a.TYPE = "5" and b.seniortype = "10"
group by a.ID
</code>```

Result:

What I want to do is get the difference of Column (Other) where type = 5 and Column (Senior)  where seniortype = 10

Here is my query for Senior:

```<code> select ID as EMPLOYEE, sum(amount)
 from gndsale
 where seniortype = "10"
 group by ID
</code>```

Result:

Here is my query for Other:

```<code>select ID as employee, sum(amount)
from gndsale
where type = "5"
group by ID
</code>```

The result should be

9907 = 530

9912 = 63.71

Anyone can help me with this? :(

Sample/Expected output:

答:
You have chosen a very bad name for the column. In spite of its name ID is not an ID to identify a record in the table.

You are probably looking for something like the following, an aggregation per ID where you sum type 5 and seniortype 10 separately:

```<code>select
  a.ID as employee,
  coalesce(sum(case when type = 5 then amount end), 0) as other,
  coalesce(sum(case when seniortype = 10 then amount end), 0) as senior,
  coalesce(sum(case when type = 5 then amount end), 0) -
  coalesce(sum(case when seniortype = 10 then amount end), 0) as result
from gndsale
group by a.id
having sum(type = 5) > 0 and sum(seniortype = 10) > 0;
</code>```

(The HAVING clause ensures only to get IDs that have both records with type = 5 and seniortype = 10. We use MySQL's true = 1 / false = 0 here. Remove it, if you want other IDs, too. If you keep it and value cannot be null, then you can remove the coalesces instead.)

Body:
I'm trying to get the difference of two columns(OTHER AND SENIOR) with WHERE clause along with the Sum of their amount. The formulas are working fine, however, I'm not getting the result I want.

I tried to do it using INNER JOIN and unfortunately its not the result that I expected

Here's my query:

select a.ID as EMPLOYEE,
sum(a.amount) as other,
sum(b.amount) as senior,
(sum(a.amount) - sum(b.amount)) as result
from gndsale a
INNER join gndsale
b ON a.ID= b.ID
where a.TYPE = "5" and b.seniortype = "10"
group by a.ID

Result:

What I want to do is get the difference of Column (Other) where type = 5 and Column (Senior)  where seniortype = 10

Here is my query for Senior:

 select ID as EMPLOYEE, sum(amount)
 from gndsale
 where seniortype = "10"
 group by ID

Result:

Here is my query for Other:

select ID as employee, sum(amount)
from gndsale
where type = "5"
group by ID

The result should be

9907 = 530

9912 = 63.71

Anyone can help me with this? :(

Sample/Expected output:

Body:
You have chosen a very bad name for the column. In spite of its name ID is not an ID to identify a record in the table.

You are probably looking for something like the following, an aggregation per ID where you sum type 5 and seniortype 10 separately:

select
  a.ID as employee,
  coalesce(sum(case when type = 5 then amount end), 0) as other,
  coalesce(sum(case when seniortype = 10 then amount end), 0) as senior,
  coalesce(sum(case when type = 5 then amount end), 0) -
  coalesce(sum(case when seniortype = 10 then amount end), 0) as result
from gndsale
group by a.id
having sum(type = 5) > 0 and sum(seniortype = 10) > 0;

(The HAVING clause ensures only to get IDs that have both records with type = 5 and seniortype = 10. We use MySQL's true = 1 / false = 0 here. Remove it, if you want other IDs, too. If you keep it and value cannot be null, then you can remove the coalesces instead.)


问:
add Javadoc for hibernate in netbeans
How to add javadoc in netbeans

mainly me using it for spring hibernate. Its not showing help and saying Javadoc not found

How to add doc for org.hibernate

When selecting a function it is showing like this

```<code>    Javadoc not found. Either Javadoc documentation for this item does not exist or
  you have not added specified Javadoc in the Java Platform Manager or the Library Manager.
</code>```

答:
First you need to download the source and Javadocs for the Hibernate, the version you are using. You can easily find that by searching over the internet. After saving the docs and source on the disk some where appropriate,

Go to project properties -> libraries -> select hibernate JAR -> click Edit -> browse to Javadocs and Source.

Title: add Javadoc for hibernate in netbeans

Body:
How to add javadoc in netbeans

mainly me using it for spring hibernate. Its not showing help and saying Javadoc not found

How to add doc for org.hibernate

When selecting a function it is showing like this

    Javadoc not found. Either Javadoc documentation for this item does not exist or
  you have not added specified Javadoc in the Java Platform Manager or the Library Manager.

ContentLicense: CC BY-SA 2.5


问:
Reading a string from and to a certain character
I would like to know if it is possible to read a certain string of n-length, from x character to y character without having to split it into smaller pieces.

I have the following string, for a path in AD CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com, and I would like to be able to just read the someName part of it, without splitting by = or , first. How do I achieve that?

Reason is, that I do not have to do group comparison as I am doing it right now:

```<code>SearchResult t1 = search.FindOne();
foreach (string s in t1.Properties["memberof"])
{
    foreach (string g in groups)
    {
        if (s.ToLower().Contains(g.ToLower()))
        {
            // do something
        }
    }
}
</code>```

I would rather make the if clause to equals, but I do not want to always split the above path/groups into an array twice. How do I do that?

答:
If you are doing group comparisons I would use System.DirectoryServices.AccountManagement namespace</p>

```<code>PrincipalContext Context = new PrincipalContext(ContextType.Domain, "");
UserPrincipal Usr = UserPrincipal.FindByIdentity(Context, "User");
GroupPrincipal G = GroupPrincipal.FindByIdentity(Context, "Group");

if(Usr.IsMemberOf(G)) {

}
</code>```

Body:
I would like to know if it is possible to read a certain string of n-length, from x character to y character without having to split it into smaller pieces.

I have the following string, for a path in AD CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com, and I would like to be able to just read the someName part of it, without splitting by = or , first. How do I achieve that?

Reason is, that I do not have to do group comparison as I am doing it right now:

SearchResult t1 = search.FindOne();
foreach (string s in t1.Properties["memberof"])
{
    foreach (string g in groups)
    {
        if (s.ToLower().Contains(g.ToLower()))
        {
            // do something
        }
    }
}

I would rather make the if clause to equals, but I do not want to always split the above path/groups into an array twice. How do I do that?

Body:
If you are doing group comparisons I would use System.DirectoryServices.AccountManagement namespace

PrincipalContext Context = new PrincipalContext(ContextType.Domain, "");
UserPrincipal Usr = UserPrincipal.FindByIdentity(Context, "User");
GroupPrincipal G = GroupPrincipal.FindByIdentity(Context, "Group");

if(Usr.IsMemberOf(G)) {

}


问:
Default style property when animating in Javascript
I am making a function to animate elements in the DOM. Everything works, except for one thing.

Transitions are only working while the element has the css property that has to be animated. For example, I want to slowly fade out an element (opacity 1 to opacity 0). This works only of I apply the opacity property manually. So:

```<code><div class="header-logo" id="id" style="opacity: 1;">Logo</div>
</code>```

works with the following code:

```<code>animate(css) {
    if(this !== undefined && css) {
        this.css = css;
    }

    let start = performance.now();

    requestAnimationFrame(function animate(time) {
        let timeFraction = (time - start) / this.duration;

        if( timeFraction > 1) timeFraction = 1;

        let timing = this.timer(timeFraction); //Different timers for different easing (like ease-in-out)

        this.draw(timing);

        if (timeFraction < 1) {
            requestAnimationFrame(animate.bind(this));
        }
    }.bind(this));
}

draw(timing) {
    for(let property in this.css) {
            this.element.style[property] -= timing * (this.element.style[property] - this.css[property]);
    }
}
</code>```

But if I don't apply the opacity: 1;, the code doesn't animate.

My concrete question

How can I check whether an element has the to be animated style property? And if it doesn't have the property, how can I apply (dynamically) the to be animated property (so without setting it by hand in the css sheet or inline)?

答:
How can I check whether an element has the to be animated style
  property?

To check if the opacity is actually 1, set manually or otherwise:

document.getElementById("id").style.opacity === "1"

To check if the opacity is effectively rendered by the browser as being 1:

document.getElementById("id").style.opacity === "" || document.getElementById("id").style.opacity === "1"

To check styles that are set with CSS:

window.getComputedStyle(document.getElementById("id")).opacity === "1"

how can I apply (dynamically) the to be animated property (so without
  setting it by hand in the css sheet or inline)?

document.getElementById("id").style.opacity = "1"

As a final remark: be aware that there are a lot of great libraries doing all this work for you. A couple are:

Jquery (although this gives you a lot more than just animations)

D3 (awesome but can be a steep learning curve for a start)

Dynamicsjs (smaller and more specific for animations, but not a very big community behind it)

Body:
I am making a function to animate elements in the DOM. Everything works, except for one thing.

Transitions are only working while the element has the css property that has to be animated. For example, I want to slowly fade out an element (opacity 1 to opacity 0). This works only of I apply the opacity property manually. So:

Logo

works with the following code:

animate(css) {
    if(this !== undefined && css) {
        this.css = css;
    }

    let start = performance.now();

    requestAnimationFrame(function animate(time) {
        let timeFraction = (time - start) / this.duration;

        if( timeFraction > 1) timeFraction = 1;

        let timing = this.timer(timeFraction); //Different timers for different easing (like ease-in-out)

        this.draw(timing);

        if (timeFraction < 1) {
            requestAnimationFrame(animate.bind(this));
        }
    }.bind(this));
}

draw(timing) {
    for(let property in this.css) {
            this.element.style[property] -= timing * (this.element.style[property] - this.css[property]);
    }
}

But if I don't apply the opacity: 1;, the code doesn't animate.

My concrete question

How can I check whether an element has the to be animated style property? And if it doesn't have the property, how can I apply (dynamically) the to be animated property (so without setting it by hand in the css sheet or inline)?


问:
Correcting x-values in matplotlib with Python
```<code>import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig = plt.figure()
ax1 = fig.add_subplot(111)

numbers = [0, 1, 4, 5, 8, 5, 3, 2, 6, 7, 9, 11]

x = 0
for current, next in zip(numbers, numbers[1:]):
    if (current < next):
        up_bar = patches.Rectangle((x,current), 1, next-current, fc='green')
        ax1.add_patch(up_bar)
    else:
        down_bar = patches.Rectangle((x,current), 1, next-current, fc='red')
        ax1.add_patch(down_bar)
    x += 1

ax1.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8])
ax1.set_yticks([0, 1, 2, 3, 4, 5, 6, 7, 8])
plt.show()
</code>```

^This plots:

Though this is how I want it:

x always shifts one unit to the right. What I want is for it to only shift one unit to the right when its going down(red bar) and going up(green bar).
Does anyone know how to do it? :)

答:
You can introduce a variable old_current (not the best name, though) and check whether this your numbers have "made a turn". Only in this case you should increase x. The following should fit your needs:

```<code>import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig = plt.figure()
ax1 = fig.add_subplot(111)

numbers = [0, 1, 4, 5, 8, 5, 3, 2, 6, 7, 9, 11]

x = 0
old_current = 0
for current, next in zip(numbers, numbers[1:]):
    if (current < next):
        if (old_current > current):
            x += 1
        up_bar = patches.Rectangle((x,current), 1, next-current, fc='green')
        ax1.add_patch(up_bar)
    else:
        if (old_current < current):
            x += 1
        down_bar = patches.Rectangle((x,current), 1, next-current, fc='red')
        ax1.add_patch(down_bar)
    old_current = current

ax1.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
ax1.set_yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
ax1.set_xlim(0,12)
ax1.set_ylim(0,12)
plt.show()
</code>```

Body:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig = plt.figure()
ax1 = fig.add_subplot(111)

numbers = [0, 1, 4, 5, 8, 5, 3, 2, 6, 7, 9, 11]

x = 0
for current, next in zip(numbers, numbers[1:]):
    if (current < next):
        up_bar = patches.Rectangle((x,current), 1, next-current, fc='green')
        ax1.add_patch(up_bar)
    else:
        down_bar = patches.Rectangle((x,current), 1, next-current, fc='red')
        ax1.add_patch(down_bar)
    x += 1

ax1.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8])
ax1.set_yticks([0, 1, 2, 3, 4, 5, 6, 7, 8])
plt.show()

^This plots:

Though this is how I want it:

x always shifts one unit to the right. What I want is for it to only shift one unit to the right when its going down(red bar) and going up(green bar).
Does anyone know how to do it? :)

Body:
You can introduce a variable old_current (not the best name, though) and check whether this your numbers have "made a turn". Only in this case you should increase x. The following should fit your needs:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig = plt.figure()
ax1 = fig.add_subplot(111)

numbers = [0, 1, 4, 5, 8, 5, 3, 2, 6, 7, 9, 11]

x = 0
old_current = 0
for current, next in zip(numbers, numbers[1:]):
    if (current < next):
        if (old_current > current):
            x += 1
        up_bar = patches.Rectangle((x,current), 1, next-current, fc='green')
        ax1.add_patch(up_bar)
    else:
        if (old_current < current):
            x += 1
        down_bar = patches.Rectangle((x,current), 1, next-current, fc='red')
        ax1.add_patch(down_bar)
    old_current = current

ax1.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
ax1.set_yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
ax1.set_xlim(0,12)
ax1.set_ylim(0,12)
plt.show()


问:
SQLSTATE[42S22]: Column not found: 1054 Unknown column one to many(inverse) relation laravel
I have two models Tour.php and TourCategory.php:

Tour.php

```<code>protected $table = `tours`;

public function category()
{
    return $this->belongsTo('App\TourCategory');
}
</code>```

TourCategory.php

```<code>protected $table = 'tcategories';

public function tours()
{
    return $this->hasMany('App\Tour');
}
</code>```

My db tables are as follows:

tours table

id|title|category_id|content|

tcatgegories table

id|name

And I have a view to show the all tours belonging to a category with the following code:

```<code>    @foreach ($category->tours as $tour)
     <tr>
        <th>{{ $tour->id}}</th>
        <td>{{ $tour->title}}</td>
        <td>
            <span class="label label-default">{{$category->name}}</span>
        </td>
     </tr>
    @endforeach
</code>```

With this above code I'm getting error of:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tours.tour_category_id' in
'where clause' (SQL: select * from `tours` where `tours`.`tour_category_id` = 1 and
`tours`.`tour_category_id` is not null) (View: F:\multiauth_tutorial-master\resources\
views\admin\categories\show.blade.php
</code>```

I have used same code for my previous projects also but didn't had any errors. Or am I missing something ?

答:
this column tour_category_id lis not found in your tours table, change your sql query to

```<code>select * from `tours` where `tours`.`category_id` = 1 and `tours`.`category_id` is not null
</code>```

Body:
I have two models Tour.php and TourCategory.php:

Tour.php

protected $table = `tours`;

public function category()
{
    return $this->belongsTo('App\TourCategory');
}

TourCategory.php

protected $table = 'tcategories';

public function tours()
{
    return $this->hasMany('App\Tour');
}

My db tables are as follows:

tours table

id|title|category_id|content|

tcatgegories table

id|name

And I have a view to show the all tours belonging to a category with the following code:

    @foreach ($category->tours as $tour)

        {{ $tour->id}}
        {{ $tour->title}}

            {{$category->name}}

    @endforeach

With this above code I'm getting error of:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tours.tour_category_id' in
'where clause' (SQL: select * from `tours` where `tours`.`tour_category_id` = 1 and
`tours`.`tour_category_id` is not null) (View: F:\multiauth_tutorial-master\resources\
views\admin\categories\show.blade.php

I have used same code for my previous projects also but didn't had any errors. Or am I missing something ?

Body:
this column tour_category_id lis not found in your tours table, change your sql query to

select * from `tours` where `tours`.`category_id` = 1 and `tours`.`category_id` is not null


问:
PHP classes is this right
still getting used to PHP classes so a bit of "help /guidance" please

I have a class like this:

```<code>class ansa_accounturl_query {

    function __construct() {

     global $DBH;
     global $limit;
     $STH = $DBH->query("SELECT frm_url.frm_urlID,frm_url.frm_url FROM frm_url WHERE frm_url.accountID='SOMETHING' ".$limit." ");
     $STH->setFetchMode(PDO::FETCH_OBJ);
     $this->noforms = $STH->rowCount();
     while($row  = $STH->fetch()):
         $this->frm_urlID[]  = $row->frm_urlID;
         $this->frm_url[] = $row->frm_url;
     endwhile;
    }

}
</code>```

The limit comes from a PHP function - and works.

What I would really like to do is create extend classes for  the above example which gives say $this-frm_url as a function. so that on the "page" I call the class $classcall = new class(); but rather than have to go echo $classcall->frm_url[$key]; I can just call a function like this echo frm_url(); So in the example above there would be 2 extend classes one for frm_urlID and one for frm_url.

Also, in the "master class" am I right in in setting as array? i.e. $this->frm_url[] as without that I cannot seem to run a loop but the loop does seem "over" complex if you do it this way as you (well I) have to get a count of the array items then run the loop so you (again I) have a for() statement then a foreach().  Seems longwinded to me.

Thanks in adavance.

答:
What I would really like to do is
  create extend classes for the above
  example which gives say $this-frm_url
  as a function. so that on the "page" I
  call the class $classcall = new
  class(); but rather than have to go
  echo $classcall->frm_url[$key]; I can
  just call a function like this echo
  frm_url(); So in the example above
  there would be 2 extend classes one
  for frm_urlID and one for frm_url.

echo frm_url(); won't work. You have to use $classcall->frm_url[$key]; unless you define a function like

```<code>function frm_url($key){
  if (!$key) $key = 0;
  $classcall = new ansa_accounturl_query();
  return $classcall->frm_url[$key];
}
</code>```

Title: PHP classes is this right

Body:
still getting used to PHP classes so a bit of "help /guidance" please

I have a class like this:

class ansa_accounturl_query {

    function __construct() {

     global $DBH;
     global $limit;
     $STH = $DBH->query("SELECT frm_url.frm_urlID,frm_url.frm_url FROM frm_url WHERE frm_url.accountID='SOMETHING' ".$limit." ");
     $STH->setFetchMode(PDO::FETCH_OBJ);
     $this->noforms = $STH->rowCount();
     while($row  = $STH->fetch()):
         $this->frm_urlID[]  = $row->frm_urlID;
         $this->frm_url[] = $row->frm_url;
     endwhile;
    }

}

The limit comes from a PHP function - and works.

What I would really like to do is create extend classes for  the above example which gives say $this-frm_url as a function. so that on the "page" I call the class $classcall = new class(); but rather than have to go echo $classcall->frm_url[$key]; I can just call a function like this echo frm_url(); So in the example above there would be 2 extend classes one for frm_urlID and one for frm_url.

Also, in the "master class" am I right in in setting as array? i.e. $this->frm_url[] as without that I cannot seem to run a loop but the loop does seem "over" complex if you do it this way as you (well I) have to get a count of the array items then run the loop so you (again I) have a for() statement then a foreach().  Seems longwinded to me.

Thanks in adavance.

Body:
What I would really like to do is
  create extend classes for the above
  example which gives say $this-frm_url
  as a function. so that on the "page" I
  call the class $classcall = new
  class(); but rather than have to go
  echo $classcall->frm_url[$key]; I can
  just call a function like this echo
  frm_url(); So in the example above
  there would be 2 extend classes one
  for frm_urlID and one for frm_url.

echo frm_url(); won't work. You have to use $classcall->frm_url[$key]; unless you define a function like

function frm_url($key){
  if (!$key) $key = 0;
  $classcall = new ansa_accounturl_query();
  return $classcall->frm_url[$key];
}


问:
What does Python's matplotlib figure constructor do with this number?
The code I am currently using has the following:

```<code>import matplotlib.pyplot as plt

fig = plt.figure(1)
</code>```

My question is the following: What is the "1" for? I assume it is some kind of index, but the documentation does not have this parameter:

class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)

Am I missing something? I am pretty sure that I am not the first one to ask this, but neither search nor "Questions that may already have your answer" gave me an answer...

Am I supposed to increase this for the next figure I plot?

答:
You would need to look at the documentation of the command you're using, not some other.

matplotlib.pyplot.figure(num=None, figsize=None, dpi=None,...) has a num argument.

num : integer or string, optional, default: none

  If not provided, a new figure will be created, and the figure number will be incremented. The figure objects holds this number in a number attribute. If num is provided, and a figure with this id already exists, make it active, and returns a reference to it. If this figure does not exists, create it and returns it. If num is a string, the window title will be set to this figure’s num.

You don't need to use this, successive calls of plt.figure() will create new figures automatically.

Body:
The code I am currently using has the following:

import matplotlib.pyplot as plt

fig = plt.figure(1)

My question is the following: What is the "1" for? I assume it is some kind of index, but the documentation does not have this parameter:

class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)

Am I missing something? I am pretty sure that I am not the first one to ask this, but neither search nor "Questions that may already have your answer" gave me an answer...

Am I supposed to increase this for the next figure I plot?


问:
Fail to load url on WebView
I have my own internet site on localhost.
The JSP page is working fine when I run the JSP files from NetBeans.
also running fine when I run it from the browser.
I made a simple Android application with a WebView.
The application also runs fine when I try to load CNN site:
But when I replace the URL with my own URL, I get the famous
Error message: HTTP Status 404 - Not Found.
I know that the URL is also fine because I can run it from the browser.
The only difference is that my URL is on localhost.
I'm using Android Emulator Nexus_6_API_23 Google_API:5554
I read in other's people answers that the emulator interact with localhost using IP 10.0.2.2,
So I have changed the WebView URL as follow:
from: http://localhost:8080/MissionWS/myLogin.jsp
  To: http://10.0.2.2:8080/MissionsWS/myLogin.jsp

Here is the code of the web view android application:
Can anyone help?

```<code>public class MainActivity extends AppCompatActivity {
private WebView mWebView;

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

    mWebView = (WebView) findViewById(R.id.mWebView);
    mWebView.getSettings().setJavaScriptEnabled(true);
    //mWebView.loadUrl("http://edition.cnn.com/");
    mWebView.loadUrl("http://10.0.2.2:8080/MissionsWS/myLogin.jsp");
    }
}
</code>```

答:
You cannot access like that to the localhost.
I think you should look over to : How can I access my localhost from my Android device?</p>

Title: Fail to load url on WebView

Body:
I have my own internet site on localhost.
The JSP page is working fine when I run the JSP files from NetBeans.
also running fine when I run it from the browser.
I made a simple Android application with a WebView.
The application also runs fine when I try to load CNN site:
But when I replace the URL with my own URL, I get the famous
Error message: HTTP Status 404 - Not Found.
I know that the URL is also fine because I can run it from the browser.
The only difference is that my URL is on localhost.
I'm using Android Emulator Nexus_6_API_23 Google_API:5554
I read in other's people answers that the emulator interact with localhost using IP 10.0.2.2,
So I have changed the WebView URL as follow:
from: http://localhost:8080/MissionWS/myLogin.jsp
  To: http://10.0.2.2:8080/MissionsWS/myLogin.jsp

Here is the code of the web view android application:
Can anyone help?

public class MainActivity extends AppCompatActivity {
private WebView mWebView;

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

    mWebView = (WebView) findViewById(R.id.mWebView);
    mWebView.getSettings().setJavaScriptEnabled(true);
    //mWebView.loadUrl("http://edition.cnn.com/");
    mWebView.loadUrl("http://10.0.2.2:8080/MissionsWS/myLogin.jsp");
    }
}


问:
How to Alow Two Letters at the end of string with regex?
I have the following pattern:

```<code>^(01|04|05|06|PP|PPC)[0-9]*$
</code>```

This works if the string starts with PP and ends with numbers.

How to allow UK at the end? I want to match a string like: PPC12345678UK

答:
```<code>^(01|04|05|06|PP|PPC)[0-9]*(UK)?$
</code>```

In regular expressions, ? means "0 or 1", i.e. it's equivalent to writing {0,1}. It makes the attribute "optional".

So, the above regex will match strings like:

PP23462937

PPC328472936UK

And it will not match strings like:

01937492384U

068203472K

Body:
I have the following pattern:

^(01|04|05|06|PP|PPC)[0-9]*$

This works if the string starts with PP and ends with numbers.

How to allow UK at the end? I want to match a string like: PPC12345678UK

Body:
^(01|04|05|06|PP|PPC)[0-9]*(UK)?$

In regular expressions, ? means "0 or 1", i.e. it's equivalent to writing {0,1}. It makes the attribute "optional".

So, the above regex will match strings like:

PP23462937

PPC328472936UK

And it will not match strings like:

01937492384U

068203472K


问:
Event value keeps changing when an object equal to the event is changed
The following code is being used to map an event with an object:

```<code>//shortened the function for better visibility
moveToolbar.on("graphic-move-stop", function (evt) {
    oldGraphicMove = evt.graphic;
    oldGraphicMove.geometry.rings[0][0] = 42173;
    newGraphicMove = evt.graphic;
});
</code>```

However when changing the value of oldGraphicMove the value of the event is also changing to mimic it even though no change is being made to the event itself. Is there any way to prevent this?

答:
The problem is that oldGraphicMove points to the same object as evt.graphic.
You need to make a copy of evt.graphic.

oldGraphicMove = JSON.parse(JSON.stringify(evt.graphic)); should do the trick.

Body:
The following code is being used to map an event with an object:

//shortened the function for better visibility
moveToolbar.on("graphic-move-stop", function (evt) {
    oldGraphicMove = evt.graphic;
    oldGraphicMove.geometry.rings[0][0] = 42173;
    newGraphicMove = evt.graphic;
});

However when changing the value of oldGraphicMove the value of the event is also changing to mimic it even though no change is being made to the event itself. Is there any way to prevent this?


问:
Weird gcc error stray/missing terminating " character in C
I get the following errors:

```<code>error: missing terminating " character
</code>```

and

```<code>error: stray `\' in program
</code>```

In this line of C code:

```<code> system("sqlite3 -html /home/user/.rtcom-eventlogger/el.db \"SELECT service_id, event_type_id,free_text, remote_uid FROM Events WHERE remote_uid=\'%d\' ORDER BY start_time DESC;\" > lol.html", nr);
</code>```

"nr" is a integer variable.

I have gone over this so many times but are totally stuck of finding a solution.

EDIT: The errors is the ouput while compiling with gcc if I didn't make that clear.

答:
In my case I had an external define variable with escaped ", like this:

```<code>#define DEFINE \"string\"
</code>```

It was transcluded into code like this:

```<code>cout << DEFINE; // source code

cout << \"string\"; // source code during compilation
</code>```

Body:
I get the following errors:

error: missing terminating " character

and

error: stray `\' in program

In this line of C code:

 system("sqlite3 -html /home/user/.rtcom-eventlogger/el.db \"SELECT service_id, event_type_id,free_text, remote_uid FROM Events WHERE remote_uid=\'%d\' ORDER BY start_time DESC;\" > lol.html", nr);

"nr" is a integer variable.

I have gone over this so many times but are totally stuck of finding a solution.

EDIT: The errors is the ouput while compiling with gcc if I didn't make that clear.

Body:
In my case I had an external define variable with escaped ", like this:

#define DEFINE \"string\"

It was transcluded into code like this:

cout << DEFINE; // source code

cout << \"string\"; // source code during compilation


问:
Detect when user logs back in
I have a winforms app (C# .net 2.0) that is running in sys tray. The user can log off from the system and is presented with Windows' usual login screen.

I want to detect when user logs back in.

I know there is a SessionEnding event to detect when user logs out. I need the reverse of that event if exists.

I need to take special action only when the app is started as a result of "log off-log back in" sequence and not when computer (OS actually) boots up.

答:
When a user logs off, all of their running applications are closed, including your WinForms app that is minimized to the taskbar's notification area. The purpose of the SessionEnding event is for you to shut down your app gracefully when the user logs off or the computer is shutting down. There is no corresponding SessionBeginning event because your app is not automatically reopened when the user logs back in.

If you want your application to be automatically started whenever the user logs in, you need to place it in the "Startup" folder. All of the programs in that folder will be started automatically when the user logs in.

You can either configure your installer to place the application in the user's "Startup" folder (use the CSIDL_STARTUP environment variable to find the correct location) or the common "Startup" folder shared by all users (use the CSIDL_COMMON_STARTUP environment variable). Of course, if you don't have an installer, you can always place a shortcut to your application into that folder manually.

Title: Detect when user logs back in


问:
Angular.js "typeError: V2.example is not a function" error
i am new in angular.js and i am following a tutorial that was made about a year ago
i am trying to create a search function that takes the input and search for it in
Github.com
The HTML code is :

```<code><!DOCTYPE html>
<html ng-app="github">

<head>
    <script src="angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body ng-controller="main">
    <h1>{{message}}</h1>
    <p> {{username}} </p>
    <form name="search">
        <input type="search" placeholder="enter name" ng-model="username">
        <button type="submit" ng-click="search(username)">search</button>
    </form>
    <div>
        <h1> {{user.login}} </h1>
        <img src="http://www.gravatar.com/avatar/{{user.gravatar_id}}">
        <p> {{user.type}} </p>
    </div>
</body>

</html>
</code>```

and the JS code :

```<code>// Code goes here
(function () {
    var app = angular.module("github", []);
    var main = function ($scope, $http) {
        var onComplete = function (response) {
            $scope.user = response.data;
        };
        var onError = function (reasone) {
            $scope.error = "no can";
        };
        $scope.search = function (username) {
            $http.get("http://api.github.com/users/" +username).then(onComplete, onError);
        };
        $scope.message = "Git hub viewer";
    };
    app.controller("main", ["$scope", "$http", main]);
}());
</code>```

this gives me an error >>> TypeError: v2.search is not a function <<<
for help:
i got a problem like that and the solution was not to use "main" function in global type but "search" is not global i guess .. hope this help

here is the codepen link:

http://codepen.io/ToBeM12/pen/vGvwzo

答:
the function has the same name as another variable and is conflicting in $scope

In your case just replace $scope.search to $scope.searchuser since $scope.search is already defined..

Body:
i am new in angular.js and i am following a tutorial that was made about a year ago
i am trying to create a search function that takes the input and search for it in
Github.com
The HTML code is :

<!DOCTYPE html>

{{message}}

 {{username}}

    <form name="search">
        <input type="search" placeholder="enter name" ng-model="username">
        <button type="submit" ng-click="search(username)">search</button>
    </form>

 {{user.login}}

 {{user.type}}

and the JS code :

// Code goes here
(function () {
    var app = angular.module("github", []);
    var main = function ($scope, $http) {
        var onComplete = function (response) {
            $scope.user = response.data;
        };
        var onError = function (reasone) {
            $scope.error = "no can";
        };
        $scope.search = function (username) {
            $http.get("http://api.github.com/users/" +username).then(onComplete, onError);
        };
        $scope.message = "Git hub viewer";
    };
    app.controller("main", ["$scope", "$http", main]);
}());

this gives me an error >>> TypeError: v2.search is not a function <<<
for help:
i got a problem like that and the solution was not to use "main" function in global type but "search" is not global i guess .. hope this help

here is the codepen link:

http://codepen.io/ToBeM12/pen/vGvwzo


答:
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the model is not *_id, you may pass a custom key name as the second argument to the belongsTo method

So, you need to specify a foreign key:

```<code>public function category()
{
    return $this->belongsTo('App\TourCategory', 'category_id');
}
</code>```

You may also override the foreign and local keys by passing additional arguments to the hasMany method.

```<code>public function tours()
{
    return $this->hasMany('App\Tour', 'category_id');
}
</code>```

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many

Or use tour_category_id instead of category_id in the tours table.

Title: SQLSTATE[42S22]: Column not found: 1054 Unknown column one to many(inverse) relation laravel

Body:
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the model is not *_id, you may pass a custom key name as the second argument to the belongsTo method

So, you need to specify a foreign key:

public function category()
{
    return $this->belongsTo('App\TourCategory', 'category_id');
}

You may also override the foreign and local keys by passing additional arguments to the hasMany method.

public function tours()
{
    return $this->hasMany('App\Tour', 'category_id');
}

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many

Or use tour_category_id instead of category_id in the tours table.


答:
just add UK at the end
^(01|04|05|06|PP|PPC)[0-9]*UK$

Or, as @Tom Lord just responded, with question mark if optional.:
^(01|04|05|06|PP|PPC)[0-9]*(UK)?$

If you don't want to capture the UK at the end use (?:) non capturing groups: ^(01|04|05|06|PP|PPC)[0-9]*(?:UK)?$

Title: How to Alow Two Letters at the end of string with regex?


问:
ListView.addHeaderView(View) Crash on Api 11 and API12
i have a List view that i need to add a header view to it and a footer view,

it runs perfectly on any api else 11 & 12.

this is the Log cat

```<code>java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.
11-13 11:21:13.717: E/AndroidRuntime(583): at     android.widget.ListView.addHeaderView(ListView.java:255)
11-13 11:21:13.717: E/AndroidRuntime(583): at MediaFragment.setAdapter_(MediaFragment.java:1041)
11-13 11:21:13.717: E/AndroidRuntime(583): at    MediaFragment.JsonObjectOnSuccess(MediaFragment.java:991)
11-13 11:21:13.717: E/AndroidRuntime(583): at MediaFragment.GetCache_db(MediaFragment.java:2074)
11-13 11:21:13.717: E/AndroidRuntime(583): at DataBaseAdapter$GetAsyncTask.onPostExecute(DataBaseAdapter.java:253)
11-13 11:21:13.717: E/AndroidRuntime(583): at DataBaseAdapter$GetAsyncTask.onPostExecute(DataBaseAdapter.java:1)
13 11:21:13.717: E/AndroidRuntime(583): at android.os.AsyncTask.finish(AsyncTask.java:590)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.AsyncTask.access$600(AsyncTask.java:149)
  11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:603)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.Handler.dispatchMessage(Handler.java:99)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.Looper.loop(Looper.java:132)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.app.ActivityThread.main(ActivityThread.java:4025)
       11-13 11:21:13.717: E/AndroidRuntime(583): at java.lang.reflect.Method.invokeNative(Native Method)
   11-13 11:21:13.717: E/AndroidRuntime(583): at java.lang.reflect.Method.invoke(Method.java:491)
 11-13 11:21:13.717: E/AndroidRuntime(583): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
 11-13 11:21:13.717: E/AndroidRuntime(583): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
  11-13 11:21:13.717: E/AndroidRuntime(583): at dalvik.system.NativeStart.main(Native Method)
</code>```

and this is my Code :

```<code>    listview = (ListView) view.findViewById(R.id.fragmentListView);

    headListView = (View) mActivity.getLayoutInflater().inflate(
            R.layout.headlistview,listview,false);
    footerListview = (View) mActivity.getLayoutInflater().inflate(
            R.layout.media_footer,listview,false);

    listview.addHeaderView(headListView, null, false);
    listview.addFooterView(footerListview, null, false);

    listview.setAdapter(MediaAdapter);
    MediaAdapter.notifyDataSetChanged();
    listview.onRestoreInstanceState(state);
</code>```

答:
The error says: "Cannot add header view to list -- setAdapter has already been called.". This means you need to add header before setting adapter.

Also try overriding the factory method as following. It solved my problem.

```<code>public void addHeaderView(@NonNull View view){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        super.addHeaderView(view);
    } else {
        try {
            if (!(view.getLayoutParams() instanceof AbsListView.LayoutParams)) {
                view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                        , ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            super.addHeaderView(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
i have a List view that i need to add a header view to it and a footer view,

it runs perfectly on any api else 11 & 12.

this is the Log cat

java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.
11-13 11:21:13.717: E/AndroidRuntime(583): at     android.widget.ListView.addHeaderView(ListView.java:255)
11-13 11:21:13.717: E/AndroidRuntime(583): at MediaFragment.setAdapter_(MediaFragment.java:1041)
11-13 11:21:13.717: E/AndroidRuntime(583): at    MediaFragment.JsonObjectOnSuccess(MediaFragment.java:991)
11-13 11:21:13.717: E/AndroidRuntime(583): at MediaFragment.GetCache_db(MediaFragment.java:2074)
11-13 11:21:13.717: E/AndroidRuntime(583): at DataBaseAdapter$GetAsyncTask.onPostExecute(DataBaseAdapter.java:253)
11-13 11:21:13.717: E/AndroidRuntime(583): at DataBaseAdapter$GetAsyncTask.onPostExecute(DataBaseAdapter.java:1)
13 11:21:13.717: E/AndroidRuntime(583): at android.os.AsyncTask.finish(AsyncTask.java:590)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.AsyncTask.access$600(AsyncTask.java:149)
  11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:603)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.Handler.dispatchMessage(Handler.java:99)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.os.Looper.loop(Looper.java:132)
 11-13 11:21:13.717: E/AndroidRuntime(583): at android.app.ActivityThread.main(ActivityThread.java:4025)
       11-13 11:21:13.717: E/AndroidRuntime(583): at java.lang.reflect.Method.invokeNative(Native Method)
   11-13 11:21:13.717: E/AndroidRuntime(583): at java.lang.reflect.Method.invoke(Method.java:491)
 11-13 11:21:13.717: E/AndroidRuntime(583): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
 11-13 11:21:13.717: E/AndroidRuntime(583): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
  11-13 11:21:13.717: E/AndroidRuntime(583): at dalvik.system.NativeStart.main(Native Method)

and this is my Code :

    listview = (ListView) view.findViewById(R.id.fragmentListView);

    headListView = (View) mActivity.getLayoutInflater().inflate(
            R.layout.headlistview,listview,false);
    footerListview = (View) mActivity.getLayoutInflater().inflate(
            R.layout.media_footer,listview,false);

    listview.addHeaderView(headListView, null, false);
    listview.addFooterView(footerListview, null, false);

    listview.setAdapter(MediaAdapter);
    MediaAdapter.notifyDataSetChanged();
    listview.onRestoreInstanceState(state);

Body:
The error says: "Cannot add header view to list -- setAdapter has already been called.". This means you need to add header before setting adapter.

Also try overriding the factory method as following. It solved my problem.

public void addHeaderView(@NonNull View view){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        super.addHeaderView(view);
    } else {
        try {
            if (!(view.getLayoutParams() instanceof AbsListView.LayoutParams)) {
                view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                        , ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            super.addHeaderView(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
How to display realtime change in server date and time every 1 Sec in php?
I wrote this php code to show server date and time but I'd like to display realtime change in server date and time every 1 Sec

```<code><p><?php echo "Server Time " . date("Y-m-d h:i:s"); ?> (GMT) UTC +0 UK/London</p>
</code>```

Pls help me, thank you

答:
if you still need a real time clock that uses your server clock you could try this. im using twig {{now|date('Y/m/d H:i:s')}}. but you could also use php's <?php echo date('Y/m/d H:i:s');?>. its basically using localStorage to store the server date on localstorage and setSeconds updates the localstorage every 1 second , while the now variable loads the localstorage date and converts it to js date format. I then use the {{now|date('Y/m/d H:i:s')}} inside the date element for fallback in case localstorage is not enabled.

```<code>  try {
localStorage.setItem('today', new Date("{{now|date('Y/m/d H:i:s')}}");
setInterval(function clock() {
    var month = [
    "Jan", "Feb", "Marh", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Octr", "Nov", "Dec"
    ];
    var now = new Date(localStorage.getItem('today'));
    now.setSeconds(now.getSeconds() + 1);
    localStorage.setItem('today', now);
    var G = format(now.getHours() % 12 || 12);
    var i = format(now.getMinutes());
    var s = format(now.getSeconds());
    var M = month[now.getMonth()];
    var d = format(now.getDate());
    var Y = now.getFullYear();
    function format(data) {
        return (data < 10 ? data = "0" + data : data);
    }
    $("#date").html(M + ". " + d + ", " + Y + " " + G + ":" + i + ":" + s);
    return clock;
}(), 1000);
} catch(e) {
    console.log(e);
}
</code>```

Body:
I wrote this php code to show server date and time but I'd like to display realtime change in server date and time every 1 Sec

<?php echo "Server Time " . date("Y-m-d h:i:s"); ?> (GMT) UTC +0 UK/London

Pls help me, thank you

Body:
if you still need a real time clock that uses your server clock you could try this. im using twig {{now|date('Y/m/d H:i:s')}}. but you could also use php's <?php echo date('Y/m/d H:i:s');?>. its basically using localStorage to store the server date on localstorage and setSeconds updates the localstorage every 1 second , while the now variable loads the localstorage date and converts it to js date format. I then use the {{now|date('Y/m/d H:i:s')}} inside the date element for fallback in case localstorage is not enabled.

  try {
localStorage.setItem('today', new Date("{{now|date('Y/m/d H:i:s')}}");
setInterval(function clock() {
    var month = [
    "Jan", "Feb", "Marh", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Octr", "Nov", "Dec"
    ];
    var now = new Date(localStorage.getItem('today'));
    now.setSeconds(now.getSeconds() + 1);
    localStorage.setItem('today', now);
    var G = format(now.getHours() % 12 || 12);
    var i = format(now.getMinutes());
    var s = format(now.getSeconds());
    var M = month[now.getMonth()];
    var d = format(now.getDate());
    var Y = now.getFullYear();
    function format(data) {
        return (data < 10 ? data = "0" + data : data);
    }
    $("#date").html(M + ". " + d + ", " + Y + " " + G + ":" + i + ":" + s);
    return clock;
}(), 1000);
} catch(e) {
    console.log(e);
}


问:
Count of islands of negative and positive numbers in a NumPy array
I have an array containing chunks of negative and chunks of positive elements. A much simplified example of it would be an array a looking like: array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])

(a<0).sum() and (a>0).sum() give me the total number of negative and positive elements but how do I count these in order? By this I mean I want to know that my array contains first 3 negative elements, 6 positive and 2 negative.

This sounds like a topic that have been addressed somewhere, and there may be a duplicate out there, but I can't find one.

A method is to use numpy.roll(a,1) in a loop over the whole array and count the number of elements of a given sign appearing in e.g. the first element of the array as it rolls, but it doesn't look much numpyic (or pythonic) nor very efficient to me.

答:
Just use

```<code>my_array = np.array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])
negative_index = my_array<0
</code>```

and you'll get the indizes of the negative values. After that you can split this array:

```<code>splits = np.split(negative_index, np.where(np.diff(negative_index))[0]+1)
</code>```

and moreover calc the size of the inner arrays:

```<code>len_list = [len(i) for i in splits]
print(len_list)
</code>```

And you'll get what you are looking for:

```<code>Out[1]: [3, 6, 2]
</code>```

You just have to mention what your first element is. Per definition in my code, a negative one.

So just execute:

```<code>my_array = np.array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])
negative_index = my_array<0
splits = np.split(negative_index, np.where(np.diff(negative_index))[0]+1)
len_list = [len(i) for i in splits]
print(len_list)
</code>```

Body:
Just use

my_array = np.array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])
negative_index = my_array<0

and you'll get the indizes of the negative values. After that you can split this array:

splits = np.split(negative_index, np.where(np.diff(negative_index))[0]+1)

and moreover calc the size of the inner arrays:

len_list = [len(i) for i in splits]
print(len_list)

And you'll get what you are looking for:

Out[1]: [3, 6, 2]

You just have to mention what your first element is. Per definition in my code, a negative one.

So just execute:

my_array = np.array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])
negative_index = my_array<0
splits = np.split(negative_index, np.where(np.diff(negative_index))[0]+1)
len_list = [len(i) for i in splits]
print(len_list)


问:
Variable doesn't save the current List size
So I have this piece of code here:

```<code>List<String> s1 = new ArrayList<String>();
int size = s1.size();

s1.add("A");
s1.add("B");
System.out.println(size);
s1.add("C");
s1.add("D");
System.out.println(size);
</code>```

And that's the output:

```<code>0
0
</code>```

But it should be:

```<code>2
4
</code>```

What it the problem? Why doesn't the variable size get the current List size when I call her?

Thanks for helping me!

答:
The size you are printing is a variable which has already been assigned a value well before any value was added to the arraylist, hence, the size variable will always print value 0 anywhere you use it (unless youy reassign any value).

The one which you require is the size method of List; which is accessed by Arraylist_Name.size()

So, when you are printing the values, you should use s1.size() which will give the current size of the ArrayList.

Or, you need to assign the new ArrayList sizes everytime to your size variable, so that it is in sync with the actual ArrayList size.

Body:
So I have this piece of code here:

List<String> s1 = new ArrayList<String>();
int size = s1.size();

s1.add("A");
s1.add("B");
System.out.println(size);
s1.add("C");
s1.add("D");
System.out.println(size);

And that's the output:

0
0

But it should be:

2
4

What it the problem? Why doesn't the variable size get the current List size when I call her?

Thanks for helping me!


问:
Can i edit the buttons of a browser dialogs?
I was wondering if it's possible to change the text of the OK/Cancel buttons in dialogs?

答:
You may with HTML5 which permits you to create your own customized dialog boxes, as the following example illustrates:

HTML:

```<code><dialog open id="favDialog">
  <form method="dialog">
    <section>
      <p>Leave this site?</p>
    </section>
    <menu>
      <button id="cancel" type="reset">No</button>
      <button type="submit">Yes</button>
    </menu>
  </form>
</dialog>
</code>```

See live code

This code to date is only supported by a couple of the major browsers, namely Chrome 37 and Opera 24 (see more details here).

Body:
You may with HTML5 which permits you to create your own customized dialog boxes, as the following example illustrates:

HTML:

<dialog open id="favDialog">
  <form method="dialog">
    <section>
      <p>Leave this site?</p>
    </section>
    <menu>
      <button id="cancel" type="reset">No</button>
      <button type="submit">Yes</button>
    </menu>
  </form>
</dialog>

See live code

This code to date is only supported by a couple of the major browsers, namely Chrome 37 and Opera 24 (see more details here).


问:
How to insert a column of increasing numbers in Sublime Text 2?
```<code>text
text
text
text
</code>```

after the editing, those text becomes to

```<code>1 text
2 text
3 text
4 text
</code>```

It's easy in Notepad ++ with the Column Editor， but I don't know how to do the same in Sublime Text 2.

答:
The Text Pastry plugin does the job very well. It offers the Insert Numbers Syntax.

Select multiple lines with CMD+SHIFT+L (Sublime default):

```<code>   text|
   text|
   text|
   text|
</code>```

Move the cursor where you want it:

```<code> | text
 | text
 | text
 | text
</code>```

And insert numbers with Text Pastry by hitting CMD+ALT+N and entering 1 space 1 space 0:

```<code> 1| text
 2| text
 3| text
 4| text
</code>```

Where 1 space 1 space 0 stands for:

Integer to start with 1

Increment by 1

Padd leading zeros 0

Replace CMD with CTRL on Windows or Linux machines.

Body:
text
text
text
text

after the editing, those text becomes to

1 text
2 text
3 text
4 text

It's easy in Notepad ++ with the Column Editor， but I don't know how to do the same in Sublime Text 2.

Body:
The Text Pastry plugin does the job very well. It offers the Insert Numbers Syntax.

Select multiple lines with CMD+SHIFT+L (Sublime default):

   text|
   text|
   text|
   text|

Move the cursor where you want it:

 | text
 | text
 | text
 | text

And insert numbers with Text Pastry by hitting CMD+ALT+N and entering 1 space 1 space 0:

 1| text
 2| text
 3| text
 4| text

Where 1 space 1 space 0 stands for:

Integer to start with 1

Increment by 1

Padd leading zeros 0

Replace CMD with CTRL on Windows or Linux machines.


问:
Castle Windsor enable or disable interceptors during run time
Is it possible whilst an application (of any type e.g. console, web, web role in azure etc.) to switch castle windsor interceptors on or off to avoid an application restart?

My scenario is to use an Interceptor like that below, to log method entry and exit with arguments.

```<code>public class ExampleInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Debug.WriteLine(string.Format("Before method: {0}", invocation.Method.Name));
        invocation.Proceed();
        Debug.WriteLine(string.Format("After method: {0}", invocation.Method.Name));
    }
}
</code>```

My initial approach was to do something like this:

```<code>public class InterceptorSelector : IModelInterceptorsSelector
{
    public static bool InterceptorOn = false;

    public bool HasInterceptors(ComponentModel model)
    {
        return
            typeof(ExampleInterceptor) != model.Implementation
            && InterceptorOn
            && model.Implementation.Namespace.StartsWith("MvcApplication1");
    }

    public InterceptorReference[] SelectInterceptors(ComponentModel model, InterceptorReference[] interceptors)
    {
        return new[]
        {
            InterceptorReference.ForType<ExampleInterceptor>()
        };
    }
}
</code>```

However I found that once the interceptor has handled a method once, there must be some internal caching (for performance benefit no doubt) as the method does not get hit again in the InterceptorSelector.

The primary use case I have for this is a WebApi hosted in azure serving hundreds (if not 1000s) of requests per second over multiple VM instances. In the event of needing to debug the live environment I want to enable verbose logging on one of these instances but at the same time not want to take the VM instance out of action when enabling this logging.

答:
You can exclude/add interceptors at runtime this way:

```<code>public class MyController : Controller
{
    public IResolver iResolver {get;set;}
    public IService someService {get;set;}

    private UsageMethod()
    {
        ExcludeInterceptors(someService, new [] {typeof(Interceptor1),typeof(Interceptor2)};
        AddInterceptor(someService, typeof(Interceptor1), 0};
    }

    private Castle.DynamicProxy.IInterceptor[] getInterceptorsField(object service)
    {
        var field = service.GetType().GetField("__interceptors");
        return field.GetValue(service) as Castle.DynamicProxy.IInterceptor[];
    }

    private void ExcudeInterceptors(object service, params Type[] interceptorTypes2exclude)
    {
        var newInterceptors = getInterceptorsField(service).Where(x => !interceptorTypes2exclude.Contains(x.GetType())).ToArray();
        field.SetValue(service, newInterceptors);
    }

    private void AddInterceptor(object service, Castle.DynamicProxy.IInterceptor interceptorType2add, int position)
    {
        var newInterceptors = getInterceptorsField(service).ToList();
        newInterceptors.Insert(position, iResolver.Resolve(interceptorType2add));
        field.SetValue(service, newInterceptors.ToArray());
    }
}
</code>```

P.S. Was tested with Castle.Windsor 3.3.0

Body:
Is it possible whilst an application (of any type e.g. console, web, web role in azure etc.) to switch castle windsor interceptors on or off to avoid an application restart?

My scenario is to use an Interceptor like that below, to log method entry and exit with arguments.

public class ExampleInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Debug.WriteLine(string.Format("Before method: {0}", invocation.Method.Name));
        invocation.Proceed();
        Debug.WriteLine(string.Format("After method: {0}", invocation.Method.Name));
    }
}

My initial approach was to do something like this:

public class InterceptorSelector : IModelInterceptorsSelector
{
    public static bool InterceptorOn = false;

    public bool HasInterceptors(ComponentModel model)
    {
        return
            typeof(ExampleInterceptor) != model.Implementation
            && InterceptorOn
            && model.Implementation.Namespace.StartsWith("MvcApplication1");
    }

    public InterceptorReference[] SelectInterceptors(ComponentModel model, InterceptorReference[] interceptors)
    {
        return new[]
        {
            InterceptorReference.ForType<ExampleInterceptor>()
        };
    }
}

However I found that once the interceptor has handled a method once, there must be some internal caching (for performance benefit no doubt) as the method does not get hit again in the InterceptorSelector.

The primary use case I have for this is a WebApi hosted in azure serving hundreds (if not 1000s) of requests per second over multiple VM instances. In the event of needing to debug the live environment I want to enable verbose logging on one of these instances but at the same time not want to take the VM instance out of action when enabling this logging.

Body:
You can exclude/add interceptors at runtime this way:

public class MyController : Controller
{
    public IResolver iResolver {get;set;}
    public IService someService {get;set;}

    private UsageMethod()
    {
        ExcludeInterceptors(someService, new [] {typeof(Interceptor1),typeof(Interceptor2)};
        AddInterceptor(someService, typeof(Interceptor1), 0};
    }

    private Castle.DynamicProxy.IInterceptor[] getInterceptorsField(object service)
    {
        var field = service.GetType().GetField("__interceptors");
        return field.GetValue(service) as Castle.DynamicProxy.IInterceptor[];
    }

    private void ExcudeInterceptors(object service, params Type[] interceptorTypes2exclude)
    {
        var newInterceptors = getInterceptorsField(service).Where(x => !interceptorTypes2exclude.Contains(x.GetType())).ToArray();
        field.SetValue(service, newInterceptors);
    }

    private void AddInterceptor(object service, Castle.DynamicProxy.IInterceptor interceptorType2add, int position)
    {
        var newInterceptors = getInterceptorsField(service).ToList();
        newInterceptors.Insert(position, iResolver.Resolve(interceptorType2add));
        field.SetValue(service, newInterceptors.ToArray());
    }
}

P.S. Was tested with Castle.Windsor 3.3.0


问:
getting blank json response while fetching images url from database via php api
Code to fetch all images from server . I am saving the url of the
images present in my server path/directory to the  SQL database (name : photos , columns :id and image )

```<code><?php

     $connection = mysqli_connect("localhost","webkuv1c_naman","naman","webkuv1c_android_api") or die("Error " . mysqli_error($connection));
     $sql = "select image from photos";
     $res = mysqli_query($con,$sql);
     $result = array();

     while($row = mysqli_fetch_array($res)){
         array_push($result,array('url'=>$row['image']));
     }

     echo json_encode(array("result"=>$result));

     mysqli_close($con);
?>
</code>```

I am getting following response on hitting API :

```<code>{"result":[]}
</code>```

this is the image path/url : http://webkunj.com/android_api/productUpload/0.png

答:
You have made all things properly
just replace

```<code>$connection = mysqli_connect("localhost","webkuv1c_naman","naman","webkuv1c_android_api") or die("Error " . mysqli_error($connection));
</code>```

with

```<code> $con = mysqli_connect("localhost","webkuv1c_naman","naman","webkuv1c_android_api") or die("Error " . mysqli_error($con));
</code>```

Body:
Code to fetch all images from server . I am saving the url of the
images present in my server path/directory to the  SQL database (name : photos , columns :id and image )

<?php

     $connection = mysqli_connect("localhost","webkuv1c_naman","naman","webkuv1c_android_api") or die("Error " . mysqli_error($connection));
     $sql = "select image from photos";
     $res = mysqli_query($con,$sql);
     $result = array();

     while($row = mysqli_fetch_array($res)){
         array_push($result,array('url'=>$row['image']));
     }

     echo json_encode(array("result"=>$result));

     mysqli_close($con);
?>

I am getting following response on hitting API :

{"result":[]}

this is the image path/url : http://webkunj.com/android_api/productUpload/0.png

Body:
You have made all things properly
just replace

$connection = mysqli_connect("localhost","webkuv1c_naman","naman","webkuv1c_android_api") or die("Error " . mysqli_error($connection));

with

 $con = mysqli_connect("localhost","webkuv1c_naman","naman","webkuv1c_android_api") or die("Error " . mysqli_error($con));


问:
Create a new Ruby on Rails application using MySQL instead of SQLite
I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?</p>

答:
For Rails 3 you can use this command to create a new project using mysql:</p>

```<code>$ rails new projectname -d mysql
</code>```

LastEditorDisplayName: Justin Standard

Body:
For Rails 3 you can use this command to create a new project using mysql:

$ rails new projectname -d mysql


问:
Submit form is not triggger in jquery
Here is the form:

```<code><form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
  <input type="submit" value="To Confirm" name="To-Confirm" />
  <span>Click</span>
</form>
</code>```

Jquery:

```<code>span.onclick = function() {
  alert($('#frmSelect').length);

  $('#frmSelect').submit(function() {
    alert('abc');
    //var data = $("#frmSelect :input").serializeArray();
    //alert('Handler for .submit() called.');
    //OR
    //document.frmSelect.submit(); <-- Not Working Too
    //var x = document.getElementsByName("To-Confirm").value; <-- Always "undefined".
  });
}
</code>```

When I clicked on a  element, I am able to get the first alert with "1" (the length of form), but I am not able to get the second alert (which is abc).

p.s. there are many form elements but different name.

答:
There are two ways to call the jQuery submit method:

To submit the form

To do something when the form is submitted

The way you call submit (with the callback argument), you are only trying to do the second thing, so you are not submitting the form. To also submit it, add the submit call without arguments.

Secondly, it is often a bad idea to assign an event handler within another event handler. So, only submit the form inside the click handler, but don't define the submit event handler there.

As a side note, why not keeping with the jQuery syntax also for the span?

```<code>$(span).click(function() {
    alert($('#frmSelect').length);
    $('#frmSelect').submit(); // <-- this submits the form
});

$('#frmSelect').submit(function() {
    alert('abc'); // <-- this executes when the form is submitted.
});
</code>```

Title: Submit form is not triggger in jquery

Body:
Here is the form:

<form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
  <input type="submit" value="To Confirm" name="To-Confirm" />
  Click
</form>

Jquery:

span.onclick = function() {
  alert($('#frmSelect').length);

  $('#frmSelect').submit(function() {
    alert('abc');
    //var data = $("#frmSelect :input").serializeArray();
    //alert('Handler for .submit() called.');
    //OR
    //document.frmSelect.submit(); <-- Not Working Too
    //var x = document.getElementsByName("To-Confirm").value; <-- Always "undefined".
  });
}

When I clicked on a  element, I am able to get the first alert with "1" (the length of form), but I am not able to get the second alert (which is abc).

p.s. there are many form elements but different name.

Body:
There are two ways to call the jQuery submit method:

To submit the form

To do something when the form is submitted

The way you call submit (with the callback argument), you are only trying to do the second thing, so you are not submitting the form. To also submit it, add the submit call without arguments.

Secondly, it is often a bad idea to assign an event handler within another event handler. So, only submit the form inside the click handler, but don't define the submit event handler there.

As a side note, why not keeping with the jQuery syntax also for the span?

$(span).click(function() {
    alert($('#frmSelect').length);
    $('#frmSelect').submit(); // <-- this submits the form
});

$('#frmSelect').submit(function() {
    alert('abc'); // <-- this executes when the form is submitted.
});