问:
what is the use of if else statements?
I don't quite understand the meaning of else if statements.

why not just to continue with the if statements in case one is false?

it works the same.

example with if only that will work the same with else if:

```<code>function testSize(num) {

  if (num < 5){

     return "Tiny";
  }

  if (num < 10){

    return "small";
  }

  return "Change Me";

}

testSize(7);
</code>```

答:
else if should be used when there are multiple conditions and you want only one of them to be executed, for instance:

```<code>if(num<3){ console.log('less than 3') }
else if(num<2){ console.log('less than 2')
</code>```

If you use multiple if statements instead of using else if, it will be true for both the conditions if num = 1, and therefore it will print both the statements.

Multiple if statements are used when you want to run the code inside all those if statements whose conditions are true.

In your case it doesn't make a difference because the function will stop and return at the very first return statement it encounters. But let's say, the blocks' orders are interchanged, then your function will never return 'tiny' even if num = (anything less than 5).

I hope that helps!

Title: what is the use of if else statements?

Body:
I don't quite understand the meaning of else if statements.

why not just to continue with the if statements in case one is false?

it works the same.

example with if only that will work the same with else if:

function testSize(num) {

  if (num < 5){

     return "Tiny";
  }

  if (num < 10){

    return "small";
  }

  return "Change Me";

}

testSize(7);

Body:
else if should be used when there are multiple conditions and you want only one of them to be executed, for instance:

if(num<3){ console.log('less than 3') }
else if(num<2){ console.log('less than 2')

If you use multiple if statements instead of using else if, it will be true for both the conditions if num = 1, and therefore it will print both the statements.

Multiple if statements are used when you want to run the code inside all those if statements whose conditions are true.

In your case it doesn't make a difference because the function will stop and return at the very first return statement it encounters. But let's say, the blocks' orders are interchanged, then your function will never return 'tiny' even if num = (anything less than 5).

I hope that helps!


来源: stackexchange

问:
HTML Input text side by side
i've been trying to figure out how to make the input text and input button side by side. Not only that, it seems my text-align : center is not applying for the text input.

I'm trying not to add multiple spaces just to indent the placeholder.

I've been trying various way but i'm still stuck :
Codepen :-

https://codepen.io/jayvicious/pen/dRyJKE
HTML :

```<code><div class="cell at-bottom">
      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">
    </div>
</code>```

CSS:

```<code>input[type=text], select {
text-allign:center;
padding: 12px 20px;
margin: auto;
display: inline-block;
border: 1px solid  #000000;

}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    text-align: center;
    color:red;
  padding: 14px 45px;
  margin: 8px 0;
  border: 1px solid  #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}
</code>```

My expected output should be something like this :

EDIT : Center issue has been fixed by matthias gwiozda
Link that fixed it : Center HTML Input Text Field Placeholder

答:
Your placeholder problem was that you spelt text-align as text-allign. You don't need WebKit integration if you want to style all the text to the center. If you want to center just the placeholder then you will have to use WebKit integration.

For your spacing problem, try adding this block to your css:

```<code>select {
    -webkit-appearance: none;
    -webkit-border-radius: 0px;
    background: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24' viewBox='0 0 24 24'><path fill='#444' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>");
    background-position: 100% 50%;
    background-repeat: no-repeat;
}
</code>```

(select styling taken from this SO answer)

Another thing I did to fix the spacing was to put all the inputs into a table, this seemed to fix it.

input[type=text],
select {
  text-align: center;
  padding: 12px 20px;
  margin: none;
  display: inline-block;
  border: 1px solid #000000;
}

input[type=submit] {
  font-family: 'arial', sans-serif;
  background-color: white;
  text-align: center;
  color: red;
  padding: 12.5px 45px;
  border: 1px solid #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
  border-collapse: collapse;
}

.cell.at-bottom td {
  padding: 0;
  margin: 0;
}

select {
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
  background: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24' viewBox='0 0 24 24'><path fill='#444' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>");
  background-position: 100% 50%;
  background-repeat: no-repeat;
  width: 90px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="cell at-bottom"><tr><td><input type="text" placeholder="All Japan Cities" class="formElement"></td><td><input type="text" placeholder="Check In Date" class="formElement"></td><td><input type="text" placeholder="Check Out Date" class="formElement"></td><td><select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select></td><td><input type="submit" value="Search" class="formElement"></tr></table></code>```

ContentLicense: CC BY-SA 3.0

Title: HTML Input text side by side

Body:
i've been trying to figure out how to make the input text and input button side by side. Not only that, it seems my text-align : center is not applying for the text input.

I'm trying not to add multiple spaces just to indent the placeholder.

I've been trying various way but i'm still stuck :
Codepen :-

https://codepen.io/jayvicious/pen/dRyJKE
HTML :

      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">

CSS:

input[type=text], select {
text-allign:center;
padding: 12px 20px;
margin: auto;
display: inline-block;
border: 1px solid  #000000;

}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    text-align: center;
    color:red;
  padding: 14px 45px;
  margin: 8px 0;
  border: 1px solid  #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}

My expected output should be something like this :

EDIT : Center issue has been fixed by matthias gwiozda
Link that fixed it : Center HTML Input Text Field Placeholder

Body:
Your placeholder problem was that you spelt text-align as text-allign. You don't need WebKit integration if you want to style all the text to the center. If you want to center just the placeholder then you will have to use WebKit integration.

For your spacing problem, try adding this block to your css:

select {
    -webkit-appearance: none;
    -webkit-border-radius: 0px;
    background: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24' viewBox='0 0 24 24'><path fill='#444' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>");
    background-position: 100% 50%;
    background-repeat: no-repeat;
}

(select styling taken from this SO answer)

Another thing I did to fix the spacing was to put all the inputs into a table, this seemed to fix it.

input[type=text],
select {
  text-align: center;
  padding: 12px 20px;
  margin: none;
  display: inline-block;
  border: 1px solid #000000;
}

input[type=submit] {
  font-family: 'arial', sans-serif;
  background-color: white;
  text-align: center;
  color: red;
  padding: 12.5px 45px;
  border: 1px solid #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
  border-collapse: collapse;
}

.cell.at-bottom td {
  padding: 0;
  margin: 0;
}

select {
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
  background: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24' viewBox='0 0 24 24'><path fill='#444' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>");
  background-position: 100% 50%;
  background-repeat: no-repeat;
  width: 90px;
}

<table class="cell at-bottom"><tr><td><input type="text" placeholder="All Japan Cities" class="formElement"></td><td><input type="text" placeholder="Check In Date" class="formElement"></td><td><input type="text" placeholder="Check Out Date" class="formElement"></td><td><select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select></td><td><input type="submit" value="Search" class="formElement"></tr></table>


问:
How to trigger event on dynamically generated elements (in mootools)
Example to demonstrate the issue can be found here:

http://jsfiddle.net/Byyu2/

As you can see only the first "Add" button triggers an event. The dynamically generated button does not. This is understandable as on page load these elements have not been created.

So what do I need to change to enable dynamically generated elements to also be registered to an event?

Thanks for looking.

答: An answer on implementing .live (from jQuery) in mootools may be of some use.</p>

ContentLicense: CC BY-SA 2.5


问:
PHP is not getting data from MySQL
I have the next problem:

My code is this one:

```<code>$id=$_SESSION["id"];
$query="select id_period from periods where id_group=$id and end=NULL";
$result=mysqli_query($conn,$query);

if(mysqli_num_rows($result)==0){
$insert=mysqli_query($conn,"insert into periods(id_group) values($id)");
}

while($row=mysqli_fetch_row($result)){
   $period=$row['id_period'];
}

$query="insert into times(id_period,id_group) values($period,$id)";
echo $query;
$insert=mysqli_query($conn,$query);
</code>```

This code should search if exists a 'period' with field 'end'=NULL. If not, then insert a new one. That works fine. However, the next part doesn't working. The insert into 'times' query needs the id_period, given by the var $period, but the WHILE never runs.

Any idea? Thank you.

答:
I find problem in below while code

```<code>while($row=mysqli_fetch_row($result)) {
   $period=$row['id_period'];
}
</code>```

In this for fetching data from result set you have use mysqli_fetch_row as per php documentation http://php.net/manual/en/mysqli-result.fetch-row.php  mysqli_fetch_row — Get a result row as an enumerated array.

If you are interested in getting data using name as an index then please use
http://php.net/manual/en/mysqli-result.fetch-assoc.php it mysqli_fetch_assoc — Fetch a result row as an associative array.

Hopes it helps you.

Title: PHP is not getting data from MySQL

Body:
I have the next problem:

My code is this one:

$id=$_SESSION["id"];
$query="select id_period from periods where id_group=$id and end=NULL";
$result=mysqli_query($conn,$query);

if(mysqli_num_rows($result)==0){
$insert=mysqli_query($conn,"insert into periods(id_group) values($id)");
}

while($row=mysqli_fetch_row($result)){
   $period=$row['id_period'];
}

$query="insert into times(id_period,id_group) values($period,$id)";
echo $query;
$insert=mysqli_query($conn,$query);

This code should search if exists a 'period' with field 'end'=NULL. If not, then insert a new one. That works fine. However, the next part doesn't working. The insert into 'times' query needs the id_period, given by the var $period, but the WHILE never runs.

Any idea? Thank you.

Body:
I find problem in below while code

while($row=mysqli_fetch_row($result)) {
   $period=$row['id_period'];
}

In this for fetching data from result set you have use mysqli_fetch_row as per php documentation http://php.net/manual/en/mysqli-result.fetch-row.php  mysqli_fetch_row — Get a result row as an enumerated array.

If you are interested in getting data using name as an index then please use
http://php.net/manual/en/mysqli-result.fetch-assoc.php it mysqli_fetch_assoc — Fetch a result row as an associative array.

Hopes it helps you.


问:
Two TimePickers comparison
So I have allowed the user to pick two Dates Start and End time and connected to Notification Method that will check if the Current time is between his choosing. However the comparison doesn't seem to return the correct result.
Here are the method inside the BrodcatRecevier:

```<code>    public void CheackAlarmAllow(){
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    FinalTime = Calendar.getInstance();
    FinalTime.get(Calendar.HOUR);
    FinalTime.get(Calendar.MINUTE);
    FinalTime.get(Calendar.SECOND);
    FinalTimeS = dateFormat.format (FinalTime.getTime());

    DatabaseHelper db = new DatabaseHelper(this);
    ProfileHelper response = db.getNotification();

    try {
        FirstTime = dateFormat.parse (response.StartTimePicker);
        SecondTime = dateFormat.parse (response.EndimePicker);
        FinalTimeD = dateFormat.parse (FinalTimeS);

    }catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(FinalTimeD.after(FirstTime)&& FinalTime.before(SecondTime))
    {
        Log.w("Not Allowed","Working");
    }
    else
    {
        Log.w("FirstTime", String.valueOf(FirstTime));
        Log.w("Second", String.valueOf(SecondTime));
        Log.w("Final", String.valueOf(FinalTimeD));
        Log.w(" Allowed","Working");
        createNotification();
    }
}
</code>```

And Here the Log returns.

```<code>06-03 08:14:10.597 30078-7708/com.ahmad.Project W/FirstTime: Thu Jan 01
03:00:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/Second: Thu Jan 01
10:00:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/Final: Thu Jan 01
08:14:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/ Allowed: Working
</code>```

答:
Your if check if(FinalTimeD.after(FirstTime)&& FinalTime.before(SecondTime))  fails because FirstTime and SeconfTime are of type Date and Calendar.after() returns true only if the param passed is of type Calendar

From the Oracle documentation of Calender.after():-

public boolean after(Object when) Returns whether this Calendar
  represents a time after the time represented by the specified Object.
  This method is equivalent to:

  compareTo(when) > 0   if and only if when is a Calendar instance. Otherwise, the method returns false.

EDIT (Copying code snippet from comments below for completeness)

```<code>Calendar calendar = Calendar.getInstance();
Date newDate = calendar.setTime(date);
</code>```

Title: Two TimePickers comparison

Body:
So I have allowed the user to pick two Dates Start and End time and connected to Notification Method that will check if the Current time is between his choosing. However the comparison doesn't seem to return the correct result.
Here are the method inside the BrodcatRecevier:

    public void CheackAlarmAllow(){
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    FinalTime = Calendar.getInstance();
    FinalTime.get(Calendar.HOUR);
    FinalTime.get(Calendar.MINUTE);
    FinalTime.get(Calendar.SECOND);
    FinalTimeS = dateFormat.format (FinalTime.getTime());

    DatabaseHelper db = new DatabaseHelper(this);
    ProfileHelper response = db.getNotification();

    try {
        FirstTime = dateFormat.parse (response.StartTimePicker);
        SecondTime = dateFormat.parse (response.EndimePicker);
        FinalTimeD = dateFormat.parse (FinalTimeS);

    }catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(FinalTimeD.after(FirstTime)&& FinalTime.before(SecondTime))
    {
        Log.w("Not Allowed","Working");
    }
    else
    {
        Log.w("FirstTime", String.valueOf(FirstTime));
        Log.w("Second", String.valueOf(SecondTime));
        Log.w("Final", String.valueOf(FinalTimeD));
        Log.w(" Allowed","Working");
        createNotification();
    }
}

And Here the Log returns.

06-03 08:14:10.597 30078-7708/com.ahmad.Project W/FirstTime: Thu Jan 01
03:00:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/Second: Thu Jan 01
10:00:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/Final: Thu Jan 01
08:14:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/ Allowed: Working

Body:
Your if check if(FinalTimeD.after(FirstTime)&& FinalTime.before(SecondTime))  fails because FirstTime and SeconfTime are of type Date and Calendar.after() returns true only if the param passed is of type Calendar

From the Oracle documentation of Calender.after():-

public boolean after(Object when) Returns whether this Calendar
  represents a time after the time represented by the specified Object.
  This method is equivalent to:

  compareTo(when) > 0   if and only if when is a Calendar instance. Otherwise, the method returns false.

EDIT (Copying code snippet from comments below for completeness)

Calendar calendar = Calendar.getInstance();
Date newDate = calendar.setTime(date);


问:
Jquery's .each method not working
I have created countdown with javascript and jquery. Now i want run the script for each .countdown html markup.
My script get data-attribute from the div container and then run timer according to the data value.
Currently my script show the same timer on all divs.

Countdown

Timer End !

Days

Hrs

Mins

Secs

Timer End !

Days

Hrs

Mins

Secs

Timer End !

Days

Hrs

Mins

Secs

```

答:
Use forEach because it's faster than each.

function countDown() {
  function countDownUpdate() {
  $(".count_down").get().forEach(function(el){
    var countDownValue = $(el).attr("data-countdown");
    var countDownDate = new Date(countDownValue).getTime();
    var now = new Date().getTime();
    var distance = countDownDate - now;
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    $(el).find(".count_down-seconds").html(seconds);
    $(el).find(".count_down-minutes").html(minutes);
    $(el).find(".count_down-hours").html(hours);
    $(el).find(".count_down-days").html(days);
    if (distance < 0) {
      clearInterval(countDownUpdate);
      $(this).find(".count_down-finish").show().siblings().remove();
    }
      })
  }

  countDownUpdate();
  setInterval(countDownUpdate, 1000);

}
// Run Component Function
$(document).ready(function() {
  countDown();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Countdown</h1>
<div class="count_down" data-countdown="2017-06-30T22:10:50+05:30">
  <span class="count_down-finish">Timer End !</span>
  <div><span class="count_down-days"></span><span class="count_down-separator">Days</span></div>
  <div><span class="count_down-hours"></span><span class="count_down-separator">Hrs</span></div>
  <div><span class="count_down-minutes"></span><span class="count_down-separator">Mins</span></div>
  <div><span class="count_down-seconds"></span><span class="count_down-separator">Secs</span></div>
</div>
<div class="count_down" data-countdown="2018-06-01T22:00:00+05:30">
  <span class="count_down-finish">Timer End !</span>
  <div><span class="count_down-days"></span><span class="count_down-separator">Days</span></div>
  <div><span class="count_down-hours"></span><span class="count_down-separator">Hrs</span></div>
  <div><span class="count_down-minutes"></span><span class="count_down-separator">Mins</span></div>
  <div><span class="count_down-seconds"></span><span class="count_down-separator">Secs</span></div>
</div>
<div class="count_down" data-countdown="2018-06-01T22:00:00+05:30">
  <span class="count_down-finish">Timer End !</span>
  <div><span class="count_down-days"></span><span class="count_down-separator">Days</span></div>
  <div><span class="count_down-hours"></span><span class="count_down-separator">Hrs</span></div>
  <div><span class="count_down-minutes"></span><span class="count_down-separator">Mins</span></div>
  <div><span class="count_down-seconds"></span><span class="count_down-separator">Secs</span></div>
</div></code>```

Title: Jquery's .each method not working

Body:
Use forEach because it's faster than each.

function countDown() {
  function countDownUpdate() {
  $(".count_down").get().forEach(function(el){
    var countDownValue = $(el).attr("data-countdown");
    var countDownDate = new Date(countDownValue).getTime();
    var now = new Date().getTime();
    var distance = countDownDate - now;
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    $(el).find(".count_down-seconds").html(seconds);
    $(el).find(".count_down-minutes").html(minutes);
    $(el).find(".count_down-hours").html(hours);
    $(el).find(".count_down-days").html(days);
    if (distance < 0) {
      clearInterval(countDownUpdate);
      $(this).find(".count_down-finish").show().siblings().remove();
    }
      })
  }

  countDownUpdate();
  setInterval(countDownUpdate, 1000);

}
// Run Component Function
$(document).ready(function() {
  countDown();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Countdown</h1>
<div class="count_down" data-countdown="2017-06-30T22:10:50+05:30">
  <span class="count_down-finish">Timer End !</span>
  <div><span class="count_down-days"></span><span class="count_down-separator">Days</span></div>
  <div><span class="count_down-hours"></span><span class="count_down-separator">Hrs</span></div>
  <div><span class="count_down-minutes"></span><span class="count_down-separator">Mins</span></div>
  <div><span class="count_down-seconds"></span><span class="count_down-separator">Secs</span></div>
</div>
<div class="count_down" data-countdown="2018-06-01T22:00:00+05:30">
  <span class="count_down-finish">Timer End !</span>
  <div><span class="count_down-days"></span><span class="count_down-separator">Days</span></div>
  <div><span class="count_down-hours"></span><span class="count_down-separator">Hrs</span></div>
  <div><span class="count_down-minutes"></span><span class="count_down-separator">Mins</span></div>
  <div><span class="count_down-seconds"></span><span class="count_down-separator">Secs</span></div>
</div>
<div class="count_down" data-countdown="2018-06-01T22:00:00+05:30">
  <span class="count_down-finish">Timer End !</span>
  <div><span class="count_down-days"></span><span class="count_down-separator">Days</span></div>
  <div><span class="count_down-hours"></span><span class="count_down-separator">Hrs</span></div>
  <div><span class="count_down-minutes"></span><span class="count_down-separator">Mins</span></div>
  <div><span class="count_down-seconds"></span><span class="count_down-separator">Secs</span></div>
</div>


问:
Laravel TokenMismatchException and dropzone
I'm trying to upload pictures via dropzone, but I get tokenmismatch error even tho I added csrf token everywhere needed, i'm getting quite desperate...

My form

```<code>{!! Form::open(['route' => 'photo.upload', 'id' => 'hello', 'method' => 'POST', 'class' => 'dropzone no-margin dz-clickable']) !!}
    <div class="dz-default dz-message"><span>Drop files here to upload</span></div></form>
{!! Form::close() !!}
</code>```

my script

```<code>Dropzone.autoDiscover = false;

Dropzone.options.hello = {
    paramName: "file", // The name that will be used to transfer the file
    maxFilesize: 5, // MB
    parallelUploads: 2, //limits number of files processed to reduce stress on server
    addRemoveLinks: true,
    headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content'),
    },
    accept: function(file, done) {
        // TODO: Image upload validation
        done();
    },
    sending: function(file, xhr, formData) {

        // Pass token. You can use the same method to pass any other values as well such as a id to associate the image with for example.
        formData.append("_token", $('input[name="_token"]').val() ); // Laravel expect the token post value to be named _token by default
    },
    init: function() {
        this.on("success", function(file, response) {
            // On successful upload do whatever :-)
        });
    }
};

// Manually init dropzone on our element.
var myDropzone = new Dropzone("#hello", {
    url: $('#hello').attr('action')
});
</code>```

Request headers

```<code>...
X-CSRF-Token:P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
...
</code>```

Request Payload

```<code>------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"

P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"

P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="file"; filename="Screen Shot 2016-01-14 at 18.27.40.png"
Content-Type: image/png

------WebKitFormBoundarySKMUFNO6dbgzeQVK--
</code>```

and When I look in the generated form THERE IS the csrf field

```<code><input name="_token" type="hidden" value="P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG">
</code>```

Do you have any idea why it's not working even when I put crsf token where I should?

thank you for your time.

答:
Instead of creating new element which is kinda dirty. You can just include it inside your manually init of dropzone.

```<code>var myDropzone = new Dropzone("#hello", {
            url: $('#hello').attr('action'),
            headers: {
               'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
            }
          });
</code>```

For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications

Body:
I'm trying to upload pictures via dropzone, but I get tokenmismatch error even tho I added csrf token everywhere needed, i'm getting quite desperate...

My form

{!! Form::open(['route' => 'photo.upload', 'id' => 'hello', 'method' => 'POST', 'class' => 'dropzone no-margin dz-clickable']) !!}

Drop files here to upload
</form>
{!! Form::close() !!}

my script

Dropzone.autoDiscover = false;

Dropzone.options.hello = {
    paramName: "file", // The name that will be used to transfer the file
    maxFilesize: 5, // MB
    parallelUploads: 2, //limits number of files processed to reduce stress on server
    addRemoveLinks: true,
    headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content'),
    },
    accept: function(file, done) {
        // TODO: Image upload validation
        done();
    },
    sending: function(file, xhr, formData) {

        // Pass token. You can use the same method to pass any other values as well such as a id to associate the image with for example.
        formData.append("_token", $('input[name="_token"]').val() ); // Laravel expect the token post value to be named _token by default
    },
    init: function() {
        this.on("success", function(file, response) {
            // On successful upload do whatever :-)
        });
    }
};

// Manually init dropzone on our element.
var myDropzone = new Dropzone("#hello", {
    url: $('#hello').attr('action')
});

Request headers

...
X-CSRF-Token:P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
...

Request Payload

------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"

P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"

P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="file"; filename="Screen Shot 2016-01-14 at 18.27.40.png"
Content-Type: image/png

------WebKitFormBoundarySKMUFNO6dbgzeQVK--

and When I look in the generated form THERE IS the csrf field

<input name="_token" type="hidden" value="P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG">

Do you have any idea why it's not working even when I put crsf token where I should?

thank you for your time.

Body:
Instead of creating new element which is kinda dirty. You can just include it inside your manually init of dropzone.

var myDropzone = new Dropzone("#hello", {
            url: $('#hello').attr('action'),
            headers: {
               'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
            }
          });

For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications


问:
Sharing a string between classes ruby
I have several classes that make requests to a site. For example, one class for scraping www.example.com/albums, another for www.example.com/singles etc.

```<code>/lib
   /classes
      /example
        album_request.rb
        singles_request.rb
</code>```

In each of these classes I have a constant defining the external url. e.g.

```<code>module Example
   class AlbumRequest
       BASE_URL = 'http://www.example.com/albums'
   end
end
</code>```

This means I'm repeating example.com in all my classes. What if the hostname suddenly changes?

I think my code would be better like this:

```<code>module Example
   class AlbumRequest
      ALBUM_URL = "#{BASE_URL}/albums"
   end
end
</code>```

Where BASE_URL is defined somewhere else. Where should I define such a constant? If I define it in a lower level module, am I not breaking the dependency inversion principle? Should I be putting it in a config? (even though I can assume the url will not change)

I also want to share a request header hash between all requests.

```<code>REQUEST_HEADERS = {
     'Content-Type' => 'application/json',
      ...
}
</code>```

Thanks.

答: Maybe you can use ENV file  to manage your app,  </p>

Title: Sharing a string between classes ruby

Body:
I have several classes that make requests to a site. For example, one class for scraping www.example.com/albums, another for www.example.com/singles etc.

/lib
   /classes
      /example
        album_request.rb
        singles_request.rb

In each of these classes I have a constant defining the external url. e.g.

module Example
   class AlbumRequest
       BASE_URL = 'http://www.example.com/albums'
   end
end

This means I'm repeating example.com in all my classes. What if the hostname suddenly changes?

I think my code would be better like this:

module Example
   class AlbumRequest
      ALBUM_URL = "#{BASE_URL}/albums"
   end
end

Where BASE_URL is defined somewhere else. Where should I define such a constant? If I define it in a lower level module, am I not breaking the dependency inversion principle? Should I be putting it in a config? (even though I can assume the url will not change)

I also want to share a request header hash between all requests.

REQUEST_HEADERS = {
     'Content-Type' => 'application/json',
      ...
}

Thanks.


问:
Reading a remote file with java on linux
I need to read a remote file using a java app, but the file is in apache server on linux.
I tried with "\\" but doesn't work like windows.
How can i do that?</p>

答:
Try accessing your file via web browser using url formatted like:

```<code>http://server-name-or-ip/path/filename
</code>```

When you see your file in browser, use that url from your Java app, too.

Body:
Try accessing your file via web browser using url formatted like:

http://server-name-or-ip/path/filename

When you see your file in browser, use that url from your Java app, too.


问:
How to change h1 tittle when clicked/make the section centered
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

```<code><Body>
<H1 title = "When this is clicked, the section changes"> Title </ h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</ Body>
</code>```

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

答:
First of all Please correct your html markup to standards and add some javascript code. Check below snippet:

$(document).on('click', 'h1', function(){
  $('#first').text('First section: Modified version.');
});
$(document).on('click', '#first', function(){
  $('h1').css('text-align','center');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1 title = "When this is clicked, the section changes"> Title </h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</body></code>```

Body:
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

 Title

 First section: Original version.

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

Body:
First of all Please correct your html markup to standards and add some javascript code. Check below snippet:

$(document).on('click', 'h1', function(){
  $('#first').text('First section: Modified version.');
});
$(document).on('click', '#first', function(){
  $('h1').css('text-align','center');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1 title = "When this is clicked, the section changes"> Title </h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</body>


问:
Ionic 2 app does not get JWT token from storage
I am using Ionic 2 final version with angular2-jwt plugin. I am successfully logging and receive token which I save to storage

```<code>this.storage.set('id_token', res.token);
</code>```

Once I refresh the page and I try to check authorization in my auth.ts header never sends token. I understand that the problem is with async storage, but I don't know how to solve it. I tried many different solutions...

Also, when I save token in my constants it works perfectly fine.

My app.module.ts looks like this:

```<code>...

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
     noJwtError: true,
     globalHeaders: [{'Content-Type': 'application/json', 'x-academy': 'academy'}],
     tokenGetter: () => storage.get('id_token'),
  }), http);
}

...

providers: [
   {provide: ErrorHandler, useClass: IonicErrorHandler},
   {provide: AuthHttp, useFactory: getAuthHttp, deps: [Http]}
 ...
]
</code>```

And my auth.ts:

```<code>...
@Injectable()
export class Auth {

    serverUrl: string;
    storage: Storage = new Storage();

    constructor(public http: Http,
          public authHttp: AuthHttp,
          public constantsService: ConstantsService,
    ) {
       this.serverUrl = this.constantsService.API_ENDPOINT();

    }

    login(credentials){
      let headers = new Headers({'Content-Type': 'application/json', 'x-academy': 'academy' });
      return this.authHttp.post(this.serverUrl+'/login', JSON.stringify(credentials), {headers: headers})
    }
    ....
    public checkAuthentication(){
       return this.authHttp.post(this.serverUrl+'/restricted',{})
    }
    ....
</code>```

Thank you.

答:
Change you getAuthHttp like this to use localStorage instead of ionic storage:

```<code>export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    globalHeaders: [{'Accept': 'application/json'}],
    //tokenGetter: (() => storage.get('id_token').then((val)=>{return val}) ),
    tokenGetter: (() => JSON.parse(window.localStorage.getItem("id_token"))),
    noJwtError: true,
    headerPrefix: "JWT",
  }), http);
}
</code>```

As far as I can tell, the auth0 sdk is not using Ionic storage to store the id_token anyway... it's just using window.localStorage, so you might as well just use that too and its a synchronous method so avoids this promise stuff.

Body:
I am using Ionic 2 final version with angular2-jwt plugin. I am successfully logging and receive token which I save to storage

this.storage.set('id_token', res.token);

Once I refresh the page and I try to check authorization in my auth.ts header never sends token. I understand that the problem is with async storage, but I don't know how to solve it. I tried many different solutions...

Also, when I save token in my constants it works perfectly fine.

My app.module.ts looks like this:

...

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
     noJwtError: true,
     globalHeaders: [{'Content-Type': 'application/json', 'x-academy': 'academy'}],
     tokenGetter: () => storage.get('id_token'),
  }), http);
}

...

providers: [
   {provide: ErrorHandler, useClass: IonicErrorHandler},
   {provide: AuthHttp, useFactory: getAuthHttp, deps: [Http]}
 ...
]

And my auth.ts:

...
@Injectable()
export class Auth {

    serverUrl: string;
    storage: Storage = new Storage();

    constructor(public http: Http,
          public authHttp: AuthHttp,
          public constantsService: ConstantsService,
    ) {
       this.serverUrl = this.constantsService.API_ENDPOINT();

    }

    login(credentials){
      let headers = new Headers({'Content-Type': 'application/json', 'x-academy': 'academy' });
      return this.authHttp.post(this.serverUrl+'/login', JSON.stringify(credentials), {headers: headers})
    }
    ....
    public checkAuthentication(){
       return this.authHttp.post(this.serverUrl+'/restricted',{})
    }
    ....

Thank you.

Body:
Change you getAuthHttp like this to use localStorage instead of ionic storage:

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    globalHeaders: [{'Accept': 'application/json'}],
    //tokenGetter: (() => storage.get('id_token').then((val)=>{return val}) ),
    tokenGetter: (() => JSON.parse(window.localStorage.getItem("id_token"))),
    noJwtError: true,
    headerPrefix: "JWT",
  }), http);
}

As far as I can tell, the auth0 sdk is not using Ionic storage to store the id_token anyway... it's just using window.localStorage, so you might as well just use that too and its a synchronous method so avoids this promise stuff.


问:
Leave UI on when entering VR mode aframe
Is it possible to leave certain or all ui elements on when entering VR mode? </p>

<p>For example, if I want a health bar in screen-space while in VR mode how would I accomplish this? </p>

答: If the ui elements are "2d" elements laid on top of the 3d scene I don't think you can carry those over into VR mode, but what you might be able to do is create "3d" UI elements in the scene that are in a fixed position relative to the camera.  Although according to Oculus having things like a HUD is discouraged (https://developer.oculus.com/design/latest/concepts/bp_app_ui/)</p>

Body:
Is it possible to leave certain or all ui elements on when entering VR mode?

For example, if I want a health bar in screen-space while in VR mode how would I accomplish this?


问:
onclick function not executing to change image
In the following codepen I'm trying to change the image of an image with id="chrome" using JavaScript but it does not appear to be doing anything. What am I doing wrong and how do I fix. Thank you in advanced.

The first image has an id of chrome and when clicked I'm trying to change the image.

https://codepen.io/centem/pen/NgKEmG

Here is the js I'm using.

```<code>function changeImage() {

    if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
    {
        document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
    }
    else
    {
        document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
    }
}
</code>```

Basically, for the first row that has an chrome icon I would like to change it to an x image upon click.

答: First off, change the <img onclick()="changeImage()" to <img onclick="changeImage()". That doesn't solve your problem if you want to do it for multiple users, as each one of the chrome images needs it's own ID for the function to work on more than one logo.

Body:
In the following codepen I'm trying to change the image of an image with id="chrome" using JavaScript but it does not appear to be doing anything. What am I doing wrong and how do I fix. Thank you in advanced.

The first image has an id of chrome and when clicked I'm trying to change the image.

https://codepen.io/centem/pen/NgKEmG

Here is the js I'm using.

function changeImage() {

    if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
    {
        document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
    }
    else
    {
        document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
    }
}

Basically, for the first row that has an chrome icon I would like to change it to an x image upon click.


问:
group by and select max with value null
I have a next problem with query

```<code>SELECT
T.DETALLE_BECA_ANIO anio,
T.DETALLE_BECA_MES mes,
T.DETALLE_BECA_NIVEL_EDU_ID edu_id,
T.DETALLE_BECA_TRAMO_ID tr_id,

MAX(
CASE
  WHEN T.DETALLE_BECA_TIPO_BENE_ID IS NULL
  THEN NVL(DETALLE_BECA_VALOR,0)
  ELSE 0
END) mant ,
MAX(
  CASE
  WHEN T.DETALLE_BECA_TIPO_BENE_ID = 1
  THEN NVL(DETALLE_BECA_VALOR,0)
  ELSE 0
  END) tras
  FROM
(SELECT DETALLE_BECA_NIVEL_EDU_ID,
  DETALLE_BECA_BECA_ID,
  DETALLE_BECA_TIPO_BENE_ID,
  DETALLE_BECA_VALOR,
  DETALLE_BECA_MES,
  DETALLE_BECA_REGION_ID,
  DETALLE_BECA_PROVINCIA_ID,
  DETALLE_BECA_ANIO,
  DETALLE_BECA_TRAMO_ID,
  DETALLE_BECA_COMUNA_ID
FROM TBL_DETALLE_BECAS

WHERE (DETALLE_BECA_TIPO_BENE_ID = 1
OR DETALLE_BECA_TIPO_BENE_ID   IS NULL)
and DETALLE_BECA_BECA_ID = 1
and detalle_beca_mes = 3
) T
GROUP BY T.DETALLE_BECA_BECA_ID,
T.DETALLE_BECA_TRAMO_ID,
T.DETALLE_BECA_REGION_ID,
T.DETALLE_BECA_PROVINCIA_ID,
T.DETALLE_BECA_ANIO,
T.DETALLE_BECA_MES,
T.DETALLE_BECA_NIVEL_EDU_ID,
T.DETALLE_BECA_COMUNA_ID
ORDER BY T.DETALLE_BECA_BECA_ID,
T.DETALLE_BECA_MES,
T.DETALLE_BECA_NIVEL_EDU_ID
</code>```

output:

```<code>  "ANIO"    "MES"   "EDU_ID"    "TR_ID" "MANT"  "TRAS"
    2017      3         2        0.62     0      NULL
    2017      3         3        1.24     6      NULL
    2017      3        NULL       1.0     NULL     1
</code>```

I need that sum value where EDU_ID is null with value 2,3 in TR_ID and replace value null in "tras" with value from EDU is null

```<code>   "ANIO"   "MES"   "EDU_ID"    "TR_ID" "MANT"  "TRAS"
    2017      3         2        1.62     0      1
    2017      3         3        2.24     6      1
</code>```

I writed query with min(edu_id) or max(edu_id ) but could  not solve my problem.

The other thing that occurred to me is to make a join with the same table

答:
First, this makes more sense as your query:

```<code>SELECT T.DETALLE_BECA_ANIO as anio, T.DETALLE_BECA_MES as mes,
       T.DETALLE_BECA_NIVEL_EDU_ID as edu_id, T.DETALLE_BECA_TRAMO_ID as tr_id,
       MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID IS NULL
                THEN NVL(DETALLE_BECA_VALOR, 0)
                ELSE 0
           END) as mant ,
       MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID = 1
                THEN NVL(DETALLE_BECA_VALOR,0)
                ELSE 0
           END) tras
FROM TBL_DETALLE_BECAS
WHERE (DETALLE_BECA_TIPO_BENE_ID = 1 OR DETALLE_BECA_TIPO_BENE_ID IS NULL) AND
      DETALLE_BECA_BECA_ID = 1 AND
      detalle_beca_mes = 3
GROUP BY T.DETALLE_BECA_ANIO, T.DETALLE_BECA_MES,
         T.DETALLE_BECA_NIVEL_EDU_ID, T.DETALLE_BECA_TRAMO_ID
ORDER BY T.DETALLE_BECA_BECA_ID, T.DETALLE_BECA_MES, T.DETALLE_BECA_NIVEL_EDU_ID;
</code>```

This eliminates the subquery (unnecessary) and only aggregates by the columns being returned.  A proper query might fix your problem.

But, you seem to want to use NULL to be "all" for the other columns.  If so, something like this will work:

```<code>WITH t as (
      SELECT T.DETALLE_BECA_ANIO as anio, T.DETALLE_BECA_MES as mes,
             T.DETALLE_BECA_NIVEL_EDU_ID as edu_id, T.DETALLE_BECA_TRAMO_ID as tr_id,
             MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID IS NULL
                      THEN NVL(DETALLE_BECA_VALOR, 0)
                      ELSE 0
                 END) as mant ,
             MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID = 1
                      THEN NVL(DETALLE_BECA_VALOR,0)
                      ELSE 0
                 END) tras
      FROM TBL_DETALLE_BECAS
      WHERE (DETALLE_BECA_TIPO_BENE_ID = 1 OR DETALLE_BECA_TIPO_BENE_ID IS NULL) AND
            DETALLE_BECA_BECA_ID = 1 AND
            detalle_beca_mes = 3
      GROUP BY T.DETALLE_BECA_ANIO, T.DETALLE_BECA_MES,
             T.DETALLE_BECA_NIVEL_EDU_ID, T.DETALLE_BECA_TRAMO_ID
     )
SELECT t.ANIO, t.MES, t.EDU_ID,
       COALESCE(t.TR_ID, 0) + COALESCE(tnull.TR_ID, 0) as TR_ID,
       t.MANT,
       COALESCE(t.TRAS, 0) + COALESCE(tnull.TRAS, 0) as TRAS
FROM t LEFT JOIN
     (SELECT t.*
      FROM t
      WHERE t.edu_id IS NULL
     ) tnull
     ON tnull.ANIO = t.ANIO AND tnull.MES = t.MES
WHERE t.edu_id IS NOT NULL
ORDER BY T.DETALLE_BECA_BECA_ID, T.DETALLE_BECA_MES, T.DETALLE_BECA_NIVEL_EDU_ID;
</code>```

Title: group by and select max with value null

Body:
I have a next problem with query

SELECT
T.DETALLE_BECA_ANIO anio,
T.DETALLE_BECA_MES mes,
T.DETALLE_BECA_NIVEL_EDU_ID edu_id,
T.DETALLE_BECA_TRAMO_ID tr_id,

MAX(
CASE
  WHEN T.DETALLE_BECA_TIPO_BENE_ID IS NULL
  THEN NVL(DETALLE_BECA_VALOR,0)
  ELSE 0
END) mant ,
MAX(
  CASE
  WHEN T.DETALLE_BECA_TIPO_BENE_ID = 1
  THEN NVL(DETALLE_BECA_VALOR,0)
  ELSE 0
  END) tras
  FROM
(SELECT DETALLE_BECA_NIVEL_EDU_ID,
  DETALLE_BECA_BECA_ID,
  DETALLE_BECA_TIPO_BENE_ID,
  DETALLE_BECA_VALOR,
  DETALLE_BECA_MES,
  DETALLE_BECA_REGION_ID,
  DETALLE_BECA_PROVINCIA_ID,
  DETALLE_BECA_ANIO,
  DETALLE_BECA_TRAMO_ID,
  DETALLE_BECA_COMUNA_ID
FROM TBL_DETALLE_BECAS

WHERE (DETALLE_BECA_TIPO_BENE_ID = 1
OR DETALLE_BECA_TIPO_BENE_ID   IS NULL)
and DETALLE_BECA_BECA_ID = 1
and detalle_beca_mes = 3
) T
GROUP BY T.DETALLE_BECA_BECA_ID,
T.DETALLE_BECA_TRAMO_ID,
T.DETALLE_BECA_REGION_ID,
T.DETALLE_BECA_PROVINCIA_ID,
T.DETALLE_BECA_ANIO,
T.DETALLE_BECA_MES,
T.DETALLE_BECA_NIVEL_EDU_ID,
T.DETALLE_BECA_COMUNA_ID
ORDER BY T.DETALLE_BECA_BECA_ID,
T.DETALLE_BECA_MES,
T.DETALLE_BECA_NIVEL_EDU_ID

output:

  "ANIO"    "MES"   "EDU_ID"    "TR_ID" "MANT"  "TRAS"
    2017      3         2        0.62     0      NULL
    2017      3         3        1.24     6      NULL
    2017      3        NULL       1.0     NULL     1

I need that sum value where EDU_ID is null with value 2,3 in TR_ID and replace value null in "tras" with value from EDU is null

   "ANIO"   "MES"   "EDU_ID"    "TR_ID" "MANT"  "TRAS"
    2017      3         2        1.62     0      1
    2017      3         3        2.24     6      1

I writed query with min(edu_id) or max(edu_id ) but could  not solve my problem.

The other thing that occurred to me is to make a join with the same table

Body:
First, this makes more sense as your query:

SELECT T.DETALLE_BECA_ANIO as anio, T.DETALLE_BECA_MES as mes,
       T.DETALLE_BECA_NIVEL_EDU_ID as edu_id, T.DETALLE_BECA_TRAMO_ID as tr_id,
       MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID IS NULL
                THEN NVL(DETALLE_BECA_VALOR, 0)
                ELSE 0
           END) as mant ,
       MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID = 1
                THEN NVL(DETALLE_BECA_VALOR,0)
                ELSE 0
           END) tras
FROM TBL_DETALLE_BECAS
WHERE (DETALLE_BECA_TIPO_BENE_ID = 1 OR DETALLE_BECA_TIPO_BENE_ID IS NULL) AND
      DETALLE_BECA_BECA_ID = 1 AND
      detalle_beca_mes = 3
GROUP BY T.DETALLE_BECA_ANIO, T.DETALLE_BECA_MES,
         T.DETALLE_BECA_NIVEL_EDU_ID, T.DETALLE_BECA_TRAMO_ID
ORDER BY T.DETALLE_BECA_BECA_ID, T.DETALLE_BECA_MES, T.DETALLE_BECA_NIVEL_EDU_ID;

This eliminates the subquery (unnecessary) and only aggregates by the columns being returned.  A proper query might fix your problem.

But, you seem to want to use NULL to be "all" for the other columns.  If so, something like this will work:

WITH t as (
      SELECT T.DETALLE_BECA_ANIO as anio, T.DETALLE_BECA_MES as mes,
             T.DETALLE_BECA_NIVEL_EDU_ID as edu_id, T.DETALLE_BECA_TRAMO_ID as tr_id,
             MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID IS NULL
                      THEN NVL(DETALLE_BECA_VALOR, 0)
                      ELSE 0
                 END) as mant ,
             MAX(CASE WHEN T.DETALLE_BECA_TIPO_BENE_ID = 1
                      THEN NVL(DETALLE_BECA_VALOR,0)
                      ELSE 0
                 END) tras
      FROM TBL_DETALLE_BECAS
      WHERE (DETALLE_BECA_TIPO_BENE_ID = 1 OR DETALLE_BECA_TIPO_BENE_ID IS NULL) AND
            DETALLE_BECA_BECA_ID = 1 AND
            detalle_beca_mes = 3
      GROUP BY T.DETALLE_BECA_ANIO, T.DETALLE_BECA_MES,
             T.DETALLE_BECA_NIVEL_EDU_ID, T.DETALLE_BECA_TRAMO_ID
     )
SELECT t.ANIO, t.MES, t.EDU_ID,
       COALESCE(t.TR_ID, 0) + COALESCE(tnull.TR_ID, 0) as TR_ID,
       t.MANT,
       COALESCE(t.TRAS, 0) + COALESCE(tnull.TRAS, 0) as TRAS
FROM t LEFT JOIN
     (SELECT t.*
      FROM t
      WHERE t.edu_id IS NULL
     ) tnull
     ON tnull.ANIO = t.ANIO AND tnull.MES = t.MES
WHERE t.edu_id IS NOT NULL
ORDER BY T.DETALLE_BECA_BECA_ID, T.DETALLE_BECA_MES, T.DETALLE_BECA_NIVEL_EDU_ID;


问:
Filtering out data in Spark dataframe in Scala
I have a dataframe df, which contains below data:

```<code>**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z
</code>```

I have successfully filtered for data where column val_id is blank

```<code>df.where(col("val_id").isin(""))
</code>```

But I am not able to figure out a way to filter data where column val_id is not blank, i tried something like below, but did not work for me:

```<code>df.where(col("val_id").isnotin(""))
</code>```

Can anyone please help me to achieve it using Spark Scala.

答:
Assuming Val_id is of String type, you can use this inequality operator !==:

```<code>df.where(col("Val_id") !== "").show
</code>```

Conversely, you can also use === for matching the blank.

Body:
I have a dataframe df, which contains below data:

**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z

I have successfully filtered for data where column val_id is blank

df.where(col("val_id").isin(""))

But I am not able to figure out a way to filter data where column val_id is not blank, i tried something like below, but did not work for me:

df.where(col("val_id").isnotin(""))

Can anyone please help me to achieve it using Spark Scala.

Body:
Assuming Val_id is of String type, you can use this inequality operator !==:

df.where(col("Val_id") !== "").show

Conversely, you can also use === for matching the blank.


问:
Rails equivalent to Django's "choices"
I know there is no real equivalent in Rails but my question is mostly about best practice...

In Django, if you want to limit a model field to a limited set of choices, you would do something like this (in your model):

```<code>COLOR_CHOICES = (('B', 'Blue'), ('R', 'Red'))
item_color = models.CharField(choices=COLOR_CHOICES)
</code>```

From my (basic) understanding of Rails, I can achieve something similar, for example, by using a select tag in the forms dealing with adding/editing that model...

My question however is, where would it be appropriate to declare the "choices" hash (again I'm guessing here that a hash is what I need?). Basically I just want it to be easily re-usable in any forms where I might need to present those choices, and when it comes to validating at the model level.

Any help/tips would be appreciated!

答:
On the validation side of things, probably validates_inclusion_of is what you need:

```<code>class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
    :message => "%{value} is not a valid size"
end
</code>```

As for generating the helper, you can try something like:

```<code>class Coffee < ActiveRecord::Base
  @@coffe_size = %w(small medium large)

  validates_inclusion_of :size, :in => @@coffe_size,
    :message => "%{value} is not a valid size"

   def self.coffee_size_options
       @@coffe_size.map{ |z| [z,z]}
   end
end
</code>```

And then in some helper:

```<code><%= select(:coffee, :size, Coffee.coffee_size_options) %>
</code>```

Title: Rails equivalent to Django's "choices"

Body:
I know there is no real equivalent in Rails but my question is mostly about best practice...

In Django, if you want to limit a model field to a limited set of choices, you would do something like this (in your model):

COLOR_CHOICES = (('B', 'Blue'), ('R', 'Red'))
item_color = models.CharField(choices=COLOR_CHOICES)

From my (basic) understanding of Rails, I can achieve something similar, for example, by using a select tag in the forms dealing with adding/editing that model...

My question however is, where would it be appropriate to declare the "choices" hash (again I'm guessing here that a hash is what I need?). Basically I just want it to be easily re-usable in any forms where I might need to present those choices, and when it comes to validating at the model level.

Any help/tips would be appreciated!

Body:
On the validation side of things, probably validates_inclusion_of is what you need:

class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
    :message => "%{value} is not a valid size"
end

As for generating the helper, you can try something like:

class Coffee < ActiveRecord::Base
  @@coffe_size = %w(small medium large)

  validates_inclusion_of :size, :in => @@coffe_size,
    :message => "%{value} is not a valid size"

   def self.coffee_size_options
       @@coffe_size.map{ |z| [z,z]}
   end
end

And then in some helper:

<%= select(:coffee, :size, Coffee.coffee_size_options) %>


问:
Kuberetes V1.6.2 flannel not running on master node
I am running 2 node cluster using vagrant, configured with kubeadm command. When I setup the cluster flannel was running on all three nodes. Now i don't see flannel running  in master node. because of this overlay network is not working from master node.

Used this yaml files to configure flannel.

```<code>kubectl create -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel-rbac.yml
kubectl create -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

# kubectl get pods --all-namespaces -o wide |grep fla
kube-system   kube-flannel-ds-0d3bn                       2/2       Running   0          20m       192.168.15.102   node-01
kube-system   kube-flannel-ds-86bzs                       2/2       Running   0          20m       192.168.15.103   node-02

#  k get nodes -o wide
NAME       STATUS    AGE       VERSION   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION
master01   Ready     26d       v1.6.2    <none>        CentOS Linux 7 (Core)   3.10.0-514.10.2.el7.x86_64
node-01    Ready     26d       v1.6.2    <none>        CentOS Linux 7 (Core)   3.10.0-514.10.2.el7.x86_64
node-02    Ready     26d       v1.6.2    <none>        CentOS Linux 7 (Core)   3.10.0-514.10.2.el7.x86_64
</code>```

How can I start the flannel pod in my master node?

答:
I see you using RBAC, maybe there are not enough rights at a node.
Try creating a clusterrolebinding with the necessary rights

$ kubectl create clusterrolebinding nodeName --clusterrole=system:node --
user=nodeName

or can use cluster-admin for testing

Body:
I am running 2 node cluster using vagrant, configured with kubeadm command. When I setup the cluster flannel was running on all three nodes. Now i don't see flannel running  in master node. because of this overlay network is not working from master node.

Used this yaml files to configure flannel.

kubectl create -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel-rbac.yml
kubectl create -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

# kubectl get pods --all-namespaces -o wide |grep fla
kube-system   kube-flannel-ds-0d3bn                       2/2       Running   0          20m       192.168.15.102   node-01
kube-system   kube-flannel-ds-86bzs                       2/2       Running   0          20m       192.168.15.103   node-02

#  k get nodes -o wide
NAME       STATUS    AGE       VERSION   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION
master01   Ready     26d       v1.6.2    <none>        CentOS Linux 7 (Core)   3.10.0-514.10.2.el7.x86_64
node-01    Ready     26d       v1.6.2    <none>        CentOS Linux 7 (Core)   3.10.0-514.10.2.el7.x86_64
node-02    Ready     26d       v1.6.2    <none>        CentOS Linux 7 (Core)   3.10.0-514.10.2.el7.x86_64

How can I start the flannel pod in my master node?


问:
Arquillian TomEE embedded javax.naming.ConfigurationException after first test
I'm using Arquillian with TomEE-embedded to test a SpringLoggerBeanProducer which uses CDI to construct a logger object, which in turn can be injected into a Spring container using a bean producing method. The issue I run into is that there are 5 types of loggers which can be produced. When I run the tests (each producing one type of logger), only the test which is executed first succeeds, whilst all following tests fail due to a javax.naming.ConfigurationException.
It appears as if only the first test is executed in a JEE server environment, whilst the others are not.

The code for the producer is as follows:

```<code>package mypackage.monitoring.spring.logger.producer;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import mypackage.monitoring.shared.logger.Logger;
import mypackage.monitoring.shared.qualifier.Application;
import mypackage.monitoring.shared.qualifier.Business;
import mypackage.monitoring.shared.qualifier.Security;
import mypackage.monitoring.shared.qualifier.Technical;

@Configuration
public class SpringLoggerBeanProducer {

private BeanManager beanManager;

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Application
public Logger applicationLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Business
public Logger businessLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Security
public Logger securityLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Technical
public Logger technicalLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

private Logger logger(org.springframework.beans.factory.InjectionPoint springIp) {
    setBeanManager();
    Field field = springIp.getField();
    Annotation[] qualifiers = getFieldQualifiers(field);
    Bean<? extends Object> bean = getLoggerBean(qualifiers);
    return getInjectableLoggerReference(field, bean);
}

private Logger getInjectableLoggerReference(Field field, Bean<?> bean) {
    CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
    return (Logger) beanManager.getInjectableReference(getInjectionPoint(field), creationalContext);
}

private Bean<? extends Object> getLoggerBean(Annotation[] qualifiers) {
    Set<Bean<?>> beans = beanManager.getBeans(Logger.class, qualifiers);
    return beanManager.resolve(beans);
}

private Annotation[] getFieldQualifiers(Field field) {
    Annotation[] annotations = field.getAnnotations();

    Set<Annotation> qualifierSet = getQualifierSet(annotations);
    annotations = qualifierSet.toArray(new Annotation[0]);
    return annotations;
}

private void setBeanManager() {
    try {
        if (beanManager == null) {
            beanManager = InitialContext.doLookup("java:comp/BeanManager");
        }
    } catch (NamingException e) {
        throw new LoggerProducerException("BeanManager not found.", e);
    }
}

private Set<Annotation> getQualifierSet(Annotation[] annotations) {
    Set<Annotation> qualifierSet = new HashSet<Annotation>();
    for (Annotation annotation : annotations) {
        if (annotation.annotationType().isAnnotationPresent(javax.inject.Qualifier.class)) {
            qualifierSet.add(annotation);
        }
    }
    return qualifierSet;
}

private InjectionPoint getInjectionPoint(final Field member) {
    class GeneratedInjectionPoint implements InjectionPoint {

        @Override
        public boolean isTransient() {
            return Modifier.isTransient(member.getModifiers());
        }

        @Override
        public boolean isDelegate() {
            return false;
        }

        @Override
        public Type getType() {
            return member.getType();
        }

        @Override
        public Set<Annotation> getQualifiers() {
            Annotation[] annotations = member.getAnnotations();
            return getQualifierSet(annotations);
        }

        @Override
        public Member getMember() {
            return member;
        }

        @Override
        public Bean<?> getBean() {
            return null;
        }

        @Override
        public Annotated getAnnotated() {
            throw new UnsupportedOperationException("Method not implemented for " + this.getClass().getSimpleName() + ".class");
        }
    }

    return new GeneratedInjectionPoint();
}
}
</code>```

The exception occurs at the line beanManager = InitialContext.doLookup("java:comp/BeanManager");

The code for the test:

```<code>package mypackage.monitoring.spring.logger.producer;

import static org.junit.Assert.assertThat;

import java.lang.reflect.Field;

import javax.inject.Inject;

import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.InjectionPoint;

import mypackage.monitoring.shared.event.MonitorEventType;
import mypackage.monitoring.shared.logger.Logger;
import mypackage.monitoring.shared.qualifier.Application;
import mypackage.monitoring.shared.qualifier.Business;
import mypackage.monitoring.shared.qualifier.Security;
import mypackage.monitoring.shared.qualifier.Technical;

@RunWith(Arquillian.class)
public class SpringLoggerBeanProducerIT<X> {

@Inject
private SpringLoggerBeanProducer producer;

private Logger defaultLogger;
@Application
private Logger applicationLogger;
@Business
private Logger businessLogger;
@Security
private Logger securityLogger;
@Technical
private Logger technicalLogger;

@Deployment
public static JavaArchive createDeployment() {
    return ShrinkWrap.create(JavaArchive.class).addPackages(true, "mypackage")
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}

@Test
public void alsDefaultLoggerDanMonitorEventTypeTechnical() throws Exception {
    System.out.println("Default Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("defaultLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.TECHNICAL));
}

@Test
public void alsApplicationLoggerDanMonitorEventTypeApplication() throws Exception {
    System.out.println("Application Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("applicationLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.APPLICATION));
}

@Test
public void alsBusinessLoggerDanMonitorEventTypeBusiness() throws Exception {
    System.out.println("Business Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("businessLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.BUSINESS));
}

@Test
public void alsSecurityLoggerDanMonitorEventTypeSecurity() throws Exception {
    System.out.println("Security Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("securityLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.SECURITY));
}

@Test
public void alsTechnicalLoggerDanMonitorEventTypeTechnical() throws Exception {
    System.out.println("Technical Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("technicalLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.TECHNICAL));
}

}
</code>```

I have added the following Maven dependencies to my project:

```<code>    <!-- Arquillian junit testen -->
    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <version>1.1.9.FINAL</version>
        <scope>test</scope>
    </dependency>

    <!-- Arquillian adapter voor TomEE -->
    <dependency>
        <groupId>org.apache.openejb</groupId>
        <artifactId>arquillian-tomee-embedded</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>

    <!-- Embedded container TomEE -->
    <dependency>
        <groupId>org.apache.openejb</groupId>
        <artifactId>tomee-embedded</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
</code>```

Test results

Stacktrace

答:
It seems some part of the application messes up tomee JNDI space (an ibm client jar?). You can try to force the context factory: org.apache.openejb.core.OpenEJBInitialContextFactory

Side note: maybe also upgrade to tomee 7.0.3?

Body:
I'm using Arquillian with TomEE-embedded to test a SpringLoggerBeanProducer which uses CDI to construct a logger object, which in turn can be injected into a Spring container using a bean producing method. The issue I run into is that there are 5 types of loggers which can be produced. When I run the tests (each producing one type of logger), only the test which is executed first succeeds, whilst all following tests fail due to a javax.naming.ConfigurationException.
It appears as if only the first test is executed in a JEE server environment, whilst the others are not.

The code for the producer is as follows:

package mypackage.monitoring.spring.logger.producer;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import mypackage.monitoring.shared.logger.Logger;
import mypackage.monitoring.shared.qualifier.Application;
import mypackage.monitoring.shared.qualifier.Business;
import mypackage.monitoring.shared.qualifier.Security;
import mypackage.monitoring.shared.qualifier.Technical;

@Configuration
public class SpringLoggerBeanProducer {

private BeanManager beanManager;

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Application
public Logger applicationLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Business
public Logger businessLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Security
public Logger securityLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

@org.springframework.context.annotation.Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Technical
public Logger technicalLogger(org.springframework.beans.factory.InjectionPoint springIp) {
    return logger(springIp);
}

private Logger logger(org.springframework.beans.factory.InjectionPoint springIp) {
    setBeanManager();
    Field field = springIp.getField();
    Annotation[] qualifiers = getFieldQualifiers(field);
    Bean<? extends Object> bean = getLoggerBean(qualifiers);
    return getInjectableLoggerReference(field, bean);
}

private Logger getInjectableLoggerReference(Field field, Bean<?> bean) {
    CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
    return (Logger) beanManager.getInjectableReference(getInjectionPoint(field), creationalContext);
}

private Bean<? extends Object> getLoggerBean(Annotation[] qualifiers) {
    Set<Bean<?>> beans = beanManager.getBeans(Logger.class, qualifiers);
    return beanManager.resolve(beans);
}

private Annotation[] getFieldQualifiers(Field field) {
    Annotation[] annotations = field.getAnnotations();

    Set<Annotation> qualifierSet = getQualifierSet(annotations);
    annotations = qualifierSet.toArray(new Annotation[0]);
    return annotations;
}

private void setBeanManager() {
    try {
        if (beanManager == null) {
            beanManager = InitialContext.doLookup("java:comp/BeanManager");
        }
    } catch (NamingException e) {
        throw new LoggerProducerException("BeanManager not found.", e);
    }
}

private Set<Annotation> getQualifierSet(Annotation[] annotations) {
    Set<Annotation> qualifierSet = new HashSet<Annotation>();
    for (Annotation annotation : annotations) {
        if (annotation.annotationType().isAnnotationPresent(javax.inject.Qualifier.class)) {
            qualifierSet.add(annotation);
        }
    }
    return qualifierSet;
}

private InjectionPoint getInjectionPoint(final Field member) {
    class GeneratedInjectionPoint implements InjectionPoint {

        @Override
        public boolean isTransient() {
            return Modifier.isTransient(member.getModifiers());
        }

        @Override
        public boolean isDelegate() {
            return false;
        }

        @Override
        public Type getType() {
            return member.getType();
        }

        @Override
        public Set<Annotation> getQualifiers() {
            Annotation[] annotations = member.getAnnotations();
            return getQualifierSet(annotations);
        }

        @Override
        public Member getMember() {
            return member;
        }

        @Override
        public Bean<?> getBean() {
            return null;
        }

        @Override
        public Annotated getAnnotated() {
            throw new UnsupportedOperationException("Method not implemented for " + this.getClass().getSimpleName() + ".class");
        }
    }

    return new GeneratedInjectionPoint();
}
}

The exception occurs at the line beanManager = InitialContext.doLookup("java:comp/BeanManager");

The code for the test:

package mypackage.monitoring.spring.logger.producer;

import static org.junit.Assert.assertThat;

import java.lang.reflect.Field;

import javax.inject.Inject;

import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.InjectionPoint;

import mypackage.monitoring.shared.event.MonitorEventType;
import mypackage.monitoring.shared.logger.Logger;
import mypackage.monitoring.shared.qualifier.Application;
import mypackage.monitoring.shared.qualifier.Business;
import mypackage.monitoring.shared.qualifier.Security;
import mypackage.monitoring.shared.qualifier.Technical;

@RunWith(Arquillian.class)
public class SpringLoggerBeanProducerIT<X> {

@Inject
private SpringLoggerBeanProducer producer;

private Logger defaultLogger;
@Application
private Logger applicationLogger;
@Business
private Logger businessLogger;
@Security
private Logger securityLogger;
@Technical
private Logger technicalLogger;

@Deployment
public static JavaArchive createDeployment() {
    return ShrinkWrap.create(JavaArchive.class).addPackages(true, "mypackage")
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}

@Test
public void alsDefaultLoggerDanMonitorEventTypeTechnical() throws Exception {
    System.out.println("Default Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("defaultLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.TECHNICAL));
}

@Test
public void alsApplicationLoggerDanMonitorEventTypeApplication() throws Exception {
    System.out.println("Application Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("applicationLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.APPLICATION));
}

@Test
public void alsBusinessLoggerDanMonitorEventTypeBusiness() throws Exception {
    System.out.println("Business Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("businessLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.BUSINESS));
}

@Test
public void alsSecurityLoggerDanMonitorEventTypeSecurity() throws Exception {
    System.out.println("Security Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("securityLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.SECURITY));
}

@Test
public void alsTechnicalLoggerDanMonitorEventTypeTechnical() throws Exception {
    System.out.println("Technical Logger");
    Logger logger = producer.applicationLogger(new InjectionPoint(this.getClass().getDeclaredField("technicalLogger")));

    assertThat(logger, Matchers.notNullValue());

    Field typeField = logger.getClass().getSuperclass().getDeclaredField("type");
    typeField.setAccessible(true);
    MonitorEventType type = (MonitorEventType) typeField.get(logger);

    assertThat(type, Matchers.is(MonitorEventType.TECHNICAL));
}

}

I have added the following Maven dependencies to my project:

    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <version>1.1.9.FINAL</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.openejb</groupId>
        <artifactId>arquillian-tomee-embedded</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.openejb</groupId>
        <artifactId>tomee-embedded</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>

Test results

Stacktrace


答:
You have a syntax error in your HTML code. onclick is not a function, it is an HTML attribute, so you don't call it like a function by adding parentheses to it.

You only to that to the value of the onclick attribute, which is JavaScript syntax.

The correct code is:

```<code><img onclick="changeImage()">
</code>```

Here is a working version of your code pen: https://codepen.io/pahund/pen/XgWVQx

Title: onclick function not executing to change image

Body:
You have a syntax error in your HTML code. onclick is not a function, it is an HTML attribute, so you don't call it like a function by adding parentheses to it.

You only to that to the value of the onclick attribute, which is JavaScript syntax.

The correct code is:

<img onclick="changeImage()">

Here is a working version of your code pen: https://codepen.io/pahund/pen/XgWVQx


问:
Button not visible inside Linear Layout
I have this vehicle_list_fragment_layout.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Layout per il fragment VehicleListFragment. -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/recycler_view_fragment_layout"/>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="+"/>
</LinearLayout>
</code>```

which is used by my VehicleListFragment in this way:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.vehicle_list_fragment_layout, container, false);
    btnStartActivity = (Button) rootView.findViewById(R.id.btnAddVehicle);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mLayoutManager = new LinearLayoutManager(getActivity());

    setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);
    initAdapter();
    mRecyclerView.setAdapter(mAdapter);
    setButtonClickListener();

    return rootView;
}
</code>```

The problem is that the RecyclerView is shown correctly, but my btnAddVehicle is not shown.

This is activity_vehicle_layout.xml, the layout of the Activity which hosts my VehicleListFragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="clyky.cartracker.activities.VehicleActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/vehicleContainer">
    </FrameLayout>
</android.support.constraint.ConstraintLayout>
</code>```

I use vehicleContainer as container for my fragment.
Thanks in advance!

EDIT

this is my recycler_view_fragment_layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Layout per un fragment che contiene una RecyclerView -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:id="@+id/recyclerView">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>
</code>```

答:
Try this in vehicle_list_fragment_layout.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Layout per il fragment VehicleListFragment. -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        layout="@layout/recycler_view_fragment_layout"/>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="+"/>

</LinearLayout>
</code>```

and in recycler_view_fragment_layout.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Layout per un fragment che contiene una RecyclerView -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="vertical"
    tools:layout_height="match_parent"
>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"/>

</LinearLayout>
</code>```

Title: Button not visible inside Linear Layout

Body:
I have this vehicle_list_fragment_layout.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/recycler_view_fragment_layout"/>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="+"/>
</LinearLayout>

which is used by my VehicleListFragment in this way:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.vehicle_list_fragment_layout, container, false);
    btnStartActivity = (Button) rootView.findViewById(R.id.btnAddVehicle);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mLayoutManager = new LinearLayoutManager(getActivity());

    setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);
    initAdapter();
    mRecyclerView.setAdapter(mAdapter);
    setButtonClickListener();

    return rootView;
}

The problem is that the RecyclerView is shown correctly, but my btnAddVehicle is not shown.

This is activity_vehicle_layout.xml, the layout of the Activity which hosts my VehicleListFragment:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="clyky.cartracker.activities.VehicleActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/vehicleContainer">
    </FrameLayout>
</android.support.constraint.ConstraintLayout>

I use vehicleContainer as container for my fragment.
Thanks in advance!

EDIT

this is my recycler_view_fragment_layout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:id="@+id/recyclerView">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

Body:
Try this in vehicle_list_fragment_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<!-- Layout per il fragment VehicleListFragment. -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        layout="@layout/recycler_view_fragment_layout"/>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="+"/>

</LinearLayout>

and in recycler_view_fragment_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<!-- Layout per un fragment che contiene una RecyclerView -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="vertical"
    tools:layout_height="match_parent"
>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"/>

</LinearLayout>


问:
Python : Increase a string
I am not really familiar with Python yet.
I have a string like "11223300". Now I want to increase the last byte of that string ( from "00" to "FF"). I tried to convert the string into an integer ( integer=int(string,16)) and increase it, and convert it back later, but that does not work for me. Maybe one of you guys has a better idea.

```<code>string = "11223300"
counter = int(string, 16)

for i in range(255):
    counter = counter + 1
    IV = hex(counter)
</code>```

Now I want to convert the IV from hex into a string

Thanks!

答:
So are you literally wanting to change the last two bits of the string to "FF"? If so, easy

```<code>string = "11223300"
modified_string = string[:-2] + "FF"
</code>```

Edit from comments

```<code>hex_str = "0x11223300"
for i in range(256):
    hex_int = int(hex_str, 16)
    new_int = hex_int + 0x01
    print(hex(hex_int))
    hex_str = str(hex(new_int))
</code>```

Title: Python : Increase a string

Body:
I am not really familiar with Python yet.
I have a string like "11223300". Now I want to increase the last byte of that string ( from "00" to "FF"). I tried to convert the string into an integer ( integer=int(string,16)) and increase it, and convert it back later, but that does not work for me. Maybe one of you guys has a better idea.

string = "11223300"
counter = int(string, 16)

for i in range(255):
    counter = counter + 1
    IV = hex(counter)

Now I want to convert the IV from hex into a string

Thanks!

Body:
So are you literally wanting to change the last two bits of the string to "FF"? If so, easy

string = "11223300"
modified_string = string[:-2] + "FF"

Edit from comments

hex_str = "0x11223300"
for i in range(256):
    hex_int = int(hex_str, 16)
    new_int = hex_int + 0x01
    print(hex(hex_int))
    hex_str = str(hex(new_int))


问:
JS Calculating and constantly showing result
I have a starting value 1000.
On button FIGHT (which already has onclikc) it needs to do 1000-20 and shows in html 980, another click 960..

function damagec() {
    var a = 500;
    var b = a/20;
    document.getElementById('resultl').innerHTML = b;
    document.getElementById('resultl').style.color = 'green';
    document.getElementById('resultlc').innerHTML = b;
    document.getElementById('resultlc').style.color = 'green';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wall">
    <p id="wallvalue">1000</p>
</div>
<button onclick="damagec()"><b>FIGHT</b></button></code>```

答:
1000

<BUTTON onclick="damagec()">FIGHT</BUTTON>

```

Body:
I have a starting value 1000.
On button FIGHT (which already has onclikc) it needs to do 1000-20 and shows in html 980, another click 960..

function damagec() {
    var a = 500;
    var b = a/20;
    document.getElementById('resultl').innerHTML = b;
    document.getElementById('resultl').style.color = 'green';
    document.getElementById('resultlc').innerHTML = b;
    document.getElementById('resultlc').style.color = 'green';
}

1000

<button onclick="damagec()">FIGHT</button>

Body:
<div class="wall">
    <p id="wallvalue">1000</p>
</div>
<BUTTON onclick="damagec()"><b>FIGHT</b></BUTTON>

<script>

function damagec(){

 var wallVal = document.getElementById('wallvalue').innerHTML;
 wallVal = wallVal - 20;
 document.getElementById('wallvalue').innerHTML = wallVal;

}

</script>