问:
JS Functions Work Separately But Not Together
I'm using two functions to shift the background position and to zoom div's background. Here they are:

```<code>(function(shifting) {

    var parallax = document.querySelectorAll(".shiftparallax"),
        speed = -0.05;

    window.onscroll = function() {
        [].slice.call(parallax).forEach(function(el, i) {

            var windowXOffset = window.pageYOffset,
                elBackgrounPos = (windowXOffset * speed) + "px";
            console.log(elBackgrounPos);
            el.style.backgroundPositionY = elBackgrounPos;

        });
    };

})();

(function(zooming) {
    var parallaxfacts = document.querySelectorAll(".parallaxfacts"),
        constantsize = 100;
    speed = -0.03;
    window.onscroll = function() {

        if (window.innerWidth > 1024) {
            [].slice.call(parallaxfacts).forEach(function(el, i) {

                var windowXOffset = window.pageYOffset,
                    elBackgrounScale = (windowXOffset / 950 * constantsize) + "%";

                el.style.backgroundSize = elBackgrounScale;

            });
        }
    };

})();
</code>```

The problem is that I need them both to run at the same time but they only run separately. If they are both written like that - the second one runs only and the first one does nothing. If I remove the second one, the first one starts working. I've got a bit rusty in JS lately so I can't figure it out. is there any way to make them both work?

答:
You overwrite the window.onscroll event

try this two lines:

```<code>window.onscroll = el => console.log ('first');
window.onscroll = el => console.log ('second');
</code>```

use the following code...

```<code>window.addEventListener('scroll',  el => console.log ('firstlistener'));
window.addEventListener('scroll',  el => console.log ('secondlistener'));
</code>```

Body:
I'm using two functions to shift the background position and to zoom div's background. Here they are:

(function(shifting) {

    var parallax = document.querySelectorAll(".shiftparallax"),
        speed = -0.05;

    window.onscroll = function() {
        [].slice.call(parallax).forEach(function(el, i) {

            var windowXOffset = window.pageYOffset,
                elBackgrounPos = (windowXOffset * speed) + "px";
            console.log(elBackgrounPos);
            el.style.backgroundPositionY = elBackgrounPos;

        });
    };

})();

(function(zooming) {
    var parallaxfacts = document.querySelectorAll(".parallaxfacts"),
        constantsize = 100;
    speed = -0.03;
    window.onscroll = function() {

        if (window.innerWidth > 1024) {
            [].slice.call(parallaxfacts).forEach(function(el, i) {

                var windowXOffset = window.pageYOffset,
                    elBackgrounScale = (windowXOffset / 950 * constantsize) + "%";

                el.style.backgroundSize = elBackgrounScale;

            });
        }
    };

})();

The problem is that I need them both to run at the same time but they only run separately. If they are both written like that - the second one runs only and the first one does nothing. If I remove the second one, the first one starts working. I've got a bit rusty in JS lately so I can't figure it out. is there any way to make them both work?

Body:
You overwrite the window.onscroll event

try this two lines:

window.onscroll = el => console.log ('first');
window.onscroll = el => console.log ('second');

use the following code...

window.addEventListener('scroll',  el => console.log ('firstlistener'));
window.addEventListener('scroll',  el => console.log ('secondlistener'));


来源: stackexchange

问:
two different sounds need to play when hovering an image?
I am a beginner in JavaScript, CSS and HTML. I have two images at the top of a bag that I want to play two different sounds when hovered. However, when I hover on either of the images they play the same sound. I would like to know what I am doing wrong and how to get the images to play two different sounds. thank you!!!         </p>

```<code><script>
   function play(){
   var audio = document.getElementById("audio");
   audio.play();
             }
   </script>

<img src="Photos/crowabout.png" height="150" width="150" value="PLAY"
onmouseover="play()" onmouseout="stop()">
 <audio id="audio" src="Sounds/divers.mp3" ></audio>

    <script>
  function play(){
       var audio = document.getElementById("audio");
       audio.play();
                 }
   </script>

<img src="Photos/harptour.png" height="150" width="150" value="PLAY"  onmouseover="play()" onmouseout="stop()">
<audio id="audio" src="Sounds/cosmia.mp3" ></audio>
</code>```

答:
In general, id attributes should always be unique.

The id global attribute defines a unique identifier (ID) which must be unique in the whole document.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

In your code, Javascript has no way of knowing which audio element to play because both have the same id. Instead, make sure both have unique ids:

```<code><audio id="audio1" src="Sounds/divers.mp3" ></audio>
<audio id="audio2" src="Sounds/cosmia.mp3" ></audio>
</code>```

Javascript functions can include parameters. This is a way to pass along additional information to your function to use:

```<code>function play(id){
    var audio = document.getElementById(id);
    audio.play();
}
</code>```

Now your play function has the parameter id. So we can pass along the correct id to play when we call the function:

```<code>play('audio1');
play('audio2');
</code>```

Finally your script should look like:

```<code><script type="text/javascript">
function play(id){
    var audio = document.getElementById(id);
    audio.play();
}
</script>

<img src="Photos/crowabout.png" style="width: 150px; height: 150px;" value="PLAY" onmouseover="play('audio1');" onmouseout="stop();">
<audio id="audio1" src="Sounds/divers.mp3"></audio>

<img src="Photos/harptour.png" style="width: 150px; height: 150px;" value="PLAY"  onmouseover="play('audio2');" onmouseout="stop()">
<audio id="audio2" src="Sounds/cosmia.mp3"></audio>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a beginner in JavaScript, CSS and HTML. I have two images at the top of a bag that I want to play two different sounds when hovered. However, when I hover on either of the images they play the same sound. I would like to know what I am doing wrong and how to get the images to play two different sounds. thank you!!!

 <audio id="audio" src="Sounds/divers.mp3" ></audio>

<audio id="audio" src="Sounds/cosmia.mp3" ></audio>

Body:
In general, id attributes should always be unique.

The id global attribute defines a unique identifier (ID) which must be unique in the whole document.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

In your code, Javascript has no way of knowing which audio element to play because both have the same id. Instead, make sure both have unique ids:

<audio id="audio1" src="Sounds/divers.mp3" ></audio>
<audio id="audio2" src="Sounds/cosmia.mp3" ></audio>

Javascript functions can include parameters. This is a way to pass along additional information to your function to use:

function play(id){
    var audio = document.getElementById(id);
    audio.play();
}

Now your play function has the parameter id. So we can pass along the correct id to play when we call the function:

play('audio1');
play('audio2');

Finally your script should look like:

<script type="text/javascript">
function play(id){
    var audio = document.getElementById(id);
    audio.play();
}
</script>

<img src="Photos/crowabout.png" style="width: 150px; height: 150px;" value="PLAY" onmouseover="play('audio1');" onmouseout="stop();">
<audio id="audio1" src="Sounds/divers.mp3"></audio>

<img src="Photos/harptour.png" style="width: 150px; height: 150px;" value="PLAY"  onmouseover="play('audio2');" onmouseout="stop()">
<audio id="audio2" src="Sounds/cosmia.mp3"></audio>


问:
Merging objects within an array and keeping the highest value for identical properties
I have this array and I would like to merge the objects within it.

```<code>[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]
</code>```

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }```

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.

答:
Libraries increase vendor size, So don't prefer it for such small purpose.

let input = [null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}];
let output = {};

for(i in input) {
   let item = input[i];
   for(j in item)
     output[j] = item[j];
}

console.log(output);```

Body:
I have this array and I would like to merge the objects within it.

[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.


问:
Dectecting browser with Dojo?
Can you detect the browser the client is using with dojo? i want to put a function in place if it is IE8.

thanks

答:
look at

http://dojotoolkit.org/reference-guide/quickstart/browser-sniffing.html

```<code>if(dojo.isIE == 8){ // only IE8
  ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Dectecting browser with Dojo?

Body:
look at

http://dojotoolkit.org/reference-guide/quickstart/browser-sniffing.html

if(dojo.isIE == 8){ // only IE8
  ...
}


答:
You're assigning to window.onscroll twice. That means the second handler "unregisters" the first.

You can use addEventListener to listen to the event in both functions:

```<code>window.addEventListener("scroll", function() { /* function 1*/ });
window.addEventListener("scroll", function() { /* function 2*/ });
</code>```

Title: JS Functions Work Separately But Not Together

Body:
You're assigning to window.onscroll twice. That means the second handler "unregisters" the first.

You can use addEventListener to listen to the event in both functions:

window.addEventListener("scroll", function() { /* function 1*/ });
window.addEventListener("scroll", function() { /* function 2*/ });


问:
OperationalError: no such table (can't find solution)
Many questions here with same issue, and I followed the instructions to solve the issue in all those questions but failed.

My problem started when I changed a table name, I had one record in that table, I didn't delete that record and used makemigrations, and then migrate. I received an error of "no such table", then I followed some instructions, including:

flush (to drop the tables)

deleted migration folder, and recreated it with init file

clear migration history using fake  zero

None of the above worked for me, I can make the migration, but when I migrate, at first instance it says no changes detected, when I make migration again, then migrate, it says no such table exists (always mentions the table that I changed the name of)

I'm wondering if there are any other solutions I can try.

答:
I found the solution:

Delete the db.sqlite3 file at project folder. After doing this, I managed to migrate without any issues.


问:
Changing columns that are string in Spark GraphFrame
I'm using GraphFrame in spark 2.0 and scala.

I need to remove double quote from columns that are in string type (out of many columns).
I'm trying to do so using UDF as follow:

import org.apache.spark.sql.functions.udf

val removeDoubleQuotes = udf( (x:Any) =>
    x match{
      case s:String => s.replace("\"","")
      case other => other
    }
  )
```

And I get the following error since type Any is not supported in GraphFrame.

java.lang.UnsupportedOperationException: Schema for type Any is not
  supported

What is a workaround for that?

答:
I think you don't have a column with type Any and you can't return different datatype from udf. You need to have a single datatype return from udf.

If your column is String then you can create udf as

```<code>import org.apache.spark.sql.functions.udf

val removeDoubleQuotes = udf( (x:String) => s.replace("\"",""))
</code>```

Body:
I'm using GraphFrame in spark 2.0 and scala.

I need to remove double quote from columns that are in string type (out of many columns).
I'm trying to do so using UDF as follow:

import org.apache.spark.sql.functions.udf

val removeDoubleQuotes = udf( (x:Any) =>
    x match{
      case s:String => s.replace("\"","")
      case other => other
    }
  )

And I get the following error since type Any is not supported in GraphFrame.

java.lang.UnsupportedOperationException: Schema for type Any is not
  supported

What is a workaround for that?

Body:
I think you don't have a column with type Any and you can't return different datatype from udf. You need to have a single datatype return from udf.

If your column is String then you can create udf as

import org.apache.spark.sql.functions.udf

val removeDoubleQuotes = udf( (x:String) => s.replace("\"",""))


问:
Filtering with jQuery "find" and "filter" with multiple dropdowns
I have been trying to make some filter options for a page on a clients website with multiple dropdown menus. I can make it work, but it will always reset the filtering when I select an option. I need them to work "together". It's for filtering rooms in a hotel (not a lot of rooms there).

So the first dropdown is the number of persons that can fit in a room, then the type of room to rent, and finally the number of bedrooms in that room/house.

A user can user all 3 dropdowns to filter his results, or he can use only 1. Whatever he likes. He must be able to select "3" in the first dropdown, then it filters everything to show only rooms with up to "3" in the results box. After, if he selects "Studios" in the second dropdown, it needs to keep in mind he has selected "3" for the number of persons that fits in the room, but also the keep in mind that he just selected "Studios" now, so it should display Studios that can have up to 3 persons. etc.

I think you get the idea.
Here's my HTML code:

```<code><select class="bedroom-min">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="type">
  <option value="all">Select...</option>
  <option value="casitas">Casitas</option>
  <option value="studios">Studios</option>
  <option value="dorm">Dorm</option>
</select>

<select class="bedrooms">
  <option value="all">Select...</option>
  <option value="1">1 bedroom</option>
  <option value="2">2 bedrooms</option>
</select>

<div class="property-load-section">
  <div class="property-item" data-bedrooms="5" data-type="casitas" data-bed="1">Room #529</div>
  <div class="property-item" data-bedrooms="4" data-type="studios" data-bed="2">Room #737</div>
  <div class="property-item" data-bedrooms="3" data-type="dorm" data-bed="2">Room #123</div>
  <div class="property-item" data-bedrooms="2" data-type="studios" data-bed="2">Room #126</div>
  <div class="property-item" data-bedrooms="1" data-type="casitas" data-bed="1">Room #523</div>
</div>
</code>```

And here's the jQuery code :

```<code>//Filtering for number of person that can sleep in that room
$("select").change(function() {
  var minValue = $('select.bedroom-min').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') < minValue;
  }).fadeOut('fast');
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') >= minValue;
  }).fadeIn('fast');
});

//Filtering for type of rooms
$("select.type").change(function() {
    var roomType = $('select.type').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-type') != roomType;
  }).fadeOut('fast');
});

//Filtering for the number of bedrooms
$("select.bedrooms").change(function() {
    var roomBed = $('select.bedrooms').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bed') != roomBed;
  }).fadeOut('fast');
});
</code>```

Here's a CodePen link: https://codepen.io/anon/pen/bRxXVK?editors=1010

Can anyone help me out with this? I'm pretty new to javascript/jQuery. Thanks a lot

答:
Here is the fixed JavaScript code or JsFiddle :</p>

```<code>$(document).ready(function(){

    // Once document is ready

    // Reference to dropdowns
    var ddlRooms = $('select.bedroom-min');
    var ddlType = $('select.type');
    var ddlBedRooms = $('select.bedrooms');

    // Hook up event handler for change event
    ddlRooms.change( doFilter );
    ddlType.change( doFilter );
    ddlBedRooms.change( doFilter );

    // Start with initial filtering
    doFilter();

    function doFilter(){

        // Start with hiding all property item
        $('.property-load-section > .property-item').hide();

        // Get the selected values
        var selectedRooms = parseInt(ddlRooms.val());
        var selectedType = ddlType.val();
        var selectedBedRooms = ddlBedRooms.val();

        // Get items matching rooms
        var matched = $('.property-load-section').find('.property-item').filter(function () {

            // Current property item
            var curPropertyItem = $(this)

            var curPropertyRooms = parseInt(curPropertyItem.attr('data-bedrooms'))
            var curPropertyType = curPropertyItem.attr('data-type');
            var curPropertyBeds = curPropertyItem.attr('data-bed');

            //console.log('Rooms matched: ' + roomMatched());
            //console.log('Type matched: ' + roomTypMatched());
            //console.log('Beds matched: ' + bedsMatched())

            return ( roomMatched() && roomTypMatched() && bedsMatched() );

            function roomMatched(){
                return curPropertyRooms >= selectedRooms;
            }

            function roomTypMatched(){
                if ( selectedType === 'all' ){
                    return true;
                }
                else if( curPropertyType === selectedType ){
                    return true;
                }
                else{
                    return false;
                }
            }

            function bedsMatched(){

                if( selectedBedRooms === 'all' ){
                    return true;
                }
                else if ( curPropertyBeds === selectedBedRooms ){
                    return true;
                }
                else{
                    return false;
                }
            }
        });

        // Show matched property
        //console.log('Matched items: ' + matched.length);
        matched.show();
    }
})
</code>```

Body:
I have been trying to make some filter options for a page on a clients website with multiple dropdown menus. I can make it work, but it will always reset the filtering when I select an option. I need them to work "together". It's for filtering rooms in a hotel (not a lot of rooms there).

So the first dropdown is the number of persons that can fit in a room, then the type of room to rent, and finally the number of bedrooms in that room/house.

A user can user all 3 dropdowns to filter his results, or he can use only 1. Whatever he likes. He must be able to select "3" in the first dropdown, then it filters everything to show only rooms with up to "3" in the results box. After, if he selects "Studios" in the second dropdown, it needs to keep in mind he has selected "3" for the number of persons that fits in the room, but also the keep in mind that he just selected "Studios" now, so it should display Studios that can have up to 3 persons. etc.

I think you get the idea.
Here's my HTML code:

<select class="bedroom-min">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="type">
  <option value="all">Select...</option>
  <option value="casitas">Casitas</option>
  <option value="studios">Studios</option>
  <option value="dorm">Dorm</option>
</select>

<select class="bedrooms">
  <option value="all">Select...</option>
  <option value="1">1 bedroom</option>
  <option value="2">2 bedrooms</option>
</select>

Room #529

Room #737

Room #123

Room #126

Room #523

And here's the jQuery code :

//Filtering for number of person that can sleep in that room
$("select").change(function() {
  var minValue = $('select.bedroom-min').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') < minValue;
  }).fadeOut('fast');
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') >= minValue;
  }).fadeIn('fast');
});

//Filtering for type of rooms
$("select.type").change(function() {
    var roomType = $('select.type').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-type') != roomType;
  }).fadeOut('fast');
});

//Filtering for the number of bedrooms
$("select.bedrooms").change(function() {
    var roomBed = $('select.bedrooms').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bed') != roomBed;
  }).fadeOut('fast');
});

Here's a CodePen link: https://codepen.io/anon/pen/bRxXVK?editors=1010

Can anyone help me out with this? I'm pretty new to javascript/jQuery. Thanks a lot

Body:
Here is the fixed JavaScript code or JsFiddle :

$(document).ready(function(){

    // Once document is ready

    // Reference to dropdowns
    var ddlRooms = $('select.bedroom-min');
    var ddlType = $('select.type');
    var ddlBedRooms = $('select.bedrooms');

    // Hook up event handler for change event
    ddlRooms.change( doFilter );
    ddlType.change( doFilter );
    ddlBedRooms.change( doFilter );

    // Start with initial filtering
    doFilter();

    function doFilter(){

        // Start with hiding all property item
        $('.property-load-section > .property-item').hide();

        // Get the selected values
        var selectedRooms = parseInt(ddlRooms.val());
        var selectedType = ddlType.val();
        var selectedBedRooms = ddlBedRooms.val();

        // Get items matching rooms
        var matched = $('.property-load-section').find('.property-item').filter(function () {

            // Current property item
            var curPropertyItem = $(this)

            var curPropertyRooms = parseInt(curPropertyItem.attr('data-bedrooms'))
            var curPropertyType = curPropertyItem.attr('data-type');
            var curPropertyBeds = curPropertyItem.attr('data-bed');

            //console.log('Rooms matched: ' + roomMatched());
            //console.log('Type matched: ' + roomTypMatched());
            //console.log('Beds matched: ' + bedsMatched())

            return ( roomMatched() && roomTypMatched() && bedsMatched() );

            function roomMatched(){
                return curPropertyRooms >= selectedRooms;
            }

            function roomTypMatched(){
                if ( selectedType === 'all' ){
                    return true;
                }
                else if( curPropertyType === selectedType ){
                    return true;
                }
                else{
                    return false;
                }
            }

            function bedsMatched(){

                if( selectedBedRooms === 'all' ){
                    return true;
                }
                else if ( curPropertyBeds === selectedBedRooms ){
                    return true;
                }
                else{
                    return false;
                }
            }
        });

        // Show matched property
        //console.log('Matched items: ' + matched.length);
        matched.show();
    }
})


问:
Simplest way to detect a mobile device in PHP
What is the simplest way to tell if a user is using a mobile device to browse my site using PHP?

I have come across many classes that you can use but I was hoping for a simple if condition!

Is there a way I can do this?

答:
You could also use a third party api to do device detection via user agent string. One such service is www.useragentinfo.co. Just sign up and get your api token and below is how you get the device info via PHP:

```<code><?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
// get api token at https://www.useragentinfo.co/
$token = "<api-token>";
$url = "https://www.useragentinfo.co/api/v1/device/";

$data = array('useragent' => $useragent);

$headers = array();
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Token " . $token;

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status != 200 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

echo $json_response;
?>
</code>```

And here is the sample response if the visitor is using an iPhone:

```<code>{
  "device_type":"SmartPhone",
  "browser_version":"5.1",
  "os":"iOS",
  "os_version":"5.1",
  "device_brand":"Apple",
  "bot":false,
  "browser":"Mobile Safari",
  "device_model":"iPhone"
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You could also use a third party api to do device detection via user agent string. One such service is www.useragentinfo.co. Just sign up and get your api token and below is how you get the device info via PHP:

<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
// get api token at https://www.useragentinfo.co/
$token = "<api-token>";
$url = "https://www.useragentinfo.co/api/v1/device/";

$data = array('useragent' => $useragent);

$headers = array();
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Token " . $token;

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status != 200 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

echo $json_response;
?>

And here is the sample response if the visitor is using an iPhone:

{
  "device_type":"SmartPhone",
  "browser_version":"5.1",
  "os":"iOS",
  "os_version":"5.1",
  "device_brand":"Apple",
  "bot":false,
  "browser":"Mobile Safari",
  "device_model":"iPhone"
}


问:
jenkins hangs after Augmented all extensions
jenkins hangs at startup.

tail -10f /var/log/jenkins/jenkins.log

```<code>    Jul 07, 2017 5:12:16 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Started initialization
    Jul 07, 2017 5:12:16 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Listed all plugins
    Jul 07, 2017 5:12:18 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Prepared all plugins
    Jul 07, 2017 5:12:18 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Started all plugins
    Jul 07, 2017 5:12:18 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Augmented all extensions
</code>```

java -version

```<code>java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
</code>```

jenkins version ==> 2.60

Error in browser:

```<code>Please wait while Jenkins is getting ready to work...

Your browser will reload automatically when Jenkins is ready
</code>```

Tried:

```<code>1) restart jenkins and server
2) Changing the java version
3) Removed all jobs, etc
</code>```

Noting works. Thanks in advance.

答:
You have a similar issue filled here JENKINS-36931

To find out what Jenkins is doing during startup, especially when appearing to hang, follow these instructions:

"Obtaining a thread dump"

With that Thread dump, you can at least know where Jenkins is stopping and what it was doing.

Body:
jenkins hangs at startup.

tail -10f /var/log/jenkins/jenkins.log

    Jul 07, 2017 5:12:16 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Started initialization
    Jul 07, 2017 5:12:16 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Listed all plugins
    Jul 07, 2017 5:12:18 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Prepared all plugins
    Jul 07, 2017 5:12:18 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Started all plugins
    Jul 07, 2017 5:12:18 PM jenkins.InitReactorRunner$1 onAttained
    INFO: Augmented all extensions

java -version

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

jenkins version ==> 2.60

Error in browser:

Please wait while Jenkins is getting ready to work...

Your browser will reload automatically when Jenkins is ready

Tried:

1) restart jenkins and server
2) Changing the java version
3) Removed all jobs, etc

Noting works. Thanks in advance.


问:
polymer build: Warning [unknown-superclass] - Unable to resolve superclass superClass
Trying to build my polymer 2.0 project, but every time I try no matter the preset (es5-bundled, es6-bundled) or separate flags, I get the following warning for the one mixin I have:

```<code>EdmMac: public vedtam$ polymer build
info:    Clearing build/ directory...
info:    (default) Building...

    const DatastoreMixin = (superClass) => class extends superClass {
                                                         ~~~~~~~~~~
src/mixins/datastore-mixin.html(1,57) warning [unknown-superclass] - Unable to resolve superclass superClass
info:    (default) Build complete!
</code>```

build object:

```<code>  "builds": [{
    "name": "default",
    "bundle": true,
    "js": {"compile": true},
    "css": {"minify": true},
    "html": {"minify": true},
    "addServiceWorker": true
  }]
</code>```

Caller: app-main.html:

```<code>class MyApp extends Polymer.GestureEventListeners(DatastoreMixin(ReduxMixin(Polymer.Element))) {
</code>```

DatastoreMixin:

```<code><script>
    DatastoreMixin = function(superClass) {
      return class extends superClass {
        constructor() {
          super();
        }

        static get properties() {
          return {
            bar: {
              type: Object
            }
          };
        }

      }
    }
</script>
</code>```

Versions & Environment

Polymer CLI: 1.1.0

node: v6.10.3

Operating System: OSX 10.10.5

What could be wrong?

答:
In case if anyone is hitting the same issue, I got an answer from the Polymer devs, as a fix you need to use the /* @polymerMixin */ annotation:

```<code><script>
    /* @polymerMixin */
    DatastoreMixin = function(superClass) {
      return class extends superClass {
        constructor() {
          super();
        }

        static get properties() {
          return {
            bar: {
              type: Object
            }
          };
        }

      }
    }
</script>
</code>```

Body:
Trying to build my polymer 2.0 project, but every time I try no matter the preset (es5-bundled, es6-bundled) or separate flags, I get the following warning for the one mixin I have:

EdmMac: public vedtam$ polymer build
info:    Clearing build/ directory...
info:    (default) Building...

    const DatastoreMixin = (superClass) => class extends superClass {
                                                         ~~~~~~~~~~
src/mixins/datastore-mixin.html(1,57) warning [unknown-superclass] - Unable to resolve superclass superClass
info:    (default) Build complete!

build object:

  "builds": [{
    "name": "default",
    "bundle": true,
    "js": {"compile": true},
    "css": {"minify": true},
    "html": {"minify": true},
    "addServiceWorker": true
  }]

Caller: app-main.html:

class MyApp extends Polymer.GestureEventListeners(DatastoreMixin(ReduxMixin(Polymer.Element))) {

DatastoreMixin:

Versions & Environment

Polymer CLI: 1.1.0

node: v6.10.3

Operating System: OSX 10.10.5

What could be wrong?

Body:
In case if anyone is hitting the same issue, I got an answer from the Polymer devs, as a fix you need to use the /* @polymerMixin */ annotation:

<script>
    /* @polymerMixin */
    DatastoreMixin = function(superClass) {
      return class extends superClass {
        constructor() {
          super();
        }

        static get properties() {
          return {
            bar: {
              type: Object
            }
          };
        }

      }
    }
</script>


问:
How to check for palindrome using Python logic
I'm trying to check for a palindrome with Python. The code I have is very for-loop intensive.

And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language.

I see on this website. Search for "C-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.

I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?

I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.

```<code>def isPalindrome(n):
    lst = [int(n) for n in str(n)]
    l=len(lst)
    if l==0 || l==1:
        return True
    elif len(lst)%2==0:
        for k in range (l)
        #####
    else:
        while (k<=((l-1)/2)):
            if (list[]):
                #####

for i in range (999, 100, -1):
    for j in range (999,100, -1):
        if isPalindrome(i*j):
            print(i*j)
            break
</code>```

I'm missing a lot of code here. The five hashes are just reminders for myself.

Concrete questions:

In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?

My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?

Does anybody have any good advice, or good websites, or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing.

Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops...

PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.

答:
There is another way by using functions, if you don't want to use reverse</p>

```<code>#!/usr/bin/python

A = 'kayak'

def palin(A):

    i = 0
    while (i<=(A.__len__()-1)):
        if (A[A.__len__()-i-1] == A[i]):
            i +=1
        else:
         return False

if palin(A) == False:

    print("Not a Palindrome")

else :

    print ("Palindrome")
</code>```

Body:
I'm trying to check for a palindrome with Python. The code I have is very for-loop intensive.

And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language.

I see on this website. Search for "C-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.

I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?

I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.

def isPalindrome(n):
    lst = [int(n) for n in str(n)]
    l=len(lst)
    if l==0 || l==1:
        return True
    elif len(lst)%2==0:
        for k in range (l)
        #####
    else:
        while (k<=((l-1)/2)):
            if (list[]):
                #####

for i in range (999, 100, -1):
    for j in range (999,100, -1):
        if isPalindrome(i*j):
            print(i*j)
            break

I'm missing a lot of code here. The five hashes are just reminders for myself.

Concrete questions:

In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?

My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?

Does anybody have any good advice, or good websites, or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing.

Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops...

PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.

Body:
There is another way by using functions, if you don't want to use reverse

#!/usr/bin/python

A = 'kayak'

def palin(A):

    i = 0
    while (i<=(A.__len__()-1)):
        if (A[A.__len__()-i-1] == A[i]):
            i +=1
        else:
         return False

if palin(A) == False:

    print("Not a Palindrome")

else :

    print ("Palindrome")


问:
How to pass a variable from a function to another function?
Sorry if my English is bad but it is not my native language

I'm starting my programming studies in Python, And I need to make this code for my class.

Basically consists of a checklist of the workers of a company to calculate their salary, applying some discounts and bonuses. In Option 4 of the menu, I must show all registered ID's with their final salary

I need to put the variable Sueldo Descontado Which is in the function Def Calcular_Sueldo() within the function Def Liquidaciones_Rut

Someone told me to define it as a class and add it to the registry List [] but I don't know how to do this :/

PS: If I define the variable SueldoDescontado as global Prints the same value for all ID's :/

I hope someone can help me

Heres my code

```<code>Lista = [] #<----- Array

Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio',
       'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
       'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio',
       'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre',
       'ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO',
       'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']

Rank =  ['novato', 'experto', 'supervisor', 'administrativo',
        'Novato', 'Experto', 'Supervisor', 'Administrativo',
        'NOVATO', 'EXPERTO', 'SUPERVISOR', 'ADMINISTRATIVO']

SistemaSalud = ['a', 'b', 'c',
               'A', 'B', 'C']

class Trabajador: #Class <----
Mes = ''
Año = 0
Rut = ''
Nombre = ''
Categoria = ''
DiasOff = 0
AFP = ''
SSalud = ''
SueldoBruto = 0
SueldoDescontado = 0

def Ingresar_Datos():
    Elementos = int(input('Ingrese cantidad de trabajadores que desea agregar: \n')) #<--- How many people do you want to add
        for Trabajadores in range(Elementos):
        dato = Trabajador()

        while True:
            Nombre = input("Ingrese un nombre: ") #<--- Name
            if vacio(Nombre):
                print ('No puede dejar el campo vacio')
            else:
                dato.Nombre = Nombre
                break

       while True:
            Rut = input('Ingrese Rut: ') # <---- ID Number
            if vacio(Rut):
                print ('No puede dejar el campo vacio')
            else:
                dato.Rut = Rut
                break

       while True:
            Mes = input('Ingrese mes: ') # <---- Month when start at work
            if vacio(Mes):
                print ('No puede dejar el campo vacio')
            elif Mes in Mess:
                dato.Mes = Mes
                break
            else:
                print('Mes invalido')

        while True:
            Año = input('Ingrese año: ') # <---- Year when start at work
            if vacio(Año):
                print ('No puede dejar el campo vacio')
            else:
                dato.Año = Año
                break

        while True:
            AFP = input('Ingrese AFP: ') # <---- NVM just a company name can be put here, not relevant
            if vacio(AFP):
                print ('No puede dejar el campo vacio')
            else:
                dato.AFP = AFP
                break

        while True:
            SSalud = input('Sistema de salud A B o C\nDigite opcion: ') # <---- System Health, Here is A, B or C, This make a discount%
            if vacio(SSalud):
                print ('No puede dejar el campo vacio')
           elif SSalud in SistemaSalud:
                dato.SSalud = SSalud
                break
            else:
                print ('::::::::::::::::::::ERROR Opcion Invalida::::::::::::::::::::')

        while True:
            Categoria = input('Categoria; Novato, Supervisor, Experto o Administrativo: ') # <---- Worker rank, Expert have a 2xBonus for 0 days off
            if vacio(Categoria):
                print ('No puede dejar el campo vacio')
            elif Categoria in Rank:
                dato.Categoria = Categoria
                break
            else:
                print ('::::::::::::::::::::ERROR Categoria invalida::::::::::::::::::::')

        while True:
                DiasOff = input('Ingrese cantidad de dias de ausencia: ') #<------ Days of absence, 0 days have a bonus$
                if dato.DiasOff < 0 or dato.DiasOff > 30:
                    print ('Dias de ausencia no puede ser negativo o mayor a 30')
                else:
                    dato.DiasOff = DiasOff
                    break

       while True:
            try:
                SueldoBruto = int(input('Ingrese sueldo bruto: ')) # <------- Gross Salary
                if dato.SueldoBruto < 0:
                    print ('El monto del sueldo bruto no puede ser negativo')
                else:
                    dato.SueldoBruto = SueldoBruto
                    break
            except ValueError:
                print('error')

        print("------------------------------------------------")
        Lista.append(dato)

def vacio(x):
    if x and x.strip():
        return False
    return True

def Calcular_Sueldo():
    Bono = 50000 #<-------- Bonus for 0 Days of absence
    for Trabajadores in Lista:
        print('Nombre trabajador: ',Trabajadores.Nombre,'\n')

        if Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('Experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('EXPERTO'):
            SueldoBono = Trabajadores.SueldoBruto + Bono*2 #<-------- There is if 0 days absence and rank experto, 2xBonus
            print('Sueldo bruto + Bono (Experto) por 0 faltas: ',SueldoBono)

        elif Trabajadores.DiasOff == '0': #<-------- Bonus for 0 Days of absence, nvm about rank here
            SueldoBono = Trabajadores.SueldoBruto + Bono
            print('Sueldo bruto + Bono por 0 faltas: ',SueldoBono)

        else:
            SueldoBono = Trabajadores.SueldoBruto #<-------- No bonus for days absence
            print('Tiene faltas/ausencia, no tiene derecho a Bono: ',SueldoBono)

        DctoAFP = SueldoBono - (SueldoBono * 0.1) #<-------- This makes a 10% descuento for AFP, the nvm'company name
        print('Sueldo bruto + Recorte del 10% por AFP ',Trabajadores.AFP,': ',DctoAFP)

        if Trabajadores.SSalud == 'a' or Trabajadores.SSalud == 'A': #<-------- If Sistem Health is A, make a 5,7% discount
            DctoSalud = (DctoAFP/100) * 5.7
            print('Recorte del sistema de salud A: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)

        if Trabajadores.SSalud == 'b' or Trabajadores.SSalud == 'B': #<-------- If Sistem Health is B, make a 6.1% discount
            DctoSalud = (DctoAFP/100) * 6.1
            print('Recorte del sistema de salud B: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)

        if Trabajadores.SSalud == 'c' or Trabajadores.SSalud == 'C': #<-------- If Sistem Health is C, make a 6.5% discount
            DctoSalud = (DctoAFP/100) * 6.5
            print('Recorte del sistema de salud C: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)

        print('--------------------------------------')

def Liquidaciones_Rut(): #<------- Here I need to print all the ID's number's with his Final Salary (SueldoDescontado)
    for Trabajadores in Lista:
        print('Rut: ',Trabajadores.Rut,'Total a pagar: $',SueldoDescontado) #<----- To here --------- !"#$"!#%!"#%!#"%"#$%$"#----------

def Listar_Empleados(): #<------------------ Here just print the names of all workers
    for Trabajadores in Lista:
        print("Empleados registrados: ", Trabajadores.Nombre)

opcion = 7
while (opcion != 6):
    print(' ========== Administracion NovaVision ========== ')
    print('Menu')
    print('1.- Ingresar Datos') #<-------------------------- Enter Data
    print('2.- Calcular Sueldo') #<-------------------------- Calculate Salary
    print('3.- Listar Empleados') #<----------------------------- List employees (by his name)
    print('4.- Mostrar Liquidaciones por RUT') # <--------- List numbers ID with his Respective Salary
    print('5.- Salir')
    opcion = int(input('Ingrese su opcion: '))
    if (opcion == 1):
       Ingresar_Datos()
    elif (opcion == 2):
       Calcular_Sueldo()
    elif (opcion == 3):
       Listar_Empleados()
    elif (opcion == 4):
       Liquidaciones_Rut()
    elif (opcion == 5):
       print('Saliendo .. ')
    else:
       print ('Opcion no valida')
</code>```

答:
Small example

```<code>class Trabajador:

    def __init__(self, number, month, year):
        self.number = number
        self.month = month
        self.year = year

Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']

T1 = Trabajador(10, Mess[0] , 1979)

print (T1.number)
print (T1.month)
print (T1.year)
</code>```

__init method is class constructor,but read the link I gave you

Run this from command line in Linux

```<code>python example1.py
</code>```

You will get

```<code>10
enero
1979
</code>```

Body:
Sorry if my English is bad but it is not my native language

I'm starting my programming studies in Python, And I need to make this code for my class.

Basically consists of a checklist of the workers of a company to calculate their salary, applying some discounts and bonuses. In Option 4 of the menu, I must show all registered ID's with their final salary

I need to put the variable Sueldo Descontado Which is in the function Def Calcular_Sueldo() within the function Def Liquidaciones_Rut

Someone told me to define it as a class and add it to the registry List [] but I don't know how to do this :/

PS: If I define the variable SueldoDescontado as global Prints the same value for all ID's :/

I hope someone can help me

Heres my code

Lista = [] #<----- Array

Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio',
       'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
       'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio',
       'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre',
       'ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO',
       'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']

Rank =  ['novato', 'experto', 'supervisor', 'administrativo',
        'Novato', 'Experto', 'Supervisor', 'Administrativo',
        'NOVATO', 'EXPERTO', 'SUPERVISOR', 'ADMINISTRATIVO']

SistemaSalud = ['a', 'b', 'c',
               'A', 'B', 'C']

class Trabajador: #Class <----
Mes = ''
Año = 0
Rut = ''
Nombre = ''
Categoria = ''
DiasOff = 0
AFP = ''
SSalud = ''
SueldoBruto = 0
SueldoDescontado = 0

def Ingresar_Datos():
    Elementos = int(input('Ingrese cantidad de trabajadores que desea agregar: \n')) #<--- How many people do you want to add
        for Trabajadores in range(Elementos):
        dato = Trabajador()

        while True:
            Nombre = input("Ingrese un nombre: ") #<--- Name
            if vacio(Nombre):
                print ('No puede dejar el campo vacio')
            else:
                dato.Nombre = Nombre
                break

       while True:
            Rut = input('Ingrese Rut: ') # <---- ID Number
            if vacio(Rut):
                print ('No puede dejar el campo vacio')
            else:
                dato.Rut = Rut
                break

       while True:
            Mes = input('Ingrese mes: ') # <---- Month when start at work
            if vacio(Mes):
                print ('No puede dejar el campo vacio')
            elif Mes in Mess:
                dato.Mes = Mes
                break
            else:
                print('Mes invalido')

        while True:
            Año = input('Ingrese año: ') # <---- Year when start at work
            if vacio(Año):
                print ('No puede dejar el campo vacio')
            else:
                dato.Año = Año
                break

        while True:
            AFP = input('Ingrese AFP: ') # <---- NVM just a company name can be put here, not relevant
            if vacio(AFP):
                print ('No puede dejar el campo vacio')
            else:
                dato.AFP = AFP
                break

        while True:
            SSalud = input('Sistema de salud A B o C\nDigite opcion: ') # <---- System Health, Here is A, B or C, This make a discount%
            if vacio(SSalud):
                print ('No puede dejar el campo vacio')
           elif SSalud in SistemaSalud:
                dato.SSalud = SSalud
                break
            else:
                print ('::::::::::::::::::::ERROR Opcion Invalida::::::::::::::::::::')

        while True:
            Categoria = input('Categoria; Novato, Supervisor, Experto o Administrativo: ') # <---- Worker rank, Expert have a 2xBonus for 0 days off
            if vacio(Categoria):
                print ('No puede dejar el campo vacio')
            elif Categoria in Rank:
                dato.Categoria = Categoria
                break
            else:
                print ('::::::::::::::::::::ERROR Categoria invalida::::::::::::::::::::')

        while True:
                DiasOff = input('Ingrese cantidad de dias de ausencia: ') #<------ Days of absence, 0 days have a bonus$
                if dato.DiasOff < 0 or dato.DiasOff > 30:
                    print ('Dias de ausencia no puede ser negativo o mayor a 30')
                else:
                    dato.DiasOff = DiasOff
                    break

       while True:
            try:
                SueldoBruto = int(input('Ingrese sueldo bruto: ')) # <------- Gross Salary
                if dato.SueldoBruto < 0:
                    print ('El monto del sueldo bruto no puede ser negativo')
                else:
                    dato.SueldoBruto = SueldoBruto
                    break
            except ValueError:
                print('error')

        print("------------------------------------------------")
        Lista.append(dato)

def vacio(x):
    if x and x.strip():
        return False
    return True

def Calcular_Sueldo():
    Bono = 50000 #<-------- Bonus for 0 Days of absence
    for Trabajadores in Lista:
        print('Nombre trabajador: ',Trabajadores.Nombre,'\n')

        if Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('Experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('EXPERTO'):
            SueldoBono = Trabajadores.SueldoBruto + Bono*2 #<-------- There is if 0 days absence and rank experto, 2xBonus
            print('Sueldo bruto + Bono (Experto) por 0 faltas: ',SueldoBono)

        elif Trabajadores.DiasOff == '0': #<-------- Bonus for 0 Days of absence, nvm about rank here
            SueldoBono = Trabajadores.SueldoBruto + Bono
            print('Sueldo bruto + Bono por 0 faltas: ',SueldoBono)

        else:
            SueldoBono = Trabajadores.SueldoBruto #<-------- No bonus for days absence
            print('Tiene faltas/ausencia, no tiene derecho a Bono: ',SueldoBono)

        DctoAFP = SueldoBono - (SueldoBono * 0.1) #<-------- This makes a 10% descuento for AFP, the nvm'company name
        print('Sueldo bruto + Recorte del 10% por AFP ',Trabajadores.AFP,': ',DctoAFP)

        if Trabajadores.SSalud == 'a' or Trabajadores.SSalud == 'A': #<-------- If Sistem Health is A, make a 5,7% discount
            DctoSalud = (DctoAFP/100) * 5.7
            print('Recorte del sistema de salud A: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)

        if Trabajadores.SSalud == 'b' or Trabajadores.SSalud == 'B': #<-------- If Sistem Health is B, make a 6.1% discount
            DctoSalud = (DctoAFP/100) * 6.1
            print('Recorte del sistema de salud B: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)

        if Trabajadores.SSalud == 'c' or Trabajadores.SSalud == 'C': #<-------- If Sistem Health is C, make a 6.5% discount
            DctoSalud = (DctoAFP/100) * 6.5
            print('Recorte del sistema de salud C: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)

        print('--------------------------------------')

def Liquidaciones_Rut(): #<------- Here I need to print all the ID's number's with his Final Salary (SueldoDescontado)
    for Trabajadores in Lista:
        print('Rut: ',Trabajadores.Rut,'Total a pagar: $',SueldoDescontado) #<----- To here --------- !"#$"!#%!"#%!#"%"#$%$"#----------

def Listar_Empleados(): #<------------------ Here just print the names of all workers
    for Trabajadores in Lista:
        print("Empleados registrados: ", Trabajadores.Nombre)

opcion = 7
while (opcion != 6):
    print(' ========== Administracion NovaVision ========== ')
    print('Menu')
    print('1.- Ingresar Datos') #<-------------------------- Enter Data
    print('2.- Calcular Sueldo') #<-------------------------- Calculate Salary
    print('3.- Listar Empleados') #<----------------------------- List employees (by his name)
    print('4.- Mostrar Liquidaciones por RUT') # <--------- List numbers ID with his Respective Salary
    print('5.- Salir')
    opcion = int(input('Ingrese su opcion: '))
    if (opcion == 1):
       Ingresar_Datos()
    elif (opcion == 2):
       Calcular_Sueldo()
    elif (opcion == 3):
       Listar_Empleados()
    elif (opcion == 4):
       Liquidaciones_Rut()
    elif (opcion == 5):
       print('Saliendo .. ')
    else:
       print ('Opcion no valida')

Body:
Small example

class Trabajador:

    def __init__(self, number, month, year):
        self.number = number
        self.month = month
        self.year = year

Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']

T1 = Trabajador(10, Mess[0] , 1979)

print (T1.number)
print (T1.month)
print (T1.year)

__init method is class constructor,but read the link I gave you

Run this from command line in Linux

python example1.py

You will get

10
enero
1979


问:
setTimeout waits too long in Node.js
I think I have a misunderstanding of what setTimeout does exactly in JavaScript. I have this script:

```<code>function recursiveFibonacci(n) {
    if ( n === 0 ) {
        return 1;
    } else if ( n === 1 ) {
        return 1;
    } else {
        return recursiveFibonacci(n-1) + recursiveFibonacci(n-2);
    }
}

setTimeout( () => {console.log("one second");}, 1000);

console.log(recursiveFibonacci(42));
</code>```

What I would expect to happen is that recursiveFibonacci starts chugging away on the 43rd value in the Fibonacci sequence. This takes about 4 seconds on my computer. So, after 1 second of work the evaluation would be interrupted and the console would log:

```<code>one second
</code>```

and then about 3 seconds later log:

```<code>433494437
</code>```

Instead what happens is that, after 4 seconds, the console logs:

```<code>433494437
one second
</code>```

all at once. Why is this the case? How can I get setTimeout to work? Is it the case that the JavaScript interpreter is not actually interrupted by  setTimeout but rather if it finishes its other jobs then it will wait until the given amount of time has passed before calling the given function?

Edit:

I found this tool very useful for understanding the relevant concepts:

Loupe

答:
It's because your function does synchronous job.

The nature of the node event loop is asynchronous. As far as you function finishes execution or you will execute something asynchronous - nextTick will be called. And most probably the first item will be you setTimout function.

Here's example with intended asynchronous chunk, and it works as you expect:

```<code>function sleep(ms) {
  return new Promise( (resolve, reject) => {
    setTimeout(resolve, ms);
  });
}

async function recursiveFibonacci(n) {
  await sleep(10);
  if ( n === 0 ) {
      return 1;
  } else if ( n === 1 ) {
      return 1;
  } else {
      return await recursiveFibonacci(n-1) + await recursiveFibonacci(n-2);
  }
}

setTimeout( () => {console.log("one second");}, 1000);

recursiveFibonacci(25).then(console.log);
</code>```

Title: setTimeout waits too long in Node.js

Body:
I think I have a misunderstanding of what setTimeout does exactly in JavaScript. I have this script:

function recursiveFibonacci(n) {
    if ( n === 0 ) {
        return 1;
    } else if ( n === 1 ) {
        return 1;
    } else {
        return recursiveFibonacci(n-1) + recursiveFibonacci(n-2);
    }
}

setTimeout( () => {console.log("one second");}, 1000);

console.log(recursiveFibonacci(42));

What I would expect to happen is that recursiveFibonacci starts chugging away on the 43rd value in the Fibonacci sequence. This takes about 4 seconds on my computer. So, after 1 second of work the evaluation would be interrupted and the console would log:

one second

and then about 3 seconds later log:

433494437

Instead what happens is that, after 4 seconds, the console logs:

433494437
one second

all at once. Why is this the case? How can I get setTimeout to work? Is it the case that the JavaScript interpreter is not actually interrupted by  setTimeout but rather if it finishes its other jobs then it will wait until the given amount of time has passed before calling the given function?

Edit:

I found this tool very useful for understanding the relevant concepts:

Loupe

Body:
It's because your function does synchronous job.

The nature of the node event loop is asynchronous. As far as you function finishes execution or you will execute something asynchronous - nextTick will be called. And most probably the first item will be you setTimout function.

Here's example with intended asynchronous chunk, and it works as you expect:

function sleep(ms) {
  return new Promise( (resolve, reject) => {
    setTimeout(resolve, ms);
  });
}

async function recursiveFibonacci(n) {
  await sleep(10);
  if ( n === 0 ) {
      return 1;
  } else if ( n === 1 ) {
      return 1;
  } else {
      return await recursiveFibonacci(n-1) + await recursiveFibonacci(n-2);
  }
}

setTimeout( () => {console.log("one second");}, 1000);

recursiveFibonacci(25).then(console.log);


问:
How to make so that the toolbar does not overlap?
I am trying to add a list in the main main, but the toolbar is overridden making in the execution the first element is not seen.

Any solution

The main layout

```<code>    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/holo_red_dark"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="@android:color/holo_red_dark"
    app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>
</code>```

The theme used in the application

```<code>  <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

The manifest of the application

```<code> <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</code>```

答:
```<code>  Use Relative layout

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <android.support.design.widget.AppBarLayout
       android:id="@+id/appBar"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/holo_red_dark"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

 <LinearLayout
        android:layout_below="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <include layout="@layout/list_elec" />
 </LinearLayout>

</RelativeLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="@android:color/holo_red_dark"
    app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Body:
I am trying to add a list in the main main, but the toolbar is overridden making in the execution the first element is not seen.

Any solution

The main layout

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/holo_red_dark"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="@android:color/holo_red_dark"
    app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>

The theme used in the application


问:
How could I use PyQuery traversal correctly?
There is a file called "name.txt"

Content is below

```<code><td>
    <input class="name" value="Michael">
    <input class="age" value="22">
    <input class="location" value="hebei">

</td>

<td>
    <input class="name" value="Jack">
    <input class="age" value="23">
    <input class="location" value="NewYo">
</td>
</code>```

Now I want to use pyquery to get all input tags, then traversal input tags

Use '.filter' to get all name class and age class

At last, get the value of name and age and write all results into a file called'name_file.txt'

My code is below

```<code># -*- coding: utf-8 -*-
from pyquery import PyQuery as pq
doc = pq(filename='name.txt')

input = doc('input')

for result in input.items():
    name_result = result.filter('.name')
    age_result = result.filter('.age')
    name = name_result.attr('value')
    age = age_result.attr('value')
    print "%s:%s" %(name,age)
    c = "%s:%s" %(name,age)
    f = file('name_file.txt','w')
    f.write(c)
    f.close()
</code>```

But now, I met 2 issues

1. The results I got are not "Michael:22", they are "Michael:None" and "None:22"

2. The content of 'name_file' I wrote into is just 'None:None', not all results I got.

答:
```<code>from pyquery import PyQuery as pq
doc = pq(filename = 'text.txt')

input=doc.children('body')

f = file('name_file.txt', 'w')

for x in [result.html() for result in input.items('td')]:
    x=pq(x)
    name = x('input').eq(0).attr('value')
    age = x('input').eq(1).attr('value')
    print "%s:%s" % (name, age)
    c = "%s:%s" % (name, age)
    f.write(c)

f.close()
</code>```

You cannot have the file opening statement inside the loop else you'd just have the file being overwritten with just one record on every loop iteration.

Similarly, you close it after the loop and not after inserting every record.

Body:
There is a file called "name.txt"

Content is below

    <input class="name" value="Michael">
    <input class="age" value="22">
    <input class="location" value="hebei">

    <input class="name" value="Jack">
    <input class="age" value="23">
    <input class="location" value="NewYo">

Now I want to use pyquery to get all input tags, then traversal input tags

Use '.filter' to get all name class and age class

At last, get the value of name and age and write all results into a file called'name_file.txt'

My code is below

# -*- coding: utf-8 -*-
from pyquery import PyQuery as pq
doc = pq(filename='name.txt')

input = doc('input')

for result in input.items():
    name_result = result.filter('.name')
    age_result = result.filter('.age')
    name = name_result.attr('value')
    age = age_result.attr('value')
    print "%s:%s" %(name,age)
    c = "%s:%s" %(name,age)
    f = file('name_file.txt','w')
    f.write(c)
    f.close()

But now, I met 2 issues

1. The results I got are not "Michael:22", they are "Michael:None" and "None:22"

2. The content of 'name_file' I wrote into is just 'None:None', not all results I got.

Body:
from pyquery import PyQuery as pq
doc = pq(filename = 'text.txt')

input=doc.children('body')

f = file('name_file.txt', 'w')

for x in [result.html() for result in input.items('td')]:
    x=pq(x)
    name = x('input').eq(0).attr('value')
    age = x('input').eq(1).attr('value')
    print "%s:%s" % (name, age)
    c = "%s:%s" % (name, age)
    f.write(c)

f.close()

You cannot have the file opening statement inside the loop else you'd just have the file being overwritten with just one record on every loop iteration.

Similarly, you close it after the loop and not after inserting every record.


问:
Is there a library that provides API compatible to java/android networking in codenameone?
I am building apps to connect to realtime and streaming services like PubNub, Ably, deep stream.io and XMPP. I am having to port java/android SDKs and the big issue is always around threads and networking. IS there plan to support the JAVA/Android API for network and threads or is there a library providing that? I do not have the skills or time to do that.</p>

答:
PubNub has a port to Codename One that's a bit outdated by now. There is support for the URL API but nothing lower level than that as it won't be doable (correctly) on iOS.

I would suggest working with websockets which are very portable and easy to work with: https://www.codenameone.com/blog/introducing-codename-one-websocket-support.html


问:
DELPHI/INDY/IdHTTP Log into invision power board forum?
Need help keeping a session after logging into forum.
I'm using TIdHttp and have a cookie manager assigned already</p>

```<code>  Http.Get(Url); //..Used to get session Id that is then stored in FSessionID

  Param := TStringList.Create;
  Param.Add('act=Login');
  Param.Add('CODE=01');
  Param.Add('s='+FSessionID);
  Param.Add('referer=''''');
  Param.Add('CookieDate=1');
  Param.Add('UserName=MYUsername');
  Param.Add('PassWord=MyPassword');
  Http.Post(Url,Param); //..The was Login succesfull. Made sure by checking responce
  Http.Get(Url); //..Now its not logged in. Why????
</code>```

答: Make sure the SessionID cookie is not being rejected by TIdCookieManager when it arrives.  Indy's cookie support is currently broken, causing valid cookies to sometimes be ignored instead of stored.</p>

Body:
Need help keeping a session after logging into forum.
I'm using TIdHttp and have a cookie manager assigned already

  Http.Get(Url); //..Used to get session Id that is then stored in FSessionID

  Param := TStringList.Create;
  Param.Add('act=Login');
  Param.Add('CODE=01');
  Param.Add('s='+FSessionID);
  Param.Add('referer=''''');
  Param.Add('CookieDate=1');
  Param.Add('UserName=MYUsername');
  Param.Add('PassWord=MyPassword');
  Http.Post(Url,Param); //..The was Login succesfull. Made sure by checking responce
  Http.Get(Url); //..Now its not logged in. Why????


问:
Why automatic currying in ML family languages
ML family languages have automatic currying - where a function call with two arguments is considered to apply them one at a time, f x y = (f x) y - whereas other language families don't.

Is this just a historical accident, or is there a technical reason for this?

Note that I am not asking whether automatic currying is net good or bad (that's a subjective judgment). I'm asking whether it synergizes with other features of ML family languages so as to make it more natural to include in those languages, and if so, what are those features and what is the nature of the synergy? Or conversely, are there features of other language families that would clash with any attempt to provide automatic currying?

Edit: in addition to the given answers, it occurs to me that there is probably another factor: if you are writing the compiler in a language with pattern matching, it's okay for the AST to be more complex, which means it's okay for the conventional 'call with a tuple' construct to be a compound term. So given that the compiler is often written in its own language, automatic currying and pattern matching go well together.

答:
Since Standard ML supports tuples (and other records) and pattern-matching, it also supports a non-currying model:

```<code>fun add (x, y) = x + y
</code>```

So curried functions are just one option, and the special support for defining them is just syntactic sugar (albeit very important syntactic sugar for writing idiomatic ML code). There's no reason that a language like JavaScript couldn't offer the same syntactic sugar:

```<code>// Analogous to fun (f o g) x = f (g x) -- not actually valid JS:
function compose(f)(g)(arg) {
    return f(g(arg));
}
</code>```

but since it's not so common for JavaScript functions to immediately return a function, this syntactic sugar wouldn't be so useful there. (Of course, this is somewhat circular: what's common in a language is shaped by what the language makes easy, and a language makes things easy because they're common in that language. But that's true of all language features, and not specific to this one.)

Interestingly, even in Standard ML, the special curried-function syntax only works for function declarations (fun ...), not for function expressions (fn ...). So I can write

```<code>val op o = fn f => fn g => fn x => f (g x)
</code>```

but not

```<code>val op o = fn f g x => f (g x)         (* illegal *)
</code>```

In Haskell, by contrast, even function expressions support automatic currying; for example, (\ x y z -> x + y + z) 3 4 5 evaluates to 12. (Haskell also treats currying as more central in one other respect, namely that infix operators are curried functions, unlike in Standard ML where infix operators are functions that take a pair.)

Body:
Since Standard ML supports tuples (and other records) and pattern-matching, it also supports a non-currying model:

fun add (x, y) = x + y

So curried functions are just one option, and the special support for defining them is just syntactic sugar (albeit very important syntactic sugar for writing idiomatic ML code). There's no reason that a language like JavaScript couldn't offer the same syntactic sugar:

// Analogous to fun (f o g) x = f (g x) -- not actually valid JS:
function compose(f)(g)(arg) {
    return f(g(arg));
}

but since it's not so common for JavaScript functions to immediately return a function, this syntactic sugar wouldn't be so useful there. (Of course, this is somewhat circular: what's common in a language is shaped by what the language makes easy, and a language makes things easy because they're common in that language. But that's true of all language features, and not specific to this one.)

Interestingly, even in Standard ML, the special curried-function syntax only works for function declarations (fun ...), not for function expressions (fn ...). So I can write

val op o = fn f => fn g => fn x => f (g x)

but not

val op o = fn f g x => f (g x)         (* illegal *)

In Haskell, by contrast, even function expressions support automatic currying; for example, (\ x y z -> x + y + z) 3 4 5 evaluates to 12. (Haskell also treats currying as more central in one other respect, namely that infix operators are curried functions, unlike in Standard ML where infix operators are functions that take a pair.)


问:
store variable value between program execution in c#
I have 2 console applications.

Application_B and Application_C. Both applications are collecting data from
Application_A.

Lets say if I run Application_B first and it gets data from Application_A. At the same time if I run Application_C it should  display message that values have been filled, or something like that.

答:
The option that's probably optimal for your case:

Save the value into a file in App_B and make App_C check for its presence and read it.

Detailed answer:

You need to do two things:

Save the value somewhere or otherwise make it available for reading from App_C

Signal App_C of the event

There is a multitude of possible solutions that include:

the simplest: save the value into a file (if it's an entire structure, probably by serializing it) and make App_C check for its presence

if the value must only be available while App_B is running, the latter can provide the means to read it via IPC. App_C then can check for App_B's process and/or for the communication channel's (e.g. a named pipe's) availability.


问:
Does Cn1 support serial ports?
I will need the ability to communicate with a device attached via USB that shows up as a serial port.  Is this possible with cn1?  I haven't seen any reference to it.  Does the native java import javax.comm.*; work on all platforms?</p>

答:
No, comm isn't portable. You would be able to bundle it into the desktop port but you'd need a different implementation for everything else using the native interfaces.

Before we had builtin support for sockets Steve created a cn1lib for socket support which you can use as a reference to how one would implement streaming data over native interfaces

Title: Does Cn1 support serial ports?


问:
Yii2 Update records resulting from query
I need to update month_no fields of the records resulting from a select query using some variables passed from controller but every field is written with the same value.

These are the variables:

```<code>    $id_calc = 27
    $from_y = "2013-05-01"
    $to_y = "2015-11-31"
</code>```

The table result:

```<code>   id   id_paid   year_ref     month_no
    1        26      2012         12
    2        26      2013         12
    4        27      2013         12  (should be 8)
    5        27      2014         12
    6        27      2015         12  (should be 11)
</code>```

This is model:

```<code> public function CorrectTable($id_calc, $from_y, $to_y)
    {
        $connection = Yii::$app->db;
        $query = "SELECT * FROM my_table where id_paid='$id_calc'";
        $data = $connection->createCommand($query)->queryAll();
        // calculate no. of month first and last year
        $month_no_begin = (13 - date("m",strtotime($from_y)));
        $month_no_end = (date("m",strtotime($to_y)));
        //
        foreach($data as $row)
        {
          $id = $row['id'];
          // calculate number of month per year
          if ($row['year_ref'] = date("Y",strtotime($from_y)))
          {
            $month_no = $month_no_begin;
          } elseif  ($row['year_ref'] = date("Y",strtotime($to_y)))
          {
            $month_no = $month_no_end;
          } else
          {
            $month_no = 12;
          }
            Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
        }
</code>```

I tried to put the above code in controller with the same result.

答:
our if ... esleif ... else sequence seems not logig
as you done the else if is never executed

so you should change the condition this way  the e

```<code> foreach($data as $row)
    {
        $id = $row['id'];

        // assigne default value
        $month_no = 12;

        // check for month_begin
        if ($row['year_ref'] == date("Y",strtotime($from_y)))
        {
            $month_no = $month_no_begin;
        }

        //check for month_end
        if ($row['year_ref'] == date("Y",strtotime($to_y)))
        {
            $month_no = $month_no_end;
        }

        Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
    }
</code>```

Body:
I need to update month_no fields of the records resulting from a select query using some variables passed from controller but every field is written with the same value.

These are the variables:

    $id_calc = 27
    $from_y = "2013-05-01"
    $to_y = "2015-11-31"

The table result:

   id   id_paid   year_ref     month_no
    1        26      2012         12
    2        26      2013         12
    4        27      2013         12  (should be 8)
    5        27      2014         12
    6        27      2015         12  (should be 11)

This is model:

 public function CorrectTable($id_calc, $from_y, $to_y)
    {
        $connection = Yii::$app->db;
        $query = "SELECT * FROM my_table where id_paid='$id_calc'";
        $data = $connection->createCommand($query)->queryAll();
        // calculate no. of month first and last year
        $month_no_begin = (13 - date("m",strtotime($from_y)));
        $month_no_end = (date("m",strtotime($to_y)));
        //
        foreach($data as $row)
        {
          $id = $row['id'];
          // calculate number of month per year
          if ($row['year_ref'] = date("Y",strtotime($from_y)))
          {
            $month_no = $month_no_begin;
          } elseif  ($row['year_ref'] = date("Y",strtotime($to_y)))
          {
            $month_no = $month_no_end;
          } else
          {
            $month_no = 12;
          }
            Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
        }

I tried to put the above code in controller with the same result.

Body:
our if ... esleif ... else sequence seems not logig
as you done the else if is never executed

so you should change the condition this way  the e

 foreach($data as $row)
    {
        $id = $row['id'];

        // assigne default value
        $month_no = 12;

        // check for month_begin
        if ($row['year_ref'] == date("Y",strtotime($from_y)))
        {
            $month_no = $month_no_begin;
        }

        //check for month_end
        if ($row['year_ref'] == date("Y",strtotime($to_y)))
        {
            $month_no = $month_no_end;
        }

        Yii::$app->db->createCommand()
            ->update('my_table', ['month_no' => $month_no], ['id' => $id])
            ->execute();
    }


问:
Referencing a static class from an array?
I have a list of numbers, and each number that is the same should act exactly the same. So I have static classes for each number so that if I change the class, so do all of the numbers it references to.

The way the numbers are accessed is via a wrapper function, so that I'm not referencing the array directly, e.g.:

```<code>Map.GetBlock(x,y).AccessToStaticClassMembers;
</code>```

So, how would I go about this?

答: Why make it static? This looks more like overrides of some abstract method or implementations of some interface method, if I got you correctly.</p>

Body:
I have a list of numbers, and each number that is the same should act exactly the same. So I have static classes for each number so that if I change the class, so do all of the numbers it references to.

The way the numbers are accessed is via a wrapper function, so that I'm not referencing the array directly, e.g.:

Map.GetBlock(x,y).AccessToStaticClassMembers;

So, how would I go about this?


问:
jQuery get a smooth update of li elements Ajax
Im wondering how I can implement a smooth autocomplete ul, The problem is that whenever it is updated it blinks, By smooth I mean that it does not blink, to be more precise to act like the one of google, everytime you type something, the list of results is updated without blinking.

My code:

```<code>    $("#uname").on("input", function () {
        let data = {"name": $("#uname").val()};
        $(".suggested-names ul li").remove(); //remove previous results
        $.ajax({
            url: "searchInDB.php",
            method: "POST",
            data: data,
            dataType: "json",
            success: function (response) {
                for(var key in response){
                    $(".suggested-names ul").append("<li>" + response[key] +"</li>"); //update results
                }
            }
        });
    });
</code>```

The css:

```<code>    .suggested-names{
    min-width: 100%;
    background: #fff;
    position: absolute;
    z-index: 2;
}
.suggested-names ul{
    min-width: 100%;
    max-width: 100%;
    margin: 0;
    padding:0px;
    box-shadow: #8c8c8c 0 4px 3px 0;
}
.suggested-names li{
    text-decoration: none;
    list-style: none;
    padding:5px;
    font-size: 16px;
    color: #0f0f0f;
}
.suggested-names li:hover{
    background: #eeeeee;
    cursor: pointer;
}
.suggested-names li:last-of-type{
    border: none;
}
</code>```

My code makes a request to a PHP script that returns an array of strings, each time the user writes or deletes something it is updated up it doesn't look very good, It blinks and I can't figure out how to fix it, It would be awesome that you could help me.

And also if there is a better way to do what Im trying to do I'm opened to listen to your ideas. Thanks

答:
I'd suggest removing the elements from the ul only in the success function because AJAX is asynchronous and there's a delay between the removal and insertion of the elements.

```<code>$("#uname").on("input", function () {
    let data = {"name": $("#uname").val()};
    $.ajax({
        url: "searchInDB.php",
        method: "POST",
        data: data,
        dataType: "json",
        success: function (response) {
            $(".suggested-names ul li").remove(); //remove previous results
            for(var key in response){
                $(".suggested-names ul").append("<li>" + response[key] +"</li>"); //update results
            }
        }
    });
});
</code>```

Here's a Fiddle demonstrating the principle.

Note: jQuery deprecated the success function so in the future consider using .done() instead.

From the documentation:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Also note that if response is an array and not an object you shouldn't use the for(var ... in ...) for loop, it's consider better practice to loop trough it with a regular for.

And if it is an object, you should test for response.hasOwnProperty(key), otherwise it will match any user-defined properties which extend the Object.prototype.

Body:
Im wondering how I can implement a smooth autocomplete ul, The problem is that whenever it is updated it blinks, By smooth I mean that it does not blink, to be more precise to act like the one of google, everytime you type something, the list of results is updated without blinking.

My code:

    $("#uname").on("input", function () {
        let data = {"name": $("#uname").val()};
        $(".suggested-names ul li").remove(); //remove previous results
        $.ajax({
            url: "searchInDB.php",
            method: "POST",
            data: data,
            dataType: "json",
            success: function (response) {
                for(var key in response){
                    $(".suggested-names ul").append("
" + response[key] +"
"); //update results
                }
            }
        });
    });

The css:

    .suggested-names{
    min-width: 100%;
    background: #fff;
    position: absolute;
    z-index: 2;
}
.suggested-names ul{
    min-width: 100%;
    max-width: 100%;
    margin: 0;
    padding:0px;
    box-shadow: #8c8c8c 0 4px 3px 0;
}
.suggested-names li{
    text-decoration: none;
    list-style: none;
    padding:5px;
    font-size: 16px;
    color: #0f0f0f;
}
.suggested-names li:hover{
    background: #eeeeee;
    cursor: pointer;
}
.suggested-names li:last-of-type{
    border: none;
}

My code makes a request to a PHP script that returns an array of strings, each time the user writes or deletes something it is updated up it doesn't look very good, It blinks and I can't figure out how to fix it, It would be awesome that you could help me.

And also if there is a better way to do what Im trying to do I'm opened to listen to your ideas. Thanks

Body:
I'd suggest removing the elements from the ul only in the success function because AJAX is asynchronous and there's a delay between the removal and insertion of the elements.

$("#uname").on("input", function () {
    let data = {"name": $("#uname").val()};
    $.ajax({
        url: "searchInDB.php",
        method: "POST",
        data: data,
        dataType: "json",
        success: function (response) {
            $(".suggested-names ul li").remove(); //remove previous results
            for(var key in response){
                $(".suggested-names ul").append("<li>" + response[key] +"</li>"); //update results
            }
        }
    });
});

Here's a Fiddle demonstrating the principle.

Note: jQuery deprecated the success function so in the future consider using .done() instead.

From the documentation:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Also note that if response is an array and not an object you shouldn't use the for(var ... in ...) for loop, it's consider better practice to loop trough it with a regular for.

And if it is an object, you should test for response.hasOwnProperty(key), otherwise it will match any user-defined properties which extend the Object.prototype.


问:
Is it possible to turn text to speech using the Google assistant SDK?
Is it possible that after doing processing, I can turn a certain text result to speech using the SDK. Or say turn an alarm or warning message to speech eg. "You have left the gas on" .etc.</p>

答:
Not sure how much this will help, but you may want to look at the IfTTT (If This Than That) app.

I know they have a bunch of pre-made applets you can use that run on the Google Assistant API, and you can make your own too! If you have a nest fire alarm, for example, you can have the assistant and the alarm talk to one another.

On my Google Assistant Raspberry Pi, I can instruct it to change the temperature on the thermostat, for example. I can also set it up to give custom (often humerus), replies to specific commands. I know you can give it commands, and it will give back a custom TTS response. But I'm not sure you can make it read your devices and give an automatic response yet (E.g., If the Nest Alarm detects fire, Then send the message "FIRE! Get out!" to assistant). Pretty sure it's one way at the moment. Hope this helped and Cheers!


问:
How to push down main menu while expanding nested menu using Flex CSS?
I have two level menu (main and nested). The menu appears as Flex column on small screen size but when I hover on the main menu the sub menu appears top of the main menu. How can I push down the main menu to make require room for sub menu while expanding?

#main-menu ul {
    display: flex;
    flex-direction: row;
    background-color: #F2F3F4;
    padding: 0;
}
#main-menu ul li {
    position: relative;
    flex: 1 0 auto;
    text-align: left;
}
#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;
}
#main-menu ul ul {
    left: 0;
    top: 10;
}
#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
    display: flex;
    flex-direction: column;
}
#main-menu ul a {
    display: block;
    padding: 10px;
}
#main-menu ul a:hover {
    background-color: #B2BABB;
}
@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav id="main-menu">
<ul>
    <li>Item 1
        <ul id="sub-menu">
            <li>Item 1.1</li>
            <li>Item 1.2</li>
            <li>Item 1.3</li>
        </ul>
    </li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>
</nav></code>```

答:
You can add position: static for you submenu:

#main-menu ul {
  display: flex;
  flex-direction: row;
  background-color: #F2F3F4;
  padding: 0;
}

#main-menu ul li {
  position: relative;
  flex: 1 0 auto;
  text-align: left;
}

#main-menu li ul {
  display: none;
  width: 100%;
  position: absolute;
}

#main-menu ul ul {
  left: 0;
  top: 10;
}

#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
  display: flex;
  flex-direction: column;
}

#main-menu ul a {
  display: block;
  padding: 10px;
}

#main-menu ul a:hover {
  background-color: #B2BABB;
}

@media only screen and (max-width: 768px) {
  #main-menu ul {
    flex-direction: column;
  }

  /* new */
  #main-menu ul ul {
    position: static;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav id="main-menu">
  <ul>
    <li>Item 1
      <ul id="sub-menu">
        <li>Item 1.1</li>
        <li>Item 1.2</li>
        <li>Item 1.3</li>
      </ul>
    </li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
</nav></code>```

Body:
I have two level menu (main and nested). The menu appears as Flex column on small screen size but when I hover on the main menu the sub menu appears top of the main menu. How can I push down the main menu to make require room for sub menu while expanding?

#main-menu ul {
    display: flex;
    flex-direction: row;
    background-color: #F2F3F4;
    padding: 0;
}
#main-menu ul li {
    position: relative;
    flex: 1 0 auto;
    text-align: left;
}
#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;
}
#main-menu ul ul {
    left: 0;
    top: 10;
}
#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
    display: flex;
    flex-direction: column;
}
#main-menu ul a {
    display: block;
    padding: 10px;
}
#main-menu ul a:hover {
    background-color: #B2BABB;
}
@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
}

Item 1

Item 1.1

Item 1.2

Item 1.3

Item 2

Item 3

Item 4

Body:
You can add position: static for you submenu:

#main-menu ul {
  display: flex;
  flex-direction: row;
  background-color: #F2F3F4;
  padding: 0;
}

#main-menu ul li {
  position: relative;
  flex: 1 0 auto;
  text-align: left;
}

#main-menu li ul {
  display: none;
  width: 100%;
  position: absolute;
}

#main-menu ul ul {
  left: 0;
  top: 10;
}

#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
  display: flex;
  flex-direction: column;
}

#main-menu ul a {
  display: block;
  padding: 10px;
}

#main-menu ul a:hover {
  background-color: #B2BABB;
}

@media only screen and (max-width: 768px) {
  #main-menu ul {
    flex-direction: column;
  }

  /* new */
  #main-menu ul ul {
    position: static;
  }
}

<nav id="main-menu">
  <ul>
    <li><a href="#">Item 1</a>
      <ul id="sub-menu">
        <li><a href="#">Item 1.1</a></li>
        <li><a href="#">Item 1.2</a></li>
        <li><a href="#">Item 1.3</a></li>
      </ul>
    </li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a></li>
    <li><a href="#">Item 4</a></li>
  </ul>
</nav>