问:
Workaround solution to do a "INSERT...ON DUPLICATE KEY UPDATE" with null value on unique key
To begin with, here is my code structure and what I want to achieve :

I have this 3 tables :

```<code>+----------------------+
| CONFIG_CAMPAIGN      |
+----------------------+
| - id_config          |
| // other fields      |
+----------------------+

+----------------------+
| SLOT_CONFIG          |
+----------------------+
| - id_slot_config     |
| - id_config          |
| - id_slot_pb         |
+----------------------+

+----------------------+
| SLOT_PLACE_BOX       |
+----------------------+
| - id_slot_pb         |
| - id_place_box       |
| - date               |
| - hour               |
| - slot_available     |
+----------------------+
</code>```

So one "slot_place_box" can have multiple "config" and one "config" can be on multiple "slot_place_box". I have some trigger on "slot_config" to update the field "slot_available" according to the config.

Now I have a PHP where I get some FORM data and build a SQL request which look like this (when I have my problem) :

```<code>INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-10', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-10' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-11', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-11' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-12', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-12' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

// and so on
</code>```

The idea is to create a new "slot_place_box" + "slot_config" if I have no duplicate according to the new config I create before in my code

OR

If I already have a "slot_place_box" with same "id_place_box + date + hour" I only INSERT a new "slot_config" with the new_config id + the "slot_place_box" I already have.

I choose the "INSERT...ON DUPLICATE KEY /do nothing/" because I need the id of the row I INSERT / I already have.

I have an UNIQUE index key in "slot_place_box" for the fields "id_place_box + date + hour". My problem begin because "hour" can be an hour ("12:00:00" for example) but can be NULL too (= for me, when NULL it means "all day" of the "date"). When hour is NULL, my UNIQUE index doesn't work so the INSERT happens and I have duplicate in database.

So how can I make this "INSERT...ON DUPLICATE KEY UPDATE" works with an UNIQUE index with NULL value?

I can't use this solution (here) because I use MySQl 5.6 so I will try to make a trigger as someone suggest me in my last question (here).

I'm beginner in SQL so I'd like some help please to achieve this trigger please. The idea, if I understand well, is to create some "virtual" column with the trigger and add some value in it if "hour" is null + add this virtual column in my UNIQUE index so the ON DUPLICATE KEY will works.

So my questions are :

How can I create this "virtual column" in a trigger?

How can I use this "virtual column" for my UNIQUE index if I need the "hour" value when it's not NULL?

Do you have a better idea?

答:
I will anwser myself but if you guys have other solution I'm still interested to heard it. This solution works for me because I'm working on a new project so it don't really impact the code I already wrote.

To workaround this problem, I add a new column to my "slot_place_box" table :

```<code>+----------------------+
| SLOT_PLACE_BOX       |
+----------------------+
| - id_slot_pb         |
| - id_place_box       |
| - date               |
| - hour               |
| - slot_available     |
| - virtual_hour       | <- new field
+----------------------+
</code>```

This new field is a VARCHAR(10) equal to "hour" if not NULL (ex: "12:00:00") or equal to "1" by default or when "hour" is NULL.

Then I change my UNIQUE index on this table for "id_place_box + date + virtual_hour" so I will never get NULL value. Then I UPDATE the data I already have in my table :

```<code>UPDATE slot_place_box SET (virtual_hour = IF(hour is NULL, '1', hour);
// Without the safe UPDATE (I use MySQL WorkBench)
</code>```

I change my PHP loop to build my request with the new column:

```<code> foreach($SPB_data_array as $index => $SPB_data) {
    $current_id_pb = $SPB_data['id_pb'];
    $current_date  = $SPB_data['date'];

    if (!empty($SPB_data['hour'])) {
        $current_hour = $SPB_data['hour'];
        $sql_slot_pb .= 'INSERT INTO media.slot_place_box (id_place_box, date, hour, virtual_hour) VALUES ('. $current_id_pb .', \''. $current_date .'\', \''. $current_hour .'\', \''. $current_hour .'\')
                            ON DUPLICATE KEY UPDATE id_place_box=id_place_box;
                         SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB
                            WHERE SPB.id_place_box = '. $current_id_pb .' AND SPB.date = \''. $current_date .'\' AND SPB.hour = \''. $current_hour .'\');
                         INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (:new_config_id, @id);
                         ';
    } else {
        $sql_slot_pb .= 'INSERT INTO media.slot_place_box (id_place_box, date, hour) VALUES ('. $current_id_pb .', \''. $current_date .'\', NULL)
                            ON DUPLICATE KEY UPDATE id_place_box=id_place_box;
                         SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB
                            WHERE SPB.id_place_box = '. $current_id_pb .' AND SPB.date = \''. $current_date .'\' AND SPB.hour IS NULL);
                         INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (:new_config_id, @id);
                         ';
    }
}
</code>```

I just added the fourth column with the "hour" value when "hour" is NOT NULL, by default "virtual_hour" is "1" so no need to add it in this case.

I don't know if it's the best solution for BIG project with lot of data, but in my case it was the easiest way to resolve my problem.

Body:
To begin with, here is my code structure and what I want to achieve :

I have this 3 tables :

+----------------------+
| CONFIG_CAMPAIGN      |
+----------------------+
| - id_config          |
| // other fields      |
+----------------------+

+----------------------+
| SLOT_CONFIG          |
+----------------------+
| - id_slot_config     |
| - id_config          |
| - id_slot_pb         |
+----------------------+

+----------------------+
| SLOT_PLACE_BOX       |
+----------------------+
| - id_slot_pb         |
| - id_place_box       |
| - date               |
| - hour               |
| - slot_available     |
+----------------------+

So one "slot_place_box" can have multiple "config" and one "config" can be on multiple "slot_place_box". I have some trigger on "slot_config" to update the field "slot_available" according to the config.

Now I have a PHP where I get some FORM data and build a SQL request which look like this (when I have my problem) :

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-10', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-10' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-11', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-11' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-12', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-12' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);

// and so on

The idea is to create a new "slot_place_box" + "slot_config" if I have no duplicate according to the new config I create before in my code

OR

If I already have a "slot_place_box" with same "id_place_box + date + hour" I only INSERT a new "slot_config" with the new_config id + the "slot_place_box" I already have.

I choose the "INSERT...ON DUPLICATE KEY /do nothing/" because I need the id of the row I INSERT / I already have.

I have an UNIQUE index key in "slot_place_box" for the fields "id_place_box + date + hour". My problem begin because "hour" can be an hour ("12:00:00" for example) but can be NULL too (= for me, when NULL it means "all day" of the "date"). When hour is NULL, my UNIQUE index doesn't work so the INSERT happens and I have duplicate in database.

So how can I make this "INSERT...ON DUPLICATE KEY UPDATE" works with an UNIQUE index with NULL value?

I can't use this solution (here) because I use MySQl 5.6 so I will try to make a trigger as someone suggest me in my last question (here).

I'm beginner in SQL so I'd like some help please to achieve this trigger please. The idea, if I understand well, is to create some "virtual" column with the trigger and add some value in it if "hour" is null + add this virtual column in my UNIQUE index so the ON DUPLICATE KEY will works.

So my questions are :

How can I create this "virtual column" in a trigger?

How can I use this "virtual column" for my UNIQUE index if I need the "hour" value when it's not NULL?

Do you have a better idea?

Body:
I will anwser myself but if you guys have other solution I'm still interested to heard it. This solution works for me because I'm working on a new project so it don't really impact the code I already wrote.

To workaround this problem, I add a new column to my "slot_place_box" table :

+----------------------+
| SLOT_PLACE_BOX       |
+----------------------+
| - id_slot_pb         |
| - id_place_box       |
| - date               |
| - hour               |
| - slot_available     |
| - virtual_hour       | <- new field
+----------------------+

This new field is a VARCHAR(10) equal to "hour" if not NULL (ex: "12:00:00") or equal to "1" by default or when "hour" is NULL.

Then I change my UNIQUE index on this table for "id_place_box + date + virtual_hour" so I will never get NULL value. Then I UPDATE the data I already have in my table :

UPDATE slot_place_box SET (virtual_hour = IF(hour is NULL, '1', hour);
// Without the safe UPDATE (I use MySQL WorkBench)

I change my PHP loop to build my request with the new column:

 foreach($SPB_data_array as $index => $SPB_data) {
    $current_id_pb = $SPB_data['id_pb'];
    $current_date  = $SPB_data['date'];

    if (!empty($SPB_data['hour'])) {
        $current_hour = $SPB_data['hour'];
        $sql_slot_pb .= 'INSERT INTO media.slot_place_box (id_place_box, date, hour, virtual_hour) VALUES ('. $current_id_pb .', \''. $current_date .'\', \''. $current_hour .'\', \''. $current_hour .'\')
                            ON DUPLICATE KEY UPDATE id_place_box=id_place_box;
                         SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB
                            WHERE SPB.id_place_box = '. $current_id_pb .' AND SPB.date = \''. $current_date .'\' AND SPB.hour = \''. $current_hour .'\');
                         INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (:new_config_id, @id);
                         ';
    } else {
        $sql_slot_pb .= 'INSERT INTO media.slot_place_box (id_place_box, date, hour) VALUES ('. $current_id_pb .', \''. $current_date .'\', NULL)
                            ON DUPLICATE KEY UPDATE id_place_box=id_place_box;
                         SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB
                            WHERE SPB.id_place_box = '. $current_id_pb .' AND SPB.date = \''. $current_date .'\' AND SPB.hour IS NULL);
                         INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (:new_config_id, @id);
                         ';
    }
}

I just added the fourth column with the "hour" value when "hour" is NOT NULL, by default "virtual_hour" is "1" so no need to add it in this case.

I don't know if it's the best solution for BIG project with lot of data, but in my case it was the easiest way to resolve my problem.


来源: stackexchange

问:
Conditionally show/hide divs based on select option in AMP
I am developing my first AMP site and would like to know if it's possible to show/hide multiple divs on:change based on user selection, like so.

```<code><div class="ampstart-input" id="index">
    <select name="product_type" id="product_type" required>
        <option value="type_one">Type one</option>
        <option value="type_two">Type two</option>
        <option value="type_three">Type three</option>
        <option value="type_four">Type four</option>
    </select>
</div>

<div class="loan" id="type_one" hidden">Content for product one</div>
<div class="loan" id="type_two" hidden">Content for product two</div>
<div class="loan" id="type_three" hidden">Content for product three</div>
<div class="loan" id="type_four" hidden">Content for product four</div>
</code>```

When the user changes the select field, I'd like to be able to show the selected product, and hide the others (and possibly hide the original select #index). This is familiar and simple in JavaScript, but I can't find any way to achieve it in AMP. Any help would be VERY appreciated. Thank you.

答:
Yes You can do it with simple jquery. try it will work.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Try jQuery Online</title>

    <style>
        .selected {
            color:red;
        }
        .highlight {
            background:yellow;
        }
    </style>
</head>
<body>
    <div class="ampstart-input" id="index">
        <select name="product_type" id="product_type">
            <option value="type_one">Type one</option>
            <option value="type_two">Type two</option>
            <option value="type_three">Type three</option>
            <option value="type_four">Type four</option>
        </select>
    </div>

    <div class="loan" id="type_one" >Content for product one</div>
    <div class="loan" id="type_two">Content for product two</div>
    <div class="loan" id="type_three">Content for product three</div>
    <div class="loan" id="type_four">Content for product four</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        alert("hello");
      $('#product_type').on('change', function() {
        $('.loan').each(function(i, obj) {
            $(this).css('display','none');
        });
        var select_val = $("#product_type option:selected").val();
        $("#"+select_val ).css('display','block');

    });
  });
</script>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing my first AMP site and would like to know if it's possible to show/hide multiple divs on:change based on user selection, like so.

    <select name="product_type" id="product_type" required>
        <option value="type_one">Type one</option>
        <option value="type_two">Type two</option>
        <option value="type_three">Type three</option>
        <option value="type_four">Type four</option>
    </select>

Content for product one

Content for product two

Content for product three

Content for product four

When the user changes the select field, I'd like to be able to show the selected product, and hide the others (and possibly hide the original select #index). This is familiar and simple in JavaScript, but I can't find any way to achieve it in AMP. Any help would be VERY appreciated. Thank you.

Body:
Yes You can do it with simple jquery. try it will work.

<!DOCTYPE html>
<html>
<head>
    <title>Try jQuery Online</title>

    <style>
        .selected {
            color:red;
        }
        .highlight {
            background:yellow;
        }
    </style>
</head>
<body>
    <div class="ampstart-input" id="index">
        <select name="product_type" id="product_type">
            <option value="type_one">Type one</option>
            <option value="type_two">Type two</option>
            <option value="type_three">Type three</option>
            <option value="type_four">Type four</option>
        </select>
    </div>

    <div class="loan" id="type_one" >Content for product one</div>
    <div class="loan" id="type_two">Content for product two</div>
    <div class="loan" id="type_three">Content for product three</div>
    <div class="loan" id="type_four">Content for product four</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        alert("hello");
      $('#product_type').on('change', function() {
        $('.loan').each(function(i, obj) {
            $(this).css('display','none');
        });
        var select_val = $("#product_type option:selected").val();
        $("#"+select_val ).css('display','block');

    });
  });
</script>
</html>


问:
HTTP get requests in ajax
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.

Javascript code:

```<code> $(document).ready(function () {
    $("#LoginUser").click(function () {
        $.ajax({
            url: 'http://website/api/user/Mikkel1337',
            dataType: 'json',
            type: 'GET',
            contentType: 'application/json',

            error: function () {
                alert("An error had occurred");
            },
            success: function (data) {
                var jsonStr = JSON.stringify(data);

                alert(jsonStr['password']);
            }
        });
    });
})
</code>```

The response JSON code looks like this:

```<code>{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn@mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
</code>```

When im running this I only get the error function. Any suggestions or solution is appreciated :)

答:
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:

```<code>$(document).ready(function () {
    $("#LoginUser").click(function () {
        $.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
            // do something on success
            alert(data.password);
        });
    });
});
</code>```

Cheers !!!

Title: HTTP get requests in ajax

Body:
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.

Javascript code:

 $(document).ready(function () {
    $("#LoginUser").click(function () {
        $.ajax({
            url: 'http://website/api/user/Mikkel1337',
            dataType: 'json',
            type: 'GET',
            contentType: 'application/json',

            error: function () {
                alert("An error had occurred");
            },
            success: function (data) {
                var jsonStr = JSON.stringify(data);

                alert(jsonStr['password']);
            }
        });
    });
})

The response JSON code looks like this:

{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn@mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}

When im running this I only get the error function. Any suggestions or solution is appreciated :)

Body:
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:

$(document).ready(function () {
    $("#LoginUser").click(function () {
        $.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
            // do something on success
            alert(data.password);
        });
    });
});

Cheers !!!


问:
Install ImageMagick-devel manually
I'm running into the infamous problem of installing ImageMagick on an RPM based system. After, not surprisingly, finding out that the version available in the repos is too old, I downloaded the available RPM on their website and installed that.

Apparently though its not the ImageMagick-devel package that's in the repos, as I'm now getting errors about Magick-config not existing. But I have no idea where to download the -devel package thats compatible with the much newer version of ImageMagick that I have.

Where is a place that I can download this?

答:
Development Version

```<code>svn co https://www.imagemagick.org/subversion/ImageMagick/trunk ImageMagick
</code>```

ContentLicense: CC BY-SA 2.5

Title: Install ImageMagick-devel manually

Body:
Development Version

svn co https://www.imagemagick.org/subversion/ImageMagick/trunk ImageMagick


问:
pip install python-novaclient is failing due to netifaces.c
I'm trying to install OpenStack python novaclient using pip install python-novaclient
This task fails:  netifaces.c:185:6 #error You need to add code for your platform

I have no idea what code it wants.
Does anyone understand this?

答:
Same issue in awx_task container in AWX project (Centos 7), trying to execute

```<code>pip install python-openstackclient
</code>```

Error was:

```<code>Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-LTchWP/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-86uBIZ-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-LTchWP/netifaces/
</code>```

Solved with:

```<code>yum install python-devel python-pip gcc
</code>```

Hope it will help someone!

Body:
Same issue in awx_task container in AWX project (Centos 7), trying to execute

pip install python-openstackclient

Error was:

Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-LTchWP/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-86uBIZ-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-LTchWP/netifaces/

Solved with:

yum install python-devel python-pip gcc

Hope it will help someone!


问:
Filtering a list in python with many key-value pairs
I have a list that looks like this:

```<code>commands = [
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}
]
</code>```

And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.

答:
you can make a list of k, v pairs to test for (doesn't have to be list of tuples)  </p>

```<code>hav = [('max-threshold', True), ('zero-failcount', True)]

[d for d in commands if all([d[k] == v for k, v in hav])]
</code>```

Body:
I have a list that looks like this:

commands = [
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}
]

And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.

Body:
you can make a list of k, v pairs to test for (doesn't have to be list of tuples)

hav = [('max-threshold', True), ('zero-failcount', True)]

[d for d in commands if all([d[k] == v for k, v in hav])]


问:
JQuery How to create element in created element
There is a code I'm working on - https://jsfiddle.net/md_bender/pj6a1akz/3/. I need to create new elements and append them to the existing element ul. With creating elements and appending everything is OK.
But I don't know how to create child element in the created element. I need to create

```<code><img src="path"/>
</code>```

In the div I have created earlier in script. It must be like that

```<code><div class="img-w js-popup">
    <img src="path"/>
</div>
<a href="delete.php">Delete</a>
</code>```

But only I can do is create  as next sibling to the div

```<code><div class="img-w js-popup"></div>
<img src="path"/>
<a href="delete.php">Delete</a>
</code>```

Who can help me and solve my problem?

答:
If do not need single DOMs (li, div, img) its easier to create static string and append whole into list, just like that (remember about backslashes):</p>

```<code>$('ul').append("<li><div><img src=\"//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80\" alt=\"\"/></div><a href=\"delete.php\">Delete</a></li>");
</code>```

Body:
There is a code I'm working on - https://jsfiddle.net/md_bender/pj6a1akz/3/. I need to create new elements and append them to the existing element ul. With creating elements and appending everything is OK.
But I don't know how to create child element in the created element. I need to create

In the div I have created earlier in script. It must be like that

Delete

But only I can do is create  as next sibling to the div

Delete

Who can help me and solve my problem?

Body:
If do not need single DOMs (li, div, img) its easier to create static string and append whole into list, just like that (remember about backslashes):

$('ul').append("<li><div><img src=\"//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80\" alt=\"\"/></div><a href=\"delete.php\">Delete</a></li>");


问:
Build Failure while integrating Jenkins with HP ALM
Created a Build for running Selenium Maven Scripts through jenkins and publish Results in HP ALM.
Steps I follow:-
1.Add ALM ServerName and ALM URL under Configure System>> Manage Jenkins
2.Add Build Step>> Execute HP Functional Tests from HPALM
Added the test Set Value as Root\TestSet\TestSetFolder
3.Add Post Build Action>>Publish HP Tests Result>> Reports archive Mode
4.Add>>Upload Test Result to ALM
Testing Frameowrk = Junit, Test Folder = "TestSet\TestSetFolder\TestCaseName ,Test Set Folder = "TestSet\TestSetFolder, Testing result file ="**/junitResult.xml
5. Run the Build and getting the Failure whereas my particular selenium scripts get passed. Below is the Error for Console Output.

答:
I had the same problem, that was because of "\" which were escaped by Jenkins. I don't why. If you remove them and always have a bad path you should have a trace like that :

```<code>Run mode is set to: RUN_PLANNED_HOST
Could not find TestSet Subject/Scenario/BAD_PATH/TEST_SET
================================================
Run status: Job failed, total tests: 0, succeeded: 0, failures: 0, errors: 0
================================================
Build step 'Execute HPE functional tests from HPE ALM' changed build result to FAILURE
Finished: FAILURE
</code>```

Personnaly I solved the problem replacing "\" by "\\".

Body:
I had the same problem, that was because of "\" which were escaped by Jenkins. I don't why. If you remove them and always have a bad path you should have a trace like that :

Run mode is set to: RUN_PLANNED_HOST
Could not find TestSet Subject/Scenario/BAD_PATH/TEST_SET
================================================
Run status: Job failed, total tests: 0, succeeded: 0, failures: 0, errors: 0
================================================
Build step 'Execute HPE functional tests from HPE ALM' changed build result to FAILURE
Finished: FAILURE

Personnaly I solved the problem replacing "\" by "\\".


问:
how to list the selected options and remove the selected options by using jQuery?

Below is my HTML code and i have to add jquery for this how to do?

```<code>    <div class="container">
<div class="row one">
    <h4>Staff Re-Admission</h4>
</div><br>
<div class="row">
    <p>Academic Year</p>
    <select>
        <option>2010/2011</option>
        <option>2010/2011</option>
        <option>2010/2011</option>
    </select>
</div><br>
<div class="row">
<div class="container">
  <div class="row">
  <div class="col-md-12">
  <div class="table-responsive">
    <table class="table" style="width: 100%;">
        <tbody>
        <tr>
          <td style="width: 250px"><p>Staff List</p></td>
          <td></td>
          <td><p>Continue</p></td>
          <td><p>Discontinue</p></td>
        </tr>
        <tr>
          <td><select size="14" class="Staff" multiple="multiple">
            <option value="SJB2017NT021">SJB2017NT021--Vishu</option>
            <option value="SJB2017NT022">SJB2017NT022--Naveen</option>
            <option value="SJB2017NT023">SJB2017NT023--Uday</option>
            <option value="SJB2017NT024">SJB2017NT024--Mohan</option>
            <option value="SJB2017TS019">SJB2017TS019--Thejaswini</option>
            <option value="SJB2017TS020">SJB2017TS020--Prasad</option>
          </select></td>
          <td>
            <button type="submit"  value="" id="Continue">Continue >>
            </button><br><br>
            <button type="submit"  value="" id="Discontinue">Discontinue >>
            </button><br><br>
            <button type="submit" value="" id="Back">Back To List
            <<</button>
          </td>
          <td><select size="14" multiple="multiple" class="Staff" ></select>
          </td>
          <td><select size="14" multiple="multiple" class="Staff" ></select>
          </td>
        <tr>
          <td><button type="submit">submit</button>
          <button type="submit">submit</button>
          </td>
        </tr>
        </tr>
      </tbody>
    </table>
  </div><!--end of .table-responsive-->
  </div>
  </div>
</div>
</div>
</div>
</code>```

when i selcet the option and click on continue it has to be listed in continue box and same if i select discontinue then in discontinue box and if i select back entire thing has to come back how to do this please help me out.

答:
Make 2 methods for each button and on click of each move item to particular box...

on back button click take all items from both the box (Continue and Discontinue) and add them to <select> back..
also clear both boxes...

Body:
Below is my HTML code and i have to add jquery for this how to do?

Staff Re-Admission

Academic Year

    <select>
        <option>2010/2011</option>
        <option>2010/2011</option>
        <option>2010/2011</option>
    </select>

Staff List

Continue

Discontinue

          <select size="14" class="Staff" multiple="multiple">
            <option value="SJB2017NT021">SJB2017NT021--Vishu</option>
            <option value="SJB2017NT022">SJB2017NT022--Naveen</option>
            <option value="SJB2017NT023">SJB2017NT023--Uday</option>
            <option value="SJB2017NT024">SJB2017NT024--Mohan</option>
            <option value="SJB2017TS019">SJB2017TS019--Thejaswini</option>
            <option value="SJB2017TS020">SJB2017TS020--Prasad</option>
          </select>

            <button type="submit"  value="" id="Continue">Continue >>
            </button>

            <button type="submit"  value="" id="Discontinue">Discontinue >>
            </button>

            <button type="submit" value="" id="Back">Back To List
            <<</button>

          <select size="14" multiple="multiple" class="Staff" ></select>

          <select size="14" multiple="multiple" class="Staff" ></select>

          <button type="submit">submit</button>
          <button type="submit">submit</button>

when i selcet the option and click on continue it has to be listed in continue box and same if i select discontinue then in discontinue box and if i select back entire thing has to come back how to do this please help me out.


问:
How to detect if an MPMediaItem represents a DRM-protected audio track on iOS
I would like to know if an MPMediaItem that represents a music track is for a Fairplay/DRM-protected item. Any way to do this?</p>

答:
MPMediaItemPropertyAssetURL is not nil on iPhone X running iOS 11 for songs saved offline via Apple Music but AVPlayer is unable to play them since they are DRM protected. The same song returns MPMediaItemPropertyAssetURL nil on iOS 9.

MPMediaItemPropertyAssetURL returns nil for songs added to Library via Apple Music but not available offline - both on iOS 9 & 11.

Thus, @voidStern's answer (and not Justin Kent's) is the correct way to test for DRM-protected asset.

Swift 4 version of voidStern's answer (works perfectly for me on iOS 9 to 11):

```<code>let itemUrl = targetMPMediaItem?.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
if itemUrl != nil {
    let theAsset = AVAsset(url: itemUrl!)
    if theAsset.hasProtectedContent {
        //Asset is protected
        //Must be played only via MPPlayer
    } else {
        //Asset is not protected
        //Can be played both via AVPlayer & MPPlayer\
    }
} else {
    //probably the asset is not avilable offline
    //Must be played only via MPPlayer
}
</code>```

Another correct way of checking for DRM-protected asset is by making use of protectedAsset property of MPMediaItem - an answer by @weirdyu. But, this property is available only on iOS 9.2 and above.

Swift 4 solution for this method (works perfectly for me on iOS 9.2 and above):

```<code>if #available(iOS 9.2, *) {
    if (targetMPMediaItem?.hasProtectedAsset)! {
        //asset is protected
        //Must be played only via MPMusicPlayer
    } else {
        //asset is not protected
        //Can be played both via AVPlayer & MPMusicPlayer
    }
} else {
    //Fallback on earlier versions
    //Probably use the method explained earlier
}
</code>```

Body:
MPMediaItemPropertyAssetURL is not nil on iPhone X running iOS 11 for songs saved offline via Apple Music but AVPlayer is unable to play them since they are DRM protected. The same song returns MPMediaItemPropertyAssetURL nil on iOS 9.

MPMediaItemPropertyAssetURL returns nil for songs added to Library via Apple Music but not available offline - both on iOS 9 & 11.

Thus, @voidStern's answer (and not Justin Kent's) is the correct way to test for DRM-protected asset.

Swift 4 version of voidStern's answer (works perfectly for me on iOS 9 to 11):

let itemUrl = targetMPMediaItem?.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
if itemUrl != nil {
    let theAsset = AVAsset(url: itemUrl!)
    if theAsset.hasProtectedContent {
        //Asset is protected
        //Must be played only via MPPlayer
    } else {
        //Asset is not protected
        //Can be played both via AVPlayer & MPPlayer\
    }
} else {
    //probably the asset is not avilable offline
    //Must be played only via MPPlayer
}

Another correct way of checking for DRM-protected asset is by making use of protectedAsset property of MPMediaItem - an answer by @weirdyu. But, this property is available only on iOS 9.2 and above.

Swift 4 solution for this method (works perfectly for me on iOS 9.2 and above):

if #available(iOS 9.2, *) {
    if (targetMPMediaItem?.hasProtectedAsset)! {
        //asset is protected
        //Must be played only via MPMusicPlayer
    } else {
        //asset is not protected
        //Can be played both via AVPlayer & MPMusicPlayer
    }
} else {
    //Fallback on earlier versions
    //Probably use the method explained earlier
}


问:
r googlesheets package Waiting for authentication in browser
I installed the googlesheets package and

```<code>code:
gs_auth()
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
</code>```

The browser pop up in a blank website, it is not go to the google auth page.

Below is my session_info():

```<code>R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS:
</code>```

/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

```<code>locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] googlesheets_0.2.2       Rcpp_0.12.14             ggplot2_2.2.1
quantmod_0.4-11
 [5] TTR_0.23-2               xts_0.10-0               zoo_1.8-0
dplyr_0.7.4
 [9] data.table_1.10.4-3      bindrcpp_0.2
alphavantager_0.1.0.9000 devtools_1.13.4

loaded via a namespace (and not attached):
 [1] cellranger_1.1.0 compiler_3.4.2   git2r_0.19.0     plyr_1.8.4
bindr_0.1
 [6] tools_3.4.2      digest_0.6.12    jsonlite_1.5     memoise_1.1.0
tibble_1.3.4
[11] gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.1  rlang_0.1.4
curl_3.0
[16] xml2_1.1.1       withr_2.1.0      httr_1.3.1       stringr_1.2.0
knitr_1.17
[21] hms_0.4.0        grid_3.4.2       glue_1.2.0       R6_2.2.2
purrr_0.2.4
[26] readr_1.1.1      magrittr_1.5     scales_0.5.0
assertthat_0.2.0 colorspace_1.3-2
[31] httpuv_1.3.5     stringi_1.1.6    openssl_0.9.9    lazyeval_0.2.1
munsell_0.4.3
</code>```

I have checked my httr package is updated, so I have not idea where the problem is. please advice.

Thanks.

答:
Per the R help for gs_auth(), this function is not typically called directly by end users.  Instead, it is called by other functions in the googlesheets package when they need to authenticate with Google.

Instead, if you try to get a list of worksheets from a Google account, it will ask you to authenticate with a Google account. For example:

```<code> mySheetList <- gs_ls()
</code>```

...will initiate a login sequence that asks you to cut & paste an authentication URL into your web browser. Subsequent steps generate a token that is pasted back into the R console to authenticate.

Details including screen shots on how to authenticate Google Sheets may be found in the Working with Google Sheets section of my article Running R and RStudio on a Chromebook.

Here is an R console log including sessionInfo() illustrating the packages and versions used.

```<code>> library(googlesheets)
> theSheetList <- gs_ls()
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
> theSheetList
# A tibble: 1 x 10
               sheet_title        author  perm version             updated sheet_key
                     <chr>         <chr> <chr>   <chr>              <dttm>     <chr>
1             PokemonStats    greskilabs    rw     new 2017-07-08 22:40:15 13rGxY7S…
 # ... with 4 more variables: ws_feed <chr>, alternate <chr>, self <chr>, alt_key <chr>
>
> sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] googlesheets_0.2.2

loaded via a namespace (and not attached):
[1] Rcpp_0.12.13     dplyr_0.7.4      assertthat_0.2.0 cellranger_1.1.0 R6_2.2.2         jsonlite_1.5     magrittr_1.5
[8] httr_1.3.1       stringi_1.1.5    rlang_0.1.2      curl_3.0        bindrcpp_0.2     xml2_1.1.1       tools_3.4.2
[15] stringr_1.2.0    glue_1.1.1       purrr_0.2.4      httpuv_1.3.5     yaml_2.1.14      compiler_3.4.2   pkgconfig_2.0.1
[22] openssl_0.9.7    bindr_0.1        tibble_1.3.4
>
</code>```

Body:
I installed the googlesheets package and

code:
gs_auth()
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort

The browser pop up in a blank website, it is not go to the google auth page.

Below is my session_info():

R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS:

/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] googlesheets_0.2.2       Rcpp_0.12.14             ggplot2_2.2.1
quantmod_0.4-11
 [5] TTR_0.23-2               xts_0.10-0               zoo_1.8-0
dplyr_0.7.4
 [9] data.table_1.10.4-3      bindrcpp_0.2
alphavantager_0.1.0.9000 devtools_1.13.4

loaded via a namespace (and not attached):
 [1] cellranger_1.1.0 compiler_3.4.2   git2r_0.19.0     plyr_1.8.4
bindr_0.1
 [6] tools_3.4.2      digest_0.6.12    jsonlite_1.5     memoise_1.1.0
tibble_1.3.4
[11] gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.1  rlang_0.1.4
curl_3.0
[16] xml2_1.1.1       withr_2.1.0      httr_1.3.1       stringr_1.2.0
knitr_1.17
[21] hms_0.4.0        grid_3.4.2       glue_1.2.0       R6_2.2.2
purrr_0.2.4
[26] readr_1.1.1      magrittr_1.5     scales_0.5.0
assertthat_0.2.0 colorspace_1.3-2
[31] httpuv_1.3.5     stringi_1.1.6    openssl_0.9.9    lazyeval_0.2.1
munsell_0.4.3

I have checked my httr package is updated, so I have not idea where the problem is. please advice.

Thanks.

Body:
Per the R help for gs_auth(), this function is not typically called directly by end users.  Instead, it is called by other functions in the googlesheets package when they need to authenticate with Google.

Instead, if you try to get a list of worksheets from a Google account, it will ask you to authenticate with a Google account. For example:

 mySheetList <- gs_ls()

...will initiate a login sequence that asks you to cut & paste an authentication URL into your web browser. Subsequent steps generate a token that is pasted back into the R console to authenticate.

Details including screen shots on how to authenticate Google Sheets may be found in the Working with Google Sheets section of my article Running R and RStudio on a Chromebook.

Here is an R console log including sessionInfo() illustrating the packages and versions used.

> library(googlesheets)
> theSheetList <- gs_ls()
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
> theSheetList
# A tibble: 1 x 10
               sheet_title        author  perm version             updated sheet_key
                     <chr>         <chr> <chr>   <chr>              <dttm>     <chr>
1             PokemonStats    greskilabs    rw     new 2017-07-08 22:40:15 13rGxY7S…
 # ... with 4 more variables: ws_feed <chr>, alternate <chr>, self <chr>, alt_key <chr>
>
> sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] googlesheets_0.2.2

loaded via a namespace (and not attached):
[1] Rcpp_0.12.13     dplyr_0.7.4      assertthat_0.2.0 cellranger_1.1.0 R6_2.2.2         jsonlite_1.5     magrittr_1.5
[8] httr_1.3.1       stringi_1.1.5    rlang_0.1.2      curl_3.0        bindrcpp_0.2     xml2_1.1.1       tools_3.4.2
[15] stringr_1.2.0    glue_1.1.1       purrr_0.2.4      httpuv_1.3.5     yaml_2.1.14      compiler_3.4.2   pkgconfig_2.0.1
[22] openssl_0.9.7    bindr_0.1        tibble_1.3.4
>


问:
How can I give my right div margin top property here?

Hi,

I want the right div with red background some margin top property but still stay the same in the blue box. How can I achieve this? If I give margin top to the div now, it moves the whole blue div.

    left

    right

```

答:
You need to use float on both elements (if at all. A nice alternative to using float is using flexbox). You also don't need the margin-left.

#right {
  background-color: red;
  height: 50px;
  width: 50px;
  margin-top: 50px;
  float: left
}

#left {
  background-color: green;
  height: 50px;
  width: 50px;
  float: left
}

#wrapper {
  width: 100%;
  height: 100px;
  background-color: blue
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="left">
    left
  </div>
  <div id="right">
    right
  </div>
</div></code>```

Body:
You need to use float on both elements (if at all. A nice alternative to using float is using flexbox). You also don't need the margin-left.

#right {
  background-color: red;
  height: 50px;
  width: 50px;
  margin-top: 50px;
  float: left
}

#left {
  background-color: green;
  height: 50px;
  width: 50px;
  float: left
}

#wrapper {
  width: 100%;
  height: 100px;
  background-color: blue
}

<div id="wrapper">
  <div id="left">
    left
  </div>
  <div id="right">
    right
  </div>
</div>


问:
Compilation error when passing Integer into generic method with Function<T, ? extends Number>>
I have some code with 3 overriding methods that perform the same operation ( code is identically for each method) on the Inputs, the only difference between them is the input parameter type

```<code>private List<String> extractDoubleValues(Function<MyClass, List<Double>> extractions)
private List<String> extractLongValues(Function<MyClass List<Long>> extractions)
private List<String> extractIntegerValues(Function<MyClass, List<Integer>> extractions)
</code>```

I was trying to attempt to replace these 3 methods with a single method that makes us of generic wildcards as follows

```<code>private List<String> extractNumberValues(Function<MyClass, List<? extends Number>> extractions)
</code>```

When I attempt to use the above generic method in place of one of the 3 type specific methods

```<code>Function<MyClass, List<Integer>> intExtractions;
List<String> extractedValues = extractNumberValues(intExtractions);
</code>```

I get a the following compilation error on the second line of code above

```<code>Error:(59, 80) java: incompatible types: java.util.function.Function<MyClass,java.util.List<java.lang.Double>> cannot be converted to java.util.function.Function<MyClass,java.util.List<? extends java.lang.Number>>
</code>```

I've successfully replaced duplicate methods with the wildcard before, as bellow

```<code>List<String> convertNumberListToStringList(List<Integer> numberList)
List<String> convertNumberListToStringList(List<Double> numberList)
</code>```

with

```<code>List<String> convertNumberListToStringList(List<? extends Number> numberList)
</code>```

I'm new to the idea of generics so I was curious as why the above would fail to compile? I do not quite understand why it would fail to compile

答:
Major problem(or i should say feature?) here is generic are used only during compilation. During runtime you do not have any information about generic. In other words you have to consider List<Integer> and List<Double> and completelly different types. If you see inside Fucntion class you will see <T, R> without wildcard. So even Function use List<Integer> and List<Double> as completelly different types. If y ou want to say to Function that R will be something of List type, you have to code it like:

```<code>Function<SomeClass, ? extends List<? extends SomeOtherClass>>
</code>```

By code above you are telling that R will be List for sure and list will contain instances of SomeOtherClass.

Main point during work with generic is that generic changes original class to some other class...

Body:
I have some code with 3 overriding methods that perform the same operation ( code is identically for each method) on the Inputs, the only difference between them is the input parameter type

private List<String> extractDoubleValues(Function<MyClass, List<Double>> extractions)
private List<String> extractLongValues(Function<MyClass List<Long>> extractions)
private List<String> extractIntegerValues(Function<MyClass, List<Integer>> extractions)

I was trying to attempt to replace these 3 methods with a single method that makes us of generic wildcards as follows

private List<String> extractNumberValues(Function<MyClass, List<? extends Number>> extractions)

When I attempt to use the above generic method in place of one of the 3 type specific methods

Function<MyClass, List<Integer>> intExtractions;
List<String> extractedValues = extractNumberValues(intExtractions);

I get a the following compilation error on the second line of code above

Error:(59, 80) java: incompatible types: java.util.function.Function<MyClass,java.util.List<java.lang.Double>> cannot be converted to java.util.function.Function<MyClass,java.util.List<? extends java.lang.Number>>

I've successfully replaced duplicate methods with the wildcard before, as bellow

List<String> convertNumberListToStringList(List<Integer> numberList)
List<String> convertNumberListToStringList(List<Double> numberList)

with

List<String> convertNumberListToStringList(List<? extends Number> numberList)

I'm new to the idea of generics so I was curious as why the above would fail to compile? I do not quite understand why it would fail to compile

Body:
Major problem(or i should say feature?) here is generic are used only during compilation. During runtime you do not have any information about generic. In other words you have to consider List<Integer> and List<Double> and completelly different types. If you see inside Fucntion class you will see <T, R> without wildcard. So even Function use List<Integer> and List<Double> as completelly different types. If y ou want to say to Function that R will be something of List type, you have to code it like:

Function<SomeClass, ? extends List<? extends SomeOtherClass>>

By code above you are telling that R will be List for sure and list will contain instances of SomeOtherClass.

Main point during work with generic is that generic changes original class to some other class...


问:
how do you organize your programming work
I'm a newbie in the field, but in the near future I have to develop an application for a friend(I've already did some work of the app and the friend is happy).

I assume that I need 3 places to store my work, but I'm not sure if this is the best approach. I need your advice, opinion, link,book, blog about this subject.

I plan to have:

a place where I develop the application

a place where I keep a back-up of the application

a place with the application ready for use

I'll use git in the development stage, but for the later I don't know what tools to use, or which are the good practices. Can you give me an advice?

PS: at this moment I'm using cakephp to build some webapps, but I play with C++ from time to time too.

答:
A lot of people have talked about having an issue/feature tracker for your work. If it is only you that is doing work I recommend you to have a look at FreeMind.

Mind mappings is an excellent way of keeping track of the tasks and things you need to do for you project. Write down any thought that you want to keep, but you don't have time to do right now.

Edit: I added an example for a task for an expansion in my open source project:

Mind Map example


问:
Group joining data in D3 v4
I switched to version 4 of D3 and having issues with the new enter, update, exit model. I quite dont get it and I don't know how to use it when creating nested dom elements. Could someone show me, how I should adjust my Code.</p>

```<code>var c2 = d3.select("#formdfield-node").selectAll(".ND-searchresults")
    .data([0]);

c2.enter()
    .append("div")
    .attr("class", "ND-searchresults");

c2.exit().remove();

var c3 = c2.selectAll(".ND-searchresults-list")
    .data(function(d) {
        return [d]
    });

c3.enter()
    .append("ul")
    .attr("class", "ND-searchresults-list");

c3.exit().remove();

var bsl = c3.selectAll(".ND-selection-rows")
    .data(vmh.filter(function(d) {
        return (d.logicalName.toLowerCase().match(re) || d.networkName.toLowerCase().match(re));
    }));

bsl.enter()
    .append("li")
    .attr("class", "ND-selection-rows")
    .attr("id", "ND-selection-rows")
    .on("mouseup", function(d) {

        d3.select("#info-sw-node").property("value", d.logicalName + " - " + d.networkName);
        _thisNode = d;
        d3.select(".ND-searchresults").remove();

    });

bsl.exit().remove();

var bsrows = bsl.selectAll(".ND-rows-name")
    .data(function(d) {
        return [d];
    });

bsrows.text(function(d) {
    return d.logicalName + " - " + d.networkName
});

bsrows.enter()
    .append("div")
    .attr("class", "ND-rows-name")
    .text(function(d) {
        return d.logicalName + " - " + d.networkName
    });

bsrows.exit().remove();
</code>```

答:
Ok fixed my Problem now by using merge </p>

```<code>d3.select(".searchbar")
.on("input", function(d) {

    if (!this.value == ""){

        var vvalue = this.value.toString().toLowerCase();
        var re = new RegExp(vvalue);

        var a = d3.select(".search").selectAll(".BS-searchresults").data([BS]);

        var a_enter = a.enter()
        .append("div")
        .attr("class","BS-searchresults");

        var a_update = a.merge(a_enter);

        a.exit().remove();

            var b = a_update.selectAll(".BS-searchresults-list").data(function (d) {return [d]});

            var b_enter =   b.enter()
                            .append("ul")
                            .attr("class","BS-searchresults-list");

            var b_update = b.merge(b_enter);

            b.exit().remove();

                var c = b_update.selectAll(".BS-selection-rows").data(function (d) {return d.filter(function(d) { return (d.logicalName.toLowerCase().match(re) || d.networkName.toLowerCase().match(re))})});

                var c_enter =   c.enter()
                                .append("li")
                                .attr("class", "BS-selection-rows")
                                .attr("id", "BS-selection-rows");

                var c_update = c.merge(c_enter)
                .attr("title", function(d) {return d.networkName});

                c.exit().remove();

                    var d = c_update.selectAll(".BS-rows-name").data(function (d) {return [d]});

                    var d_enter =   d.enter()
                                    .append("div")
                                    .attr("class", "BS-rows-name");

                    var d_update = d.merge(d_enter)
                    .text(function(d) {return d.logicalName+" - "+d.networkName})
                    .on("mouseup", function(d){

                                d3.select(".searchbar").property("value", d.logicalName+" - "+d.networkName);
                                d3.select(".BS-searchresults").remove();
                                loadBS(d);
                    });;

                    d.exit().remove();

                        //Außerhalb klicken um die Liste auszublenden

                        $(window).click(function() {
                            d3.select(".BS-searchresults").remove();
                        });

                        $('#BS-selection-rows').click(function(event){
                            event.stopPropagation();
                        });

                        $('#bs-search').click(function(event){
                            event.stopPropagation();
                        });

    }else{
       d3.select(".BS-searchresults").remove();
    }
 });
});
</code>```

Title: Group joining data in D3 v4

Body:
I switched to version 4 of D3 and having issues with the new enter, update, exit model. I quite dont get it and I don't know how to use it when creating nested dom elements. Could someone show me, how I should adjust my Code.

var c2 = d3.select("#formdfield-node").selectAll(".ND-searchresults")
    .data([0]);

c2.enter()
    .append("div")
    .attr("class", "ND-searchresults");

c2.exit().remove();

var c3 = c2.selectAll(".ND-searchresults-list")
    .data(function(d) {
        return [d]
    });

c3.enter()
    .append("ul")
    .attr("class", "ND-searchresults-list");

c3.exit().remove();

var bsl = c3.selectAll(".ND-selection-rows")
    .data(vmh.filter(function(d) {
        return (d.logicalName.toLowerCase().match(re) || d.networkName.toLowerCase().match(re));
    }));

bsl.enter()
    .append("li")
    .attr("class", "ND-selection-rows")
    .attr("id", "ND-selection-rows")
    .on("mouseup", function(d) {

        d3.select("#info-sw-node").property("value", d.logicalName + " - " + d.networkName);
        _thisNode = d;
        d3.select(".ND-searchresults").remove();

    });

bsl.exit().remove();

var bsrows = bsl.selectAll(".ND-rows-name")
    .data(function(d) {
        return [d];
    });

bsrows.text(function(d) {
    return d.logicalName + " - " + d.networkName
});

bsrows.enter()
    .append("div")
    .attr("class", "ND-rows-name")
    .text(function(d) {
        return d.logicalName + " - " + d.networkName
    });

bsrows.exit().remove();

Body:
Ok fixed my Problem now by using merge

d3.select(".searchbar")
.on("input", function(d) {

    if (!this.value == ""){

        var vvalue = this.value.toString().toLowerCase();
        var re = new RegExp(vvalue);

        var a = d3.select(".search").selectAll(".BS-searchresults").data([BS]);

        var a_enter = a.enter()
        .append("div")
        .attr("class","BS-searchresults");

        var a_update = a.merge(a_enter);

        a.exit().remove();

            var b = a_update.selectAll(".BS-searchresults-list").data(function (d) {return [d]});

            var b_enter =   b.enter()
                            .append("ul")
                            .attr("class","BS-searchresults-list");

            var b_update = b.merge(b_enter);

            b.exit().remove();

                var c = b_update.selectAll(".BS-selection-rows").data(function (d) {return d.filter(function(d) { return (d.logicalName.toLowerCase().match(re) || d.networkName.toLowerCase().match(re))})});

                var c_enter =   c.enter()
                                .append("li")
                                .attr("class", "BS-selection-rows")
                                .attr("id", "BS-selection-rows");

                var c_update = c.merge(c_enter)
                .attr("title", function(d) {return d.networkName});

                c.exit().remove();

                    var d = c_update.selectAll(".BS-rows-name").data(function (d) {return [d]});

                    var d_enter =   d.enter()
                                    .append("div")
                                    .attr("class", "BS-rows-name");

                    var d_update = d.merge(d_enter)
                    .text(function(d) {return d.logicalName+" - "+d.networkName})
                    .on("mouseup", function(d){

                                d3.select(".searchbar").property("value", d.logicalName+" - "+d.networkName);
                                d3.select(".BS-searchresults").remove();
                                loadBS(d);
                    });;

                    d.exit().remove();

                        //Außerhalb klicken um die Liste auszublenden

                        $(window).click(function() {
                            d3.select(".BS-searchresults").remove();
                        });

                        $('#BS-selection-rows').click(function(event){
                            event.stopPropagation();
                        });

                        $('#bs-search').click(function(event){
                            event.stopPropagation();
                        });

    }else{
       d3.select(".BS-searchresults").remove();
    }
 });
});


问:
VBA Excel : Subroutine work but if called, It no longer works
Hi there Stuck with a CALL problem

I created a subroutine called Daily_Proto_1
It copies data from the user form to my worksheet : This is the code:

```<code>Public Sub Daily_Proto_1()
Dim LastRow As Long, ws As Worksheet

    Set ws = Sheets("DailyRep")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row

'Adds the TextBox1 into Col A & Last Blank Row
'Adds the TextBox2 into Col B & Last Blank Row
'Adds the ComboBox1 into Col C & Last Blank Row
'Ect.

    ws.Range("A" & LastRow).Value = TextBox1.Text
    ws.Range("B" & LastRow).Value = TextBox2.Text
    ws.Range("C" & LastRow).Value = ComboBox1.Text
    ws.Range("D" & LastRow).Value = TextBox3.Text
    ws.Range("E" & LastRow).Value = ComboBox2.Text
    ws.Range("F" & LastRow).Value = ComboBox3.Text

End Sub
</code>```

Now in my User form I have a submit button that should call this routine as stipulated below:

```<code>Private Sub CommandButton1_Click()

Call Module1.Daily_Proto_1

End Sub
</code>```

The reason for this is so that I can include this in another button, but will have some additional instructions.
When I run the code under the Private Sub CommandButton1_Click() it runs perfectly, however when i move it to the Public Procedure, it gives me the following error:

When I click on debug it takes me to the first line

Can anyone tell me what I am doing wrong here please

答:
Add a name of your userform prior to TextBox1. For instance

```<code> ws.Range("A" & LastRow).Value = UserForm1.TextBox1.Text
</code>```

Or rather use

```<code>with UserForm1

end with
</code>```

and dots beforre control names.

Body:
Hi there Stuck with a CALL problem

I created a subroutine called Daily_Proto_1
It copies data from the user form to my worksheet : This is the code:

Public Sub Daily_Proto_1()
Dim LastRow As Long, ws As Worksheet

    Set ws = Sheets("DailyRep")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row

'Adds the TextBox1 into Col A & Last Blank Row
'Adds the TextBox2 into Col B & Last Blank Row
'Adds the ComboBox1 into Col C & Last Blank Row
'Ect.

    ws.Range("A" & LastRow).Value = TextBox1.Text
    ws.Range("B" & LastRow).Value = TextBox2.Text
    ws.Range("C" & LastRow).Value = ComboBox1.Text
    ws.Range("D" & LastRow).Value = TextBox3.Text
    ws.Range("E" & LastRow).Value = ComboBox2.Text
    ws.Range("F" & LastRow).Value = ComboBox3.Text

End Sub

Now in my User form I have a submit button that should call this routine as stipulated below:

Private Sub CommandButton1_Click()

Call Module1.Daily_Proto_1

End Sub

The reason for this is so that I can include this in another button, but will have some additional instructions.
When I run the code under the Private Sub CommandButton1_Click() it runs perfectly, however when i move it to the Public Procedure, it gives me the following error:

When I click on debug it takes me to the first line

Can anyone tell me what I am doing wrong here please

Body:
Add a name of your userform prior to TextBox1. For instance

 ws.Range("A" & LastRow).Value = UserForm1.TextBox1.Text

Or rather use

with UserForm1

end with

and dots beforre control names.


答:
```<code>$('<li/>')
    .append($('<div/>', {
        'class': 'img-w js-popup',
    }))
    .append($('<div/>', {
        'id': 'idOFDiv'
    }))
    .append($('<a/>', {
        href: 'delete.php',
    text: 'Delete'
    }))
    .appendTo('ul');

 $("#idOFDiv").append($('<img/>', {
        'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
    }));
</code>```

Title: JQuery How to create element in created element


问:
How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting
I am getting this error while running server, how do I fix this?

答: I am on Mac OS Sierra. I had to update /etc/paths and add /Users/my.username/.rbenv/shims to the top of the list.


问:
Wordpress session management
I'm putting up a site using Wordpress and I'd like to piggyback on its sessions. But I'm not finding any plugins, or even documentation. Any suggestions or references before I start hacking it?

Note: I'm asking about if and how WP uses standard PHP sessions itself, not how to add PHP sessions e.g. using session_start(). Apparently any state WP maintains is accomplished by other means. So if I want to use PHP sessions I need to add and maintain it myself entirely, using techniques like those in the thread.

Thanks all!

答:
It's a very bad idea to modify WP Core files for the ability to use sessions. The best way I've found is to call the session_start() from init action hook.

```<code>function kana_init_session() {
  session_start();
}

add_action('init', 'kana_init_session', 1);
</code>```

You can place it in functions.php file of your theme.

Detailed article can be found here: http://www.kanasolution.com/2011/01/session-variable-in-wordpress/

Title: Wordpress session management

Body:
It's a very bad idea to modify WP Core files for the ability to use sessions. The best way I've found is to call the session_start() from init action hook.

function kana_init_session() {
  session_start();
}

add_action('init', 'kana_init_session', 1);

You can place it in functions.php file of your theme.

Detailed article can be found here: http://www.kanasolution.com/2011/01/session-variable-in-wordpress/


问:
localhost and "stream_socket_enable_crypto(): SSL operation failed with code 1"
I was sending emails using gmail and everything was working perfectly, but suddendly it stoped working. And it shows me this

```<code>ErrorException in StreamBuffer.php line 94:

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

in StreamBuffer.php line 94
at HandleExceptions->handleError('2', 'stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed', 'C:\xampp\htdocs\coparmex\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php', '94', array())
at stream_socket_enable_crypto(resource, true, '9') in StreamBuffer.php line 94
at Swift_Transport_StreamBuffer->startTLS() in EsmtpTransport.php line 313
at Swift_Transport_EsmtpTransport->_doHeloCommand() in AbstractSmtpTransport.php line 118
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 385
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 171
</code>```

And this only happends in my localhost, in the web host works fine. I don't understand what is going on :c

These are my gmail settings

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=gmail
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
</code>```

答:
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint (such as GitHub or some other remote Git host), and you'll be vulnerable to a Man-in-the-Middle Attack. Be sure you fully understand the security issues before using this as a solution.

You should add below code in /config/mail.php ( worked on laravel 5.4 )

```<code>'stream' => [
'ssl' => [
    'allow_self_signed' => true,
    'verify_peer' => false,
    'verify_peer_name' => false,
],
],
</code>```

as you should never change code in vendors as suggested by Sultan Ahmad

Body:
I was sending emails using gmail and everything was working perfectly, but suddendly it stoped working. And it shows me this

ErrorException in StreamBuffer.php line 94:

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

in StreamBuffer.php line 94
at HandleExceptions->handleError('2', 'stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed', 'C:\xampp\htdocs\coparmex\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php', '94', array())
at stream_socket_enable_crypto(resource, true, '9') in StreamBuffer.php line 94
at Swift_Transport_StreamBuffer->startTLS() in EsmtpTransport.php line 313
at Swift_Transport_EsmtpTransport->_doHeloCommand() in AbstractSmtpTransport.php line 118
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 385
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 171

And this only happends in my localhost, in the web host works fine. I don't understand what is going on :c

These are my gmail settings

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=gmail
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

Body:
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint (such as GitHub or some other remote Git host), and you'll be vulnerable to a Man-in-the-Middle Attack. Be sure you fully understand the security issues before using this as a solution.

You should add below code in /config/mail.php ( worked on laravel 5.4 )

'stream' => [
'ssl' => [
    'allow_self_signed' => true,
    'verify_peer' => false,
    'verify_peer_name' => false,
],
],

as you should never change code in vendors as suggested by Sultan Ahmad

OwnerDisplayName: anon

ContentLicense: CC BY-SA 4.0


问:
Non-Prime Number Counter in C
I want to write a program for storing all the non-prime(composite) numbers before 10.000 in an array. I did this algorithm below, but it's not working. When I print out the array which is supposed to be holding composite numbers, it's simply counting from 4 to 10.000 .

Where is the problem? I really looked so much but I can't see.

```<code>#include <stdio.h>
#define SIZE 10000

void compositeChecker(int[]);

int main() {
    int k;
    int compositeArray[SIZE]= {0};
    compositeChecker(compositeArray);
    for(k=0; k<100; k++) {
        printf("%d\n",compositeArray[k]);
    }
}

void compositeChecker(int arr[]) {
    int i,j,counter=0;

    for(i=4; i<10000; i++) {
        for(j=2; j<i; j++) {
            if((i%j)==0) {
                counter++;
            }
        }
        if(counter!=0) {
            arr[i-4]=i;
        }
    }
}
</code>```

答:
Composite numbers is non-prime numbers greater than 1. So all you have to do is to find prime number up to 10k. It can easily be done by erythrophene sieve.

The principle of the sieve of Eratosthenes

Create array which maps numbers to {1, 0}, 1 - if number is prime, 0 - if composite.

```<code>#define SIZE 10001
int is_prime[10000];
</code>```

Now let's initialize sieve:

```<code>void init_sieve()
{
    int i, j;
    for( i = 0; i < SIZE; ++i )
        is_prime[i] = 1;

    is_prime[0] = is_prime[1] = 0;

    for( i = 2; i < SIZE; ++i )
        if( is_prime[i] )
            for( j = i*i; j < SIZE; j += i )
                is_prime[j] = 0;
}
</code>```

So we got bool array, each element of which is 1 if element's index is prime, 0 otherwise.
Now, we can simple iterate throw it and get composite numbers.

```<code>for( int i = 4; i < SIZE; ++i )
    if( !is_prime[i] )
    {
        printf( "%d\n", i );
    }
</code>```

First 10 number from stdout:
    4
    6
    8
    9
    10
    12
    14
    15
    16
    18
    20
    21
    22
    24
    25
    26
    27
    ...

Title: Non-Prime Number Counter in C

Body:
I want to write a program for storing all the non-prime(composite) numbers before 10.000 in an array. I did this algorithm below, but it's not working. When I print out the array which is supposed to be holding composite numbers, it's simply counting from 4 to 10.000 .

Where is the problem? I really looked so much but I can't see.

#include <stdio.h>
#define SIZE 10000

void compositeChecker(int[]);

int main() {
    int k;
    int compositeArray[SIZE]= {0};
    compositeChecker(compositeArray);
    for(k=0; k<100; k++) {
        printf("%d\n",compositeArray[k]);
    }
}

void compositeChecker(int arr[]) {
    int i,j,counter=0;

    for(i=4; i<10000; i++) {
        for(j=2; j<i; j++) {
            if((i%j)==0) {
                counter++;
            }
        }
        if(counter!=0) {
            arr[i-4]=i;
        }
    }
}

Body:
Composite numbers is non-prime numbers greater than 1. So all you have to do is to find prime number up to 10k. It can easily be done by erythrophene sieve.

The principle of the sieve of Eratosthenes

Create array which maps numbers to {1, 0}, 1 - if number is prime, 0 - if composite.

#define SIZE 10001
int is_prime[10000];

Now let's initialize sieve:

void init_sieve()
{
    int i, j;
    for( i = 0; i < SIZE; ++i )
        is_prime[i] = 1;

    is_prime[0] = is_prime[1] = 0;

    for( i = 2; i < SIZE; ++i )
        if( is_prime[i] )
            for( j = i*i; j < SIZE; j += i )
                is_prime[j] = 0;
}

So we got bool array, each element of which is 1 if element's index is prime, 0 otherwise.
Now, we can simple iterate throw it and get composite numbers.

for( int i = 4; i < SIZE; ++i )
    if( !is_prime[i] )
    {
        printf( "%d\n", i );
    }

First 10 number from stdout:
    4
    6
    8
    9
    10
    12
    14
    15
    16
    18
    20
    21
    22
    24
    25
    26
    27
    ...


答:
I think you may need to stipulate the name of your userform before textbox1.text.

```<code>ws.Range("A" & LastRow).Value = UserForm1.textbox1.text
</code>```

(replace Userform1 with the name of your userform)

Title: VBA Excel : Subroutine work but if called, It no longer works

Body:
I think you may need to stipulate the name of your userform before textbox1.text.

ws.Range("A" & LastRow).Value = UserForm1.textbox1.text

(replace Userform1 with the name of your userform)


问:
convert 3 columns data frame to matrix
I have the following input:

```<code>A   B   0
A   C   1
B   C   1
</code>```

Which I would like to convert to a 3x3 matrix:

```<code>    A   B   C
A   0   0   1
B   0   0   1
C   1   1   0
</code>```

How should I do this in R? The above is just to give an idea of what I aim to do. Below is my data. I cut this down to 15 obs but my dataset has 500 and the ticker set are the same for ticker1 and ticker2. Thus I would want an n x n matrix.

```<code>ticker1 ticker2 edge
AEPI    AVAV    0.044210322
AEPI    BOKF    0.008021954
AEPI    CMSB    0.001986887
AEPI    RON     0.006777085
AEPI    CAKE    0.045002911
APPL    COH     0.042760407
APPL    SWZA    0.040913242
APPL    DRIV    0.047699102
APPL    CXP     0.014103206
MSCR    FIVN    0.008781475
MSCR    HOS     0.040222645
MSCR    HDSN    0.010454853
MSCR    IPWR    0.003376232
MSCR    KELYB   0.000755429
</code>```

答:
We can use base R methods.  If the first two columns are not factor class, convert it to factor with levels specified so that both the columns have the same levels.  Then use xtabs to convert it to 'wide' format and change the values in the lower half by adding with the transpose of the 'm1'

```<code>df1[1:2] <- lapply(df1[1:2], factor, levels = LETTERS[1:3])
m1 <- xtabs(v3~v1 + v2, df1)
names(dimnames(m1)) <- NULL
m1 + t(m1)
#  A B C
#A 0 0 1
#B 0 0 1
#C 1 1 0
</code>```

data

```<code>df1 <- structure(list(v1 = c("A", "A", "B"), v2 = c("B", "C", "C"),
v3 = c(0L, 1L, 1L)), .Names = c("v1", "v2", "v3"), class = "data.frame",
 row.names = c(NA, -3L))
</code>```

Title: convert 3 columns data frame to matrix

Body:
I have the following input:

A   B   0
A   C   1
B   C   1

Which I would like to convert to a 3x3 matrix:

    A   B   C
A   0   0   1
B   0   0   1
C   1   1   0

How should I do this in R? The above is just to give an idea of what I aim to do. Below is my data. I cut this down to 15 obs but my dataset has 500 and the ticker set are the same for ticker1 and ticker2. Thus I would want an n x n matrix.

ticker1 ticker2 edge
AEPI    AVAV    0.044210322
AEPI    BOKF    0.008021954
AEPI    CMSB    0.001986887
AEPI    RON     0.006777085
AEPI    CAKE    0.045002911
APPL    COH     0.042760407
APPL    SWZA    0.040913242
APPL    DRIV    0.047699102
APPL    CXP     0.014103206
MSCR    FIVN    0.008781475
MSCR    HOS     0.040222645
MSCR    HDSN    0.010454853
MSCR    IPWR    0.003376232
MSCR    KELYB   0.000755429

Body:
We can use base R methods.  If the first two columns are not factor class, convert it to factor with levels specified so that both the columns have the same levels.  Then use xtabs to convert it to 'wide' format and change the values in the lower half by adding with the transpose of the 'm1'

df1[1:2] <- lapply(df1[1:2], factor, levels = LETTERS[1:3])
m1 <- xtabs(v3~v1 + v2, df1)
names(dimnames(m1)) <- NULL
m1 + t(m1)
#  A B C
#A 0 0 1
#B 0 0 1
#C 1 1 0

data

df1 <- structure(list(v1 = c("A", "A", "B"), v2 = c("B", "C", "C"),
v3 = c(0L, 1L, 1L)), .Names = c("v1", "v2", "v3"), class = "data.frame",
 row.names = c(NA, -3L))


问:
UI-Test with XCTest: how to trigger App-State Foreground-Inactive Foreground-Active
How can I trigger the following behavior in Swift UI Tests via XCTest:

Get the app to foreground and inactive (applicationWillResignActive) and back to "foreground and active" (applicationDidBecomeActive)

Possible gestures, while app is in foreground and active, could be:

open app switcher and go back to app

open control center and hide control center

open notification center and hide notification center

I searched for something like that following fictive(!) code XCUIDevice.shared.doublePress(XCUIDevice.Button.home) or XCUIDevice.shared.swipeDownFromOutside(); XCUIDevice.shared.swipeUpFromOutside().

Or a more better way a method call to simulate an open app switcher, control center or notification center immediately.

Or in the best way to simulate the status applicationWillResignActive, applicationDidBecomeActive immediately.

Important to understand: the event applicationDidEnterBackground must not called - the app has to stay in foreground (but inactive)!

答:
So recently on wwdc2017 Apple released a convenient way to work with multi app. You can see the multi App portion of the video link below.</p>

```<code>https://developer.apple.com/videos/play/wwdc2017/409/
</code>```

Body:
So recently on wwdc2017 Apple released a convenient way to work with multi app. You can see the multi App portion of the video link below.

https://developer.apple.com/videos/play/wwdc2017/409/


问:
jquery only firing on second click
i have a dropdown box that when i click it the arrow rotates.how ever the arrow only rotates on the second click.what am i doing wrong?

```<code><div class="dropdown">
 <a onclick="UserdropDownDetails()"><div class="triangle1"></div></a>
  <div id="myDropdown" class="dropdown-content ">
    <ul>
     // drop down elements
    </ul>
  </div>
</div>
</code>```

css

```<code>.triangle1 {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s ease;
}

.triangle-up {
    transform: rotate(180deg);
}
</code>```

code:

```<code>function flipTriangle() {
                $('.triangle1').on('click', function () {
                    $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
                });
            }

function UserdropDownDetails() {
            flipTriangle(); i need this to fire the first time its clicked
            document.getElementById("myDropdown").classList.toggle("show"); //this shows my drop down,which works fine.

        }
</code>```

what am i doing wrong?

答:
You are binding event handler in the function flipTriangle so the event is attached on first click thus it works on second click.

Move the code outside the function.

```<code>$(function () {
    $('.triangle1').on('click', function () {
        $(this).toggleClass("triangle-up"); //this flips my image but its only working if i click it twice.
    });
});
</code>```

Title: jquery only firing on second click

Body:
i have a dropdown box that when i click it the arrow rotates.how ever the arrow only rotates on the second click.what am i doing wrong?

     // drop down elements

css

.triangle1 {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s ease;
}

.triangle-up {
    transform: rotate(180deg);
}

code:

function flipTriangle() {
                $('.triangle1').on('click', function () {
                    $(this).toggleClass("triangle-up");  //this flips my image but its only working if i click it twice.
                });
            }

function UserdropDownDetails() {
            flipTriangle(); i need this to fire the first time its clicked
            document.getElementById("myDropdown").classList.toggle("show"); //this shows my drop down,which works fine.

        }

what am i doing wrong?

Body:
You are binding event handler in the function flipTriangle so the event is attached on first click thus it works on second click.

Move the code outside the function.

$(function () {
    $('.triangle1').on('click', function () {
        $(this).toggleClass("triangle-up"); //this flips my image but its only working if i click it twice.
    });
});


问:
What to choose to store just one integer? Sqlite? or Text file?
I've build a small web-service in PHP. I want to control the number of calls to a specific API method.

I thought at first of using a text file, because it's just an integer. But after taking a good look at SQLite it seemed much more convenient.
So the code is just: get the "counter" from SQLite and increment it when that method is called, then store it back on SQLite db.

Is this a right way of doing it? Would it be simpler and more scalable to just use a file or... maybe something else?

Thanks in advance.

答:
Of course use flat file.

It will be right thing to do

Extremely simple

No dependency on third-party library

You will be able to view or update counter with just plain Notepad.

Faster than SQLite (no SQL parsing, no other overhead)

and as scalable as SQLite (SQLite are just more complex flat files)

If you will ever need something as fast as possible, you will have to make persistent process in memory to eliminate I/O bottleneck. But please... just don't use SQL database to store single integer.

OwnerDisplayName: rogeriopvl

OwnerDisplayName: lubos hasko

LastEditorDisplayName: lubos hasko


问:
How to get the value of Html.Kendo().DatePicker() on change event?
I have a Html.Kendo DatePicker.  When I change the date and submitting without losing the focus for the input date, I don't have the correct date that I've selected.</p>

答: What does "submitting without losing the focus" mean.  If you are submitting anything back to the server, you have to ensure that the date is making it to the action method in a correct format, and then is being sent back down once the view loads again correctly...</p>


问:
Intellij Idea - can't run a simple java class even though the main method is declared
I'm a self-taught coder who is new to both Java & Intellij Idea. I wanted to run a simple Java class called payroll in Intellij Idea Ultimate 2017.3

```<code>public class payroll {
  public static void main(String[] args) {
    int hours = 50;
    double grossPay, payRate = 25.0;

    grossPay = hours * payRate;
    System.out.println("your gross pay is $" + grossPay);}
  }
</code>```

Unfortunately IDEA detects some errors indicating that it can't resolve symbols "String" and "System". And when I tried Run/Edit Configuration, the IDE stated that the main method isn't found in the class, but obviously it is declared already

I've used Eclipse & Netbeans before and things just went smoothly then. Can anyone please point out the main cause of this nuisance for me and how to work it out?

答:
The class name you should name with Camel-case. That is first.
Second. You need to import package for System</p>

Body:
I'm a self-taught coder who is new to both Java & Intellij Idea. I wanted to run a simple Java class called payroll in Intellij Idea Ultimate 2017.3

public class payroll {
  public static void main(String[] args) {
    int hours = 50;
    double grossPay, payRate = 25.0;

    grossPay = hours * payRate;
    System.out.println("your gross pay is $" + grossPay);}
  }

Unfortunately IDEA detects some errors indicating that it can't resolve symbols "String" and "System". And when I tried Run/Edit Configuration, the IDE stated that the main method isn't found in the class, but obviously it is declared already

I've used Eclipse & Netbeans before and things just went smoothly then. Can anyone please point out the main cause of this nuisance for me and how to work it out?


问:
HTTP get requests in ajax
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.

Javascript code:

```<code> $(document).ready(function () {
    $("#LoginUser").click(function () {
        $.ajax({
            url: 'http://website/api/user/Mikkel1337',
            dataType: 'json',
            type: 'GET',
            contentType: 'application/json',

            error: function () {
                alert("An error had occurred");
            },
            success: function (data) {
                var jsonStr = JSON.stringify(data);

                alert(jsonStr['password']);
            }
        });
    });
})
</code>```

The response JSON code looks like this:

```<code>{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn@mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
</code>```

When im running this I only get the error function. Any suggestions or solution is appreciated :)

答:
dont need to JSON.stringify of data simple use

```<code>$(document).ready(function () {
$("#LoginUser").click(function () {
    $.ajax({
        url: 'http://website/api/user/Mikkel1337',
        dataType: 'json',
        type: 'GET',
        contentType: 'application/json',

        error: function () {
            alert("An error had occurred");
        },
        success: function (data) {

            alert(data.password);
        }
    });
});
</code>```

})

Title: HTTP get requests in ajax

Body:
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.

Javascript code:

 $(document).ready(function () {
    $("#LoginUser").click(function () {
        $.ajax({
            url: 'http://website/api/user/Mikkel1337',
            dataType: 'json',
            type: 'GET',
            contentType: 'application/json',

            error: function () {
                alert("An error had occurred");
            },
            success: function (data) {
                var jsonStr = JSON.stringify(data);

                alert(jsonStr['password']);
            }
        });
    });
})

The response JSON code looks like this:

{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn@mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}

When im running this I only get the error function. Any suggestions or solution is appreciated :)

Body:
dont need to JSON.stringify of data simple use

$(document).ready(function () {
$("#LoginUser").click(function () {
    $.ajax({
        url: 'http://website/api/user/Mikkel1337',
        dataType: 'json',
        type: 'GET',
        contentType: 'application/json',

        error: function () {
            alert("An error had occurred");
        },
        success: function (data) {

            alert(data.password);
        }
    });
});

})


问:
mySQL time sum php now() in laravel seed
I have an expires_at column in mysql table. I want to fill this table using Laravel Seeding. Also i have "life_time" column in another table.

For example;

if the "life_time" is 00:05:00, my expires_at should be NOW() + 00:05:00...

expires_at is timestamp but life_time is only time. How can i create an expires_at using Carbon::now() + life_time or any time method which is showing current date.

Actually, i am trying to "A user send an image to other user using my cloud. This image has an expire date which is, if the other user does not download image from my cloud in life_time, i will delete." ... So i created a life time each file types. 5 min for images, 10 min for videos etc. I know send date and life time so i need to create expire date.

答:
The simplest solution is to keep life_time in minutes like most of systems do and use Carbon to create expires_at:

```<code>Carbon::now()->addMinutes($lifeTime)
</code>```

Body:
The simplest solution is to keep life_time in minutes like most of systems do and use Carbon to create expires_at:

Carbon::now()->addMinutes($lifeTime)


问:
Contenteditable not working with contententeditable span inside set to false
I have a problem with the contenteditable div which I have replicated in jsfiddle. The problem is when I click in between the contenteditable div and hit backspace all the span tag inside the div is deleted. I tried it the same in the fiddle but it works normal. But when I place the cursor at the end it is deleting the span one by one.

This works

```<code><div contenteditable="true">
<span contenteditable="false">value1</span>
<span contenteditable="false">value2</span>
<span contenteditable="false">value3</span>
<span contenteditable="false">value4</span>
<span contenteditable="false">value5</span>
<span contenteditable="false">value6</span>
</div>
<br/>
</code>```

and this is not

```<code><div contenteditable="true" id="formulaBox"  role="button" tabindex="0">
<span style="color: red;" contenteditable="false">SUM</span>
<span style="color: black;" contenteditable="false">(</span>
<span style="color: rgb(0, 126, 255);" contenteditable="false">value1</span><span style="color: black;" contenteditable="false">+</span>
<span style="color: rgb(0, 126, 255);" contenteditable="false">value2</span><span style="color: black;" contenteditable="false">+</span>
<span style="color: rgb(0, 126, 255);" contenteditable="false">value3</span><span style="color: black;" contenteditable="false">*</span>
<span style="color: rgb(0, 126, 255);" contenteditable="false">value4</span><span style="color: black;" contenteditable="false">)</span>
<span style="color: black;" contenteditable="false">/</span>
<span style="color: blue;" contenteditable="false">AVG</span>
<span style="color: black;" contenteditable="false">(</span>
<span style="color: rgb(0, 126, 255);" contenteditable="false">value5</span><span style="color: black;" contenteditable="false">)</span>
</div>
</code>```

Refer the below link
https://jsfiddle.net/9ruwpyv5/

The 1st div is replicated and the second is the actual code.

答:
I found it. I just added a space in between all the span tag and it solved the issue. </p>

```<code>$('#formulaBox span').before(" ");
</code>```

Body:
I have a problem with the contenteditable div which I have replicated in jsfiddle. The problem is when I click in between the contenteditable div and hit backspace all the span tag inside the div is deleted. I tried it the same in the fiddle but it works normal. But when I place the cursor at the end it is deleting the span one by one.

This works

value1
value2
value3
value4
value5
value6

and this is not

SUM
(
value1+
value2+
value3*
value4)
/
AVG
(
value5)

Refer the below link
https://jsfiddle.net/9ruwpyv5/

The 1st div is replicated and the second is the actual code.

Body:
I found it. I just added a space in between all the span tag and it solved the issue.

$('#formulaBox span').before(" ");


问:
regex to ignore lines with specific symbol
I'm trying to get a regex to set change relative paths to absolute with an alias, and ignore any lines with alias already indicated with the @ symbol to prevent folder/file name matches.  I've got as far as the replace and match , but I can't do the ignore lines with @ bit.  I would also like it to match  the /foldername/ forward slashes either side when selecting.

https://regex101.com/r/vRUegE/1/

I would have expected the lines with @ to be ignored

Here is the correct response thanks to Wiktor:

Working example

Using a combination of WinGrep and these regex's it was easy to refactor hundreds of paths in hundreds of files in minutes!

答:
difficult to say in which language you do it, seem java , regexp is bit different for different languages .

```<code>(?<=from..)(.*)(?=module)(.*(module)/g
</code>```

here you refer (.*) - e.q. any repeat chars , you need to change to

```<code>([^\@]*)  ( or ([^@]*)   )
</code>```

e.q. any non @ char

Body:
difficult to say in which language you do it, seem java , regexp is bit different for different languages .

(?<=from..)(.*)(?=module)(.*(module)/g

here you refer (.*) - e.q. any repeat chars , you need to change to

([^\@]*)  ( or ([^@]*)   )

e.q. any non @ char