问:
passing values from javascript to jsp using jquery
I have a jsp page that submits a form asynchronously using jQuery.ajax(). After successful submission the server returns a json object .
Now what I need to do is open a dialog box and display the values in the columns in a table.

I have a div in my jsp representing my dialog box. Now What I am not able to achieve over here is  that I am not able to somehow set these column values from the javascript.

I tried adding a hidden variable in the jsp for each column and then setting this variable in the js but it didn't work.

```<code>jquery("#data").val("test")
</code>```

my html code

Success!!: val

val1

val2Ticket Created:

Now over here I need to populate the table column values and the values after success! with the json object that i retrieve from the json object returned by the ajax request. I have verified that the data is correctly retrieved.
Any solutions would be highly appreciated.

答:
I'm not using json objects as such but here is how I do a partial postback in jsp.

JavaScript

```<code>var data = {"Ns":Ns, queryString: $('#hdnQueryString').val()};
var success = successSelectSortOrder;
var errorFunction = genericError;
genericPostback("post", hostPath + "ctrlSort.jsp", data,success,errorFunction);

function genericPostback(postbackType,url, data,success,errFunction)
        {
            $.ajax(
                {

                    type : "post",
                    url  : url,
                    data : data,
                    success:success,
                    error :errFunction
                }
            )
        }

        function successSelectSortOrder(msg)
        {
          //do something with the msg here.
          //generally i have returned html and if not then xml
          //i use jquery to pull it apart from here
        }
</code>```

Then my jsp page;

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<%
    out.print("My returned html or data here");
%>
</code>```

Body:
I have a jsp page that submits a form asynchronously using jQuery.ajax(). After successful submission the server returns a json object .
Now what I need to do is open a dialog box and display the values in the columns in a table.

I have a div in my jsp representing my dialog box. Now What I am not able to achieve over here is  that I am not able to somehow set these column values from the javascript.

I tried adding a hidden variable in the jsp for each column and then setting this variable in the js but it didn't work.

jquery("#data").val("test")

my html code

Success!!: val

val1

val2Ticket Created:

Now over here I need to populate the table column values and the values after success! with the json object that i retrieve from the json object returned by the ajax request. I have verified that the data is correctly retrieved.
Any solutions would be highly appreciated.

Body:
I'm not using json objects as such but here is how I do a partial postback in jsp.

JavaScript

var data = {"Ns":Ns, queryString: $('#hdnQueryString').val()};
var success = successSelectSortOrder;
var errorFunction = genericError;
genericPostback("post", hostPath + "ctrlSort.jsp", data,success,errorFunction);

function genericPostback(postbackType,url, data,success,errFunction)
        {
            $.ajax(
                {

                    type : "post",
                    url  : url,
                    data : data,
                    success:success,
                    error :errFunction
                }
            )
        }

        function successSelectSortOrder(msg)
        {
          //do something with the msg here.
          //generally i have returned html and if not then xml
          //i use jquery to pull it apart from here
        }

Then my jsp page;

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%
    out.print("My returned html or data here");
%>


来源: stackexchange

问:
Creating Dataframe from list of Dictionaries, without using pd.concat()
I have data structures that are dictionaries of numpy arrays, and look something like this:

```<code>metric_one =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

metric_two =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}
</code>```

With the following labels:

```<code>['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
</code>```

I'd like to have a dataframe that looks like this:

```<code>   0  1  2  3
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9
</code>```

I can do that by converting each of the dictionaries into dataframes and then concatenating them with pd.concat(). However, that is really slow, especially when the dicionaries to concatenate grow (I need to concatenate about 20 of them). From profiling, it seems that creating the single dataframes before concatenating is actually taking the majority of the time. Therefore I was wondering if there was a better way of doing this, for instance rearranging the dictionaries in a smart way into a big data structure that contains all the dictionaries (maybe in a list? maybe in a big dicionary?) so that we can build only one dataframe by passing this big data structure into the constructor.

Thanks!

答:
Assuming

```<code>metrics = [metric_one, metric_two]
idx = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
</code>```

Using just numpy

```<code>lol = [list(np.concatenate([m[i] for m in metrics])) for i in range(4)]
np.array(lol).T
pd.DataFrame(np.array(lol).T, idx * len(metrics))
</code>```

naive time test

ContentLicense: CC BY-SA 3.0

Body:
I have data structures that are dictionaries of numpy arrays, and look something like this:

metric_one =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

metric_two =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

With the following labels:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

I'd like to have a dataframe that looks like this:

   0  1  2  3
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9

I can do that by converting each of the dictionaries into dataframes and then concatenating them with pd.concat(). However, that is really slow, especially when the dicionaries to concatenate grow (I need to concatenate about 20 of them). From profiling, it seems that creating the single dataframes before concatenating is actually taking the majority of the time. Therefore I was wondering if there was a better way of doing this, for instance rearranging the dictionaries in a smart way into a big data structure that contains all the dictionaries (maybe in a list? maybe in a big dicionary?) so that we can build only one dataframe by passing this big data structure into the constructor.

Thanks!

Body:
Assuming

metrics = [metric_one, metric_two]
idx = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Using just numpy

lol = [list(np.concatenate([m[i] for m in metrics])) for i in range(4)]
np.array(lol).T
pd.DataFrame(np.array(lol).T, idx * len(metrics))

naive time test


问:
How does a Symfony pass parameters into a yaml config?
A Symfony Config component allows to create and load a configuration. For instance, it allows to use a yml for config.

However, in a Symfony framework configuration uses parameters with a special syntax - %parameter.key%

I've looked at Symfony YamlFileLoader but it only load a content of a yaml-file and handle such sections as imports, parameters and services. The only goal of the parameters is to be stored in a container parameter bag.

So I'm wondering what's magic used to replace placeholders in a yaml config file?

Moreover. I've tried to load a config:

```<code>application:
    aBooleanKey: "true"
</code>```

and I've got an error since aBooleanKey requires a boolean value but got a string.

答:
Bundles can define what kind of configuration they expect, including required values and restricting types. This is usually done in the bundle's DependencyInjection/Configuration.php. Here's a link to the configuration for FOSUserBundle: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/DependencyInjection/Configuration.php

The TreeBuilder defines the structure and the configuration created from parsing the yaml (or other config format's) file is passed in and validated against the requirements. You can also check the Symfony docs on Defining and Processing Configuration Values

Body:
A Symfony Config component allows to create and load a configuration. For instance, it allows to use a yml for config.

However, in a Symfony framework configuration uses parameters with a special syntax - %parameter.key%

I've looked at Symfony YamlFileLoader but it only load a content of a yaml-file and handle such sections as imports, parameters and services. The only goal of the parameters is to be stored in a container parameter bag.

So I'm wondering what's magic used to replace placeholders in a yaml config file?

Moreover. I've tried to load a config:

application:
    aBooleanKey: "true"

and I've got an error since aBooleanKey requires a boolean value but got a string.


问:
Need help in JavaScript , openWindow ();
I am trying to run the following JavaScript program,

function myFunction() {
  var x;
  if (confirm("Press a button!") == true) {
    x = "You pressed Ok!";
  } else {
    x = "You pressed Cancel!";
  }
  document.getElementById("demo").innerHTML = x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p></code>```

But I really need is not just saying "You pressed Ok" instead of that it need to open a link. Help me please.

I hope

```<code>openWindow("http://fb.com")
</code>```

this line will help, but don't know where to place it and make a working program.

答:
function myFunction() {
var x;
if (confirm("Press a button!") == true) {

location.href = "http://www.google.com";

} else {

x = "You pressed Cancel!";

}
document.getElementById("demo").innerHTML = x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click the button to display a confirm box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p></code>```

Body:
I am trying to run the following JavaScript program,

function myFunction() {
  var x;
  if (confirm("Press a button!") == true) {
    x = "You pressed Ok!";
  } else {
    x = "You pressed Cancel!";
  }
  document.getElementById("demo").innerHTML = x;
}

Click the button to display a confirm box.

<button onclick="myFunction()">Try it</button>

But I really need is not just saying "You pressed Ok" instead of that it need to open a link. Help me please.

I hope

openWindow("http://fb.com")

this line will help, but don't know where to place it and make a working program.

Body:
function myFunction() {
var x;
if (confirm("Press a button!") == true) {

location.href = "http://www.google.com";

} else {

x = "You pressed Cancel!";

}
document.getElementById("demo").innerHTML = x;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click the button to display a confirm box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


问:
Multiple WP installations using 1 database
I have three different URLS on the same server that need to share one WordPress 3.0.1 DB. I want to be able to add a new post from one main WP and the changes show up on the other two sites.

Is the change in config file (db table) enough?

答:
First of all, I think you're confusing multisite and multiple Wordpress installs with one database.

Three Wordpress installs can pull from the same database. (But not "table", as you first said and I edited.) Multiple installs can work from the same database by using different table prefixes so each install doesn't collide with the other or get overwritten when the 2nd, 3rd, etc., installs get made. See Installing Multiple Blogs « WordPress Codex

But you're asking for trouble by trying to use three different URLs unless you go Multisite and share content in a different way.

What you should do is either use three Wordpress installs with three different table prefixes on one database with WordPress › FeedWordPress « WordPress Plugins to duplicate the content.

Or, Wordpress Multisite with three folders under one WP admin (requires a VPS with access to httpd) and WordPress › WordPress MU Sitewide Tags Pages « WordPress Plugins.

Or, Wordpress Multisite with three domains under one WP admin (requires a VPS with access to httpd and DNS changes for the separate domain mapping) with WordPress › WordPress MU Domain Mapping « WordPress Plugins and WordPress › FeedWordPress « WordPress Plugins to duplicate the content.

Be aware that duplicate content will also get your SEO penalized.

And, is this question so you can bid on this Elance job?: Have three URLS that need to share the same WP DB | Elance Job

ContentLicense: CC BY-SA 2.5


问:
Returning data resolved by XMLHttpRequest with module pattern function
I have problem combining javascript callbacks and revealing module pattern.
What I'm trying to do is to return the HTTP response text with the carsData.getCars() function method.

Basically what I want to do is:

return the data from xhr.onreadystatechange function to the private getData function

return the data from getData function to the public getCars function ( or call the getCars function returning a value)

I got it to work with the synchronous AJAX mode, but I'm aware it's not the best practice in javascript development.

I tried to get it to work with callbacks but failed miserably.
Is it even posible to do in javascript?

P.S. I use XMLHttpRequest in Vanilla JS instead of other frameworks for learning purposes.

```<code>'use strict';
var carsData = (function() {
    var carsElement = document.getElementById('carsListing'),
        successHandler = function(data) {
            carsElement.innerHTML = data.data;
            //return data;
        },
        dataWrapper = "",
        getData = function(callback) {
            var url = 'data/cars.json',
                xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {
                var status;
                var data;

                if (xhr.readyState == 4) { // `DONE`
                    status = xhr.status;
                    if (status == 200) {
                        data = JSON.parse(xhr.responseText);
                        successHandler && successHandler(data);
                        callback(data);
                        return data;
                    }
                }
            };
            xhr.open('get', url, false); // synchronous js
            xhr.send();
            return xhr.onreadystatechange();
            //return 'xx';
        }

    return {
        getCars: function() {
            return getData(function(data){
              console.log(data); // Object {data: Array[5]}
            })
        }

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

答: No.  You cannot do it this way.  I figured out that is why you typically see results sent to a DOM object.  Because they are there waiting for the answer.  Your return statement, as counter-intuitive as it seems (assuming you are coming from non-prototype languages), will have already run.  It seems like it wouldn't but it has because of the async nature you are aware of.  You have to use Promises or you have to have your callback doing something with the data that is "waiting" for the callback data like you did with successdata.

Body:
I have problem combining javascript callbacks and revealing module pattern.
What I'm trying to do is to return the HTTP response text with the carsData.getCars() function method.

Basically what I want to do is:

return the data from xhr.onreadystatechange function to the private getData function

return the data from getData function to the public getCars function ( or call the getCars function returning a value)

I got it to work with the synchronous AJAX mode, but I'm aware it's not the best practice in javascript development.

I tried to get it to work with callbacks but failed miserably.
Is it even posible to do in javascript?

P.S. I use XMLHttpRequest in Vanilla JS instead of other frameworks for learning purposes.

'use strict';
var carsData = (function() {
    var carsElement = document.getElementById('carsListing'),
        successHandler = function(data) {
            carsElement.innerHTML = data.data;
            //return data;
        },
        dataWrapper = "",
        getData = function(callback) {
            var url = 'data/cars.json',
                xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {
                var status;
                var data;

                if (xhr.readyState == 4) { // `DONE`
                    status = xhr.status;
                    if (status == 200) {
                        data = JSON.parse(xhr.responseText);
                        successHandler && successHandler(data);
                        callback(data);
                        return data;
                    }
                }
            };
            xhr.open('get', url, false); // synchronous js
            xhr.send();
            return xhr.onreadystatechange();
            //return 'xx';
        }

    return {
        getCars: function() {
            return getData(function(data){
              console.log(data); // Object {data: Array[5]}
            })
        }

    }
})();


问:
Select from literal values not in table in PostgreSQL?
I have some values in Excel, I copy the values and it look like this:

1
2
3
4

I want to write a query that select from above data that is not present in a table. Somethink like:

```<code>SELECT * FROM [1, 2, 3, 4] as foo where foo IS NOT ( SELECT id from table )
</code>```

Supposing id column have 1,2,4 the query answer will be 3.

Preferably a query that can work in postgres and sql server

Thank you!

答:
```<code>select *
from
    (values (1),(2),(3),(4)) v (id)
    left join
    t using (id)
where t.id is null
</code>```

Body:
I have some values in Excel, I copy the values and it look like this:

1
2
3
4

I want to write a query that select from above data that is not present in a table. Somethink like:

SELECT * FROM [1, 2, 3, 4] as foo where foo IS NOT ( SELECT id from table )

Supposing id column have 1,2,4 the query answer will be 3.

Preferably a query that can work in postgres and sql server

Thank you!


问:
PHP command buttons that run Python script passed through AJAX not working
I am still battling through learning AJAX and various ways to implement.   I have a DIV tag on my website which I’m using AJAX to dynamically update after 5 seconds (timed update is for unrelated reasons) by reloading a status.php file into the DIV tag.

The problem I’m having is when I directly browse the status.php the command buttons work properly, however when I use them through the index.php they do not respond.

I am trying to learn why they fail this way and what I can to make in work in an “ELI5” kind of way.

The command buttons run a Python script which opens/closes the garage door.  The next time the status Python script (at the top of status.php) is run, it'll have the new status of the door and eventually display it in the DIV tags when AJAX updates that part of the page.

When I click the buttons now index.php stays displayed in it, but the DIV tag completely reloads status.php.   When this happens though, the Python script does not appear to get triggered.

I suspect the command buttons need to be run in a more AJAX/Java-ey way instead of through PHP, but I don't even know where to begin.

Oh, one more thing:    I also have a CGI script available (e.h.  http://example.com/cgi-bin/myq-cgi.py?username=user&pass=pass&command=open) which I can also use to open/close the door.   I do NOT use it for the status though because it doesn't include the time/date the status last changed like the full Python script does.  This might be a potential way to better open/close the door.

index.php:

```<code><html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script type="text/javascript">
        $(function(){
            setInterval(function(){
                $.ajax({
                    url: "status.php",
                    type: "POST",
                    dataType: "text",
                    success: function(data){
                        $("#status_div").html('The Garage Door Status is: ' + data);
                    }
                })

            }, 5000);
        });
        </script>
    </head>
    <body>
        Somethign on the web page.  Normally this would be the main website while the DIV tag waits to load.
        <div id="status_div"></div>
    </body>
</html>
</code>```

status.php:

```<code><?php

// Call Python script which gives me the status of my garage door in a text string.
$output = shell_exec('python /home/blah/garage_door/myq-garage.py status');

//I am NOT including lots of parsing of the $output.  Eventually I get the $output trimmed down to the to the $status PHP variable.
$status[1] = "Closed"   //values here can be either 'Closed' or 'Open'

?>

<!-- // Style info for table(s) -->
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:7px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:7px 7px;border-style:solid;border-width:1px;overflow:hidden;wor$
.tg .tg-baqh{text-align:center;vertical-align:top}
.tg .tg-yw4l{vertical-align:center;text-align:left}
</style>

<!-- // HTML table to display garage door status info.  Display the image of the door and door status in left cell, time/date and options in right -->
<center>
<table class="tg">
<tr>
    <th class="tg-baqh">
        <div class="garage_status">
            <?php
                //Stuff unrelated to OP question here.  Dynamically displaying an image based on garage door status.
             ?>
        </div>
    </th>
    <th class="tg-yw4l">
        <?php
            // Command button to open door.
            if (isset($_POST['button_open'])){
                if ($status[1] = "Closed"){
                    shell_exec('python /home/blah/garage_door/myq-garage.py open "Garage Door"');
                }
            }

            // Command button to close door.
                if (isset($_POST['button_close'])){
                    if ($status[1] = "Open"){
                        shell_exec('python /home/blah/garage_door/myq-garage.py close "Garage Door"');
                        echo "<script>alert (\"cmd button works\")</script>";
                    }
                }

        ?>
        <form method="post">
            <p>
                <button name="button_open">Open Door</button>
                <button name="button_close">Close Door</button>
            </p>
        </form>
    </th>
</tr>
</table>
</center>
</code>```

答:
@hassan got me thinking, so I worked on building my command buttons on the index.php so that they're not within the ajax response.

I got them working.  The garage door opens/closes.  The index.php reloads the ajax just quick enough where the user can see the status, for example change from Closed --> Opening --> Open --> Closing --> Closed.   More importantly the page doesn't do an overall reload like the old PHP buttons were causing.

This time I did the button in HTML/javascript instead of using PHP.  Also instead of running the Python script, I'm instead using a different python-based CGI script as I mentioned is available in my OP.

Once this was working in index.php, just for the heck of it, I copied it to the status.php and when it gets loaded with ajax, it still works inside there correctly and will execute!

Here is the javascipt which first was in index.html, but ultimately moved to status.php:

```<code><script>
function open_door() {
    jQuery(function($) {
        $.ajax( {
            url : "http://example.com/cgi-bin/myq-cgi.py?user=somethibng@hotmail.com&pass=dfgsdfgsdfg&cmd=open",
            type : "GET",
            success : function(data) {
                alert ("Opening Door..."); //or use data string to show something else
                }
            });
        });
    }
</script>

<script>
function close_door() {
    jQuery(function($) {
        $.ajax( {
            url : "http://example.com/cgi-bin/myq-cgi.py?user=something@hotmail.com&pass=dfgdfgsdfg&cmd=close",
            type : "GET",
            success : function(data) {
                alert ("Closing Door..."); //or use data string to show something else
                }
            });
        });
    }
</script>

<form>
<input type="button" value="open" onClick="open_door()"
</form><form>
<input type="button" value="close" onClick="close_door()"
</form>
</code>```

Body:
I am still battling through learning AJAX and various ways to implement.   I have a DIV tag on my website which I’m using AJAX to dynamically update after 5 seconds (timed update is for unrelated reasons) by reloading a status.php file into the DIV tag.

The problem I’m having is when I directly browse the status.php the command buttons work properly, however when I use them through the index.php they do not respond.

I am trying to learn why they fail this way and what I can to make in work in an “ELI5” kind of way.

The command buttons run a Python script which opens/closes the garage door.  The next time the status Python script (at the top of status.php) is run, it'll have the new status of the door and eventually display it in the DIV tags when AJAX updates that part of the page.

When I click the buttons now index.php stays displayed in it, but the DIV tag completely reloads status.php.   When this happens though, the Python script does not appear to get triggered.

I suspect the command buttons need to be run in a more AJAX/Java-ey way instead of through PHP, but I don't even know where to begin.

Oh, one more thing:    I also have a CGI script available (e.h.  http://example.com/cgi-bin/myq-cgi.py?username=user&pass=pass&command=open) which I can also use to open/close the door.   I do NOT use it for the status though because it doesn't include the time/date the status last changed like the full Python script does.  This might be a potential way to better open/close the door.

index.php:

        Somethign on the web page.  Normally this would be the main website while the DIV tag waits to load.

status.php:

<?php

// Call Python script which gives me the status of my garage door in a text string.
$output = shell_exec('python /home/blah/garage_door/myq-garage.py status');

//I am NOT including lots of parsing of the $output.  Eventually I get the $output trimmed down to the to the $status PHP variable.
$status[1] = "Closed"   //values here can be either 'Closed' or 'Open'

?>

            <?php
                //Stuff unrelated to OP question here.  Dynamically displaying an image based on garage door status.
             ?>

        <?php
            // Command button to open door.
            if (isset($_POST['button_open'])){
                if ($status[1] = "Closed"){
                    shell_exec('python /home/blah/garage_door/myq-garage.py open "Garage Door"');
                }
            }

            // Command button to close door.
                if (isset($_POST['button_close'])){
                    if ($status[1] = "Open"){
                        shell_exec('python /home/blah/garage_door/myq-garage.py close "Garage Door"');
                        echo "";
                    }
                }

        ?>
        <form method="post">

                <button name="button_open">Open Door</button>
                <button name="button_close">Close Door</button>

        </form>

Body:
@hassan got me thinking, so I worked on building my command buttons on the index.php so that they're not within the ajax response.

I got them working.  The garage door opens/closes.  The index.php reloads the ajax just quick enough where the user can see the status, for example change from Closed --> Opening --> Open --> Closing --> Closed.   More importantly the page doesn't do an overall reload like the old PHP buttons were causing.

This time I did the button in HTML/javascript instead of using PHP.  Also instead of running the Python script, I'm instead using a different python-based CGI script as I mentioned is available in my OP.

Once this was working in index.php, just for the heck of it, I copied it to the status.php and when it gets loaded with ajax, it still works inside there correctly and will execute!

Here is the javascipt which first was in index.html, but ultimately moved to status.php:

<script>
function open_door() {
    jQuery(function($) {
        $.ajax( {
            url : "http://example.com/cgi-bin/myq-cgi.py?user=somethibng@hotmail.com&pass=dfgsdfgsdfg&cmd=open",
            type : "GET",
            success : function(data) {
                alert ("Opening Door..."); //or use data string to show something else
                }
            });
        });
    }
</script>

<script>
function close_door() {
    jQuery(function($) {
        $.ajax( {
            url : "http://example.com/cgi-bin/myq-cgi.py?user=something@hotmail.com&pass=dfgdfgsdfg&cmd=close",
            type : "GET",
            success : function(data) {
                alert ("Closing Door..."); //or use data string to show something else
                }
            });
        });
    }
</script>

<form>
<input type="button" value="open" onClick="open_door()"
</form><form>
<input type="button" value="close" onClick="close_door()"
</form>


问:
Getting Application path during the installation
I'm deploying an application and during the installation after the user chooses where to install the app, I want to get that path; I'm in a custom action already but i don't know how to get the application path where it's going to be installed !

It's Windows Forms and I'm developing using Visual studio 2010 "C#".

And I'm using the default deploying tool...

Any idea?

thanks in advance...

答:
Sorry to post answer for old post but my answer may help other.</p>

```<code>public override void Install(System.Collections.IDictionary stateSaver)
{
    base.Install(stateSaver);
    rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (rkApp.GetValue("MyApp") == null)
    {
        rkApp.SetValue("MyApp", this.Context.Parameters["assemblypath"]);
    }
    else
    {
        if (rkApp.GetValue("MyApp").ToString() != this.Context.Parameters["assemblypath"])
        {
            rkApp.SetValue("MyApp", this.Context.Parameters["assemblypath"]);
        }
    }
}

public override void Uninstall(System.Collections.IDictionary savedState)
{
    base.Uninstall(savedState);
    rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

    if (rkApp.GetValue("MyApp") != null)
    {
        rkApp.DeleteValue("MyApp", false);
    }
}
</code>```

Body:
Sorry to post answer for old post but my answer may help other.

public override void Install(System.Collections.IDictionary stateSaver)
{
    base.Install(stateSaver);
    rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (rkApp.GetValue("MyApp") == null)
    {
        rkApp.SetValue("MyApp", this.Context.Parameters["assemblypath"]);
    }
    else
    {
        if (rkApp.GetValue("MyApp").ToString() != this.Context.Parameters["assemblypath"])
        {
            rkApp.SetValue("MyApp", this.Context.Parameters["assemblypath"]);
        }
    }
}

public override void Uninstall(System.Collections.IDictionary savedState)
{
    base.Uninstall(savedState);
    rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

    if (rkApp.GetValue("MyApp") != null)
    {
        rkApp.DeleteValue("MyApp", false);
    }
}


问:
Check for ascending order of a list in Racket
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

```<code>(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))
</code>```

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."

答:
I guess you want to implement a procedure from scratch, and Alexander's answer is spot-on. But in true functional programming style, you should try to reuse existing procedures to write the solution. This is what I mean:

```<code>(define (ascending? lst)
  (apply < lst))
</code>```

It's shorter, simpler and easier to understand. And it works as expected!

```<code>(ascending? '(1 2 3))
=> #t

(ascending? '(1 1 2))
=> #f
</code>```

Body:
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."

Body:
I guess you want to implement a procedure from scratch, and Alexander's answer is spot-on. But in true functional programming style, you should try to reuse existing procedures to write the solution. This is what I mean:

(define (ascending? lst)
  (apply < lst))

It's shorter, simpler and easier to understand. And it works as expected!

(ascending? '(1 2 3))
=> #t

(ascending? '(1 1 2))
=> #f


问:
How do I add an external javascript file and run a function via bookmarklet?
Hi I'm trying to make a javascript bookmarklet that will add a link to an external javascript source to a page that is off the domain. However nothing happens when I run the bookmarklet no errors and the code on the page never changes. Any ideas? Here is the bookmarklet I'm trying to use. Thanks for your time. </p>

```<code>javascript:(function(){document.body.appendChild(document.createElement('script')).src='http://mycode.com/autopopulator.js';autopopulate();})();
</code>```

答:
You can also achieve this with a callback:

```<code>    var addScript=function(filename,callback){
            var e=document.createElement('script');
            e.type = 'text/javascript';
            e.src = filename;
            if(callback){
                e.onloadDone=false;//for Opera
                e.onload=function(){e.onloadDone=true;callback();};
                e.onReadystatechange=function(){
                    if(e.readyState==='loaded'&& !e.onloadDone){
                        e.onloadDone=true;callback();
                    }
                }
            }
        if(typeof(e)!=='undefined'){
            document.getElementsByTagName('head')[0].appendChild(e);
        }
    }
addScript('http://yoursite.com/js/yourScript.js',function(){functionFromYourScript();});
</code>```

(of course you'll want to optimize this to cram it in a bookmarklet, but you get the idea...)

Body:
Hi I'm trying to make a javascript bookmarklet that will add a link to an external javascript source to a page that is off the domain. However nothing happens when I run the bookmarklet no errors and the code on the page never changes. Any ideas? Here is the bookmarklet I'm trying to use. Thanks for your time.

javascript:(function(){document.body.appendChild(document.createElement('script')).src='http://mycode.com/autopopulator.js';autopopulate();})();

Body:
You can also achieve this with a callback:

    var addScript=function(filename,callback){
            var e=document.createElement('script');
            e.type = 'text/javascript';
            e.src = filename;
            if(callback){
                e.onloadDone=false;//for Opera
                e.onload=function(){e.onloadDone=true;callback();};
                e.onReadystatechange=function(){
                    if(e.readyState==='loaded'&& !e.onloadDone){
                        e.onloadDone=true;callback();
                    }
                }
            }
        if(typeof(e)!=='undefined'){
            document.getElementsByTagName('head')[0].appendChild(e);
        }
    }
addScript('http://yoursite.com/js/yourScript.js',function(){functionFromYourScript();});

(of course you'll want to optimize this to cram it in a bookmarklet, but you get the idea...)


问:
firebase orderbychild equalTo
Hi I'm building an app using firebase and here is my firebase model:

Code for search user by name:

```<code>exports.findByUsername = function (username, cb) {

ref.orderByChild("username")
    .equalTo(username)
    .once("value", function (snapshot) {
        records = snapshot.val();

        if (records === null) {
            return cb(null, null);
        }

        return cb(null, records);
    });
</code>```

};

I expect to receive an object when I'm looking for the first user:

```<code> [ 1 ,
  { clubID: 4,
    displayName: 'Jack',
    email: 'jack@example.com',
    id: 1,
    password: 'vasa',
    token: 1,
    username: 'jack' } ]
</code>```

But I get

```<code>[  ,
      { clubID: 4,
        displayName: 'Jack',
        email: 'jack@example.com',
        id: 1,
        password: 'vasa',
        token: 1,
        username: 'jack' } ]
</code>```

What's the trouble? When looking for a second user, then everything is fine.

答:
You're storing your user info with numeric keys (1,2,3, etc). When you do this, the Firebase SDK may try to convert the result into an array. For an explanation of when it does this, see our blog post Best Practices: Arrays in Firebase.

The bottom line is: don't use numeric, sequential keys for items in Firebase. Instead:

If the items have a natural key, store them under that natural key

If the items don't have a natural key, use Firebase push IDs as the key

Since you're storing users, it's common practice to use the UID of each user as their key.

But since your User IDs don't look like Firebase Authentication UIDs, that might leave the same problem. In that case, you can keep using your current keys, but in that case prefix them with a string to prevent the array coercion of the SDK. So:

```<code>"Users": {
  "User1": {
    ...
  }
  "User2": {
    ...
  }
}
</code>```

Title: firebase orderbychild equalTo

Body:
Hi I'm building an app using firebase and here is my firebase model:

Code for search user by name:

exports.findByUsername = function (username, cb) {

ref.orderByChild("username")
    .equalTo(username)
    .once("value", function (snapshot) {
        records = snapshot.val();

        if (records === null) {
            return cb(null, null);
        }

        return cb(null, records);
    });

};

I expect to receive an object when I'm looking for the first user:

 [ 1 ,
  { clubID: 4,
    displayName: 'Jack',
    email: 'jack@example.com',
    id: 1,
    password: 'vasa',
    token: 1,
    username: 'jack' } ]

But I get

[  ,
      { clubID: 4,
        displayName: 'Jack',
        email: 'jack@example.com',
        id: 1,
        password: 'vasa',
        token: 1,
        username: 'jack' } ]

What's the trouble? When looking for a second user, then everything is fine.

Body:
You're storing your user info with numeric keys (1,2,3, etc). When you do this, the Firebase SDK may try to convert the result into an array. For an explanation of when it does this, see our blog post Best Practices: Arrays in Firebase.

The bottom line is: don't use numeric, sequential keys for items in Firebase. Instead:

If the items have a natural key, store them under that natural key

If the items don't have a natural key, use Firebase push IDs as the key

Since you're storing users, it's common practice to use the UID of each user as their key.

But since your User IDs don't look like Firebase Authentication UIDs, that might leave the same problem. In that case, you can keep using your current keys, but in that case prefix them with a string to prevent the array coercion of the SDK. So:

"Users": {
  "User1": {
    ...
  }
  "User2": {
    ...
  }
}


问:
To include css in odoo 9.0
I have problem including css in odoo9. Can you suggest any solution?

```<code><template id="mystyle" name="My style" inherit_id="website.assets_backend">
    <xpath expr="link[last()]" position="after">
        <link rel="stylesheet" href="/theme_tutorial/static/less/style.less" type="text/less"/>
    </xpath>
</template>
</code>```

```<code>.services{
    background: red;
}
</code>```

答:
you need to add the link of your css file on the template of backend assets there is two type of including css :

1- backend css  : use web.assets_backend

```<code><template id="assets_backend" name="custom bar assets" inherit_id="web.assets_backend">
        <xpath expr="." position="inside">
            <link rel="stylesheet" href="/your_module_name/static/src/css/your_css_file"/>
    </template>
</code>```

for qweb report css : use  : report.assets_common

```<code><template id="report_assets_backend" name="tip assets" inherit_id="report.assets_common">
    <xpath expr="." position="inside">
        <link rel="stylesheet" href="/your_module_name/static/src/css/you_css_file"/>
    </xpath>
</template>
</code>```

Title: To include css in odoo 9.0

Body:
I have problem including css in odoo9. Can you suggest any solution?

<template id="mystyle" name="My style" inherit_id="website.assets_backend">
    <xpath expr="link[last()]" position="after">
        <link rel="stylesheet" href="/theme_tutorial/static/less/style.less" type="text/less"/>
    </xpath>
</template>

.services{
    background: red;
}

Body:
you need to add the link of your css file on the template of backend assets there is two type of including css :

1- backend css  : use web.assets_backend

<template id="assets_backend" name="custom bar assets" inherit_id="web.assets_backend">
        <xpath expr="." position="inside">
            <link rel="stylesheet" href="/your_module_name/static/src/css/your_css_file"/>
    </template>

for qweb report css : use  : report.assets_common

<template id="report_assets_backend" name="tip assets" inherit_id="report.assets_common">
    <xpath expr="." position="inside">
        <link rel="stylesheet" href="/your_module_name/static/src/css/you_css_file"/>
    </xpath>
</template>


问:
Numpy searchsorted descending order
I am trying to understand how to correctly use numpy.searchsorted to find the correct index where to insert an element. When i run the following:

```<code>e = np.array([9,8,7,6])
np.searchsorted(e,5)
</code>```

The output I get is 0, which is wrong as I would expect 4 as the answer. Is searchsorted usable for arrays ordered in descending order? What options do I have if I need to keep the array in descending order? Thanks a lot!

答:
You can do it using the sorter optional argument.  As per the documentation this is usually the result of np.argsort(e):

```<code>array([3, 2, 1, 0])
</code>```

Which you can produce more efficiently this way:

```<code>np.arange(len(e)-1, -1, -1)
</code>```

Then:

```<code>np.searchsorted(e, 7.5, sorter=np.arange(len(e)-1, -1, -1))
</code>```

Gives you 2.

Title: Numpy searchsorted descending order

Body:
I am trying to understand how to correctly use numpy.searchsorted to find the correct index where to insert an element. When i run the following:

e = np.array([9,8,7,6])
np.searchsorted(e,5)

The output I get is 0, which is wrong as I would expect 4 as the answer. Is searchsorted usable for arrays ordered in descending order? What options do I have if I need to keep the array in descending order? Thanks a lot!

Body:
You can do it using the sorter optional argument.  As per the documentation this is usually the result of np.argsort(e):

array([3, 2, 1, 0])

Which you can produce more efficiently this way:

np.arange(len(e)-1, -1, -1)

Then:

np.searchsorted(e, 7.5, sorter=np.arange(len(e)-1, -1, -1))

Gives you 2.


问:
Clickable link inside a text control like RichTextControl in WPF?
I want to be able to have some text clickable like in webpages in WPF. The control should have both non-functional text (for display) both also some of its parts as completely clickable.

Say like Wikipedia.

But this is an independent standalone offline app.

I tried various things but I couldn't do it, especially the clicking doesn't function like web pages, i.e. 1 click to open the url contained within the tools.

答:
you should try setting the flow document manually and creating hyperlinks within the flow document...

Here is some text taken from the following link:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/99ae9d9c-1dd4-4acd-8d5d-6eb739adeb98

"
Hi,

It is possible.
Here is a small example of creating hyperlink to paragraph/section/table.

In order to navigate to website, we can create a Frame  Control for navigation. The hierarchical relationship of  elements in this example is like this :

Frame-->FlowDocument-->Table-->Section-->Paragraph-->Hyperlink

In the code behind:

```<code>public Window1()
        {
            InitializeComponent();

            // add a Frame for navigation
            Frame frame = new Frame();
            this.Content = frame;
            //add FlowDocument
            FlowDocument doc = new FlowDocument();
            frame.Navigate(doc);

            //add Table
            Table table = new Table();
            doc.Blocks.Add(table );
            TableRowGroup group = new TableRowGroup();
            table.RowGroups.Add(group );

            TableColumn col1 = new TableColumn();
            TableColumn col2 = new TableColumn();
            table.Columns.Add(col1 );
            table.Columns.Add(col2);

            TableRow row1 = new TableRow();
            TableCell cel1 = new TableCell();
            row1.Cells.Add(cel1);

            group.Rows.Add(row1);

            //add Section
            Section mySection = new Section();
            //add section to the Table cell.
            cel1.Blocks.Add(mySection);

            Paragraph paraValue = new Paragraph();
            Hyperlink hl = new Hyperlink(new Run("Click Here to Google"));
            hl.Foreground = Brushes.Red;
            paraValue.Inlines.Add(hl);

            hl.FontSize = 11;
            hl .NavigateUri =new Uri ("Http://www.google.cn");

            mySection.Blocks.Add(paraValue);
        }
</code>```

If you have any additional question about this,please feel free to ask.

Thanks. "

Body:
you should try setting the flow document manually and creating hyperlinks within the flow document...

Here is some text taken from the following link:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/99ae9d9c-1dd4-4acd-8d5d-6eb739adeb98

"
Hi,

It is possible.
Here is a small example of creating hyperlink to paragraph/section/table.

In order to navigate to website, we can create a Frame  Control for navigation. The hierarchical relationship of  elements in this example is like this :

Frame-->FlowDocument-->Table-->Section-->Paragraph-->Hyperlink

In the code behind:

public Window1()
        {
            InitializeComponent();

            // add a Frame for navigation
            Frame frame = new Frame();
            this.Content = frame;
            //add FlowDocument
            FlowDocument doc = new FlowDocument();
            frame.Navigate(doc);

            //add Table
            Table table = new Table();
            doc.Blocks.Add(table );
            TableRowGroup group = new TableRowGroup();
            table.RowGroups.Add(group );

            TableColumn col1 = new TableColumn();
            TableColumn col2 = new TableColumn();
            table.Columns.Add(col1 );
            table.Columns.Add(col2);

            TableRow row1 = new TableRow();
            TableCell cel1 = new TableCell();
            row1.Cells.Add(cel1);

            group.Rows.Add(row1);

            //add Section
            Section mySection = new Section();
            //add section to the Table cell.
            cel1.Blocks.Add(mySection);

            Paragraph paraValue = new Paragraph();
            Hyperlink hl = new Hyperlink(new Run("Click Here to Google"));
            hl.Foreground = Brushes.Red;
            paraValue.Inlines.Add(hl);

            hl.FontSize = 11;
            hl .NavigateUri =new Uri ("Http://www.google.cn");

            mySection.Blocks.Add(paraValue);
        }

If you have any additional question about this,please feel free to ask.

Thanks. "


问:
Golang convert integer to unicode character
Given the following input:

```<code>intVal := 2612
strVal := "2612"
</code>```

What is a mechanism for mapping to the associated unicode value as a string.

For example, the following code prints "☒"

```<code>fmt.Println("\u2612")
</code>```

But the following does not work:

```<code>fmt.Println("\\u" + strVal)
</code>```

I researched runes, strconv, and unicode/utf8 but was unable to find a suitable conversion strategy.

答:
This one works:

```<code>fmt.Println("\u2612")
</code>```

Because an interpreted string literal is specified in the source code, and the compiler will unquote (interpret) it. It is not the fmt package that processes this unquoting.

This doesn't work:

```<code>fmt.Println("\\u" + strVal)
</code>```

Because again an interpreted string literal is used which will be resolved to a string value \u, and then it will be concatenated with the value of the local variable strVal which is 2612, so the final string value will be \u2612. But this is not an interpreted string literal, this is the "final" result. This won't be processed / unquoted further.

Alternatively to JimB's answer, you may also use strconv.Unquote() which does an unquoting similar to what the compiler does.

See this example:

```<code>// The original that works:
s := "\u2612"
fmt.Println(s, []byte(s))

// Using strconv.Unquote():
strVal := "2612"
s2, err := strconv.Unquote(`"\u` + strVal + `"`)
fmt.Println(s2, []byte(s2), err)
fmt.Println(s == s2)
</code>```

Output (try it on the Go Playground):

```<code>☒ [226 152 146]
☒ [226 152 146] <nil>
true
</code>```

Something to note here: We want to unquote the \u2612 text by strconv.Unquote(), but Unquote() requires that the string to be unquoted to be in quotes ("Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal..."), that's why we pre- and postpended it with a quotation mark.

Body:
Given the following input:

intVal := 2612
strVal := "2612"

What is a mechanism for mapping to the associated unicode value as a string.

For example, the following code prints "☒"

fmt.Println("\u2612")

But the following does not work:

fmt.Println("\\u" + strVal)

I researched runes, strconv, and unicode/utf8 but was unable to find a suitable conversion strategy.

Body:
This one works:

fmt.Println("\u2612")

Because an interpreted string literal is specified in the source code, and the compiler will unquote (interpret) it. It is not the fmt package that processes this unquoting.

This doesn't work:

fmt.Println("\\u" + strVal)

Because again an interpreted string literal is used which will be resolved to a string value \u, and then it will be concatenated with the value of the local variable strVal which is 2612, so the final string value will be \u2612. But this is not an interpreted string literal, this is the "final" result. This won't be processed / unquoted further.

Alternatively to JimB's answer, you may also use strconv.Unquote() which does an unquoting similar to what the compiler does.

See this example:

// The original that works:
s := "\u2612"
fmt.Println(s, []byte(s))

// Using strconv.Unquote():
strVal := "2612"
s2, err := strconv.Unquote(`"\u` + strVal + `"`)
fmt.Println(s2, []byte(s2), err)
fmt.Println(s == s2)

Output (try it on the Go Playground):

☒ [226 152 146]
☒ [226 152 146] <nil>
true

Something to note here: We want to unquote the \u2612 text by strconv.Unquote(), but Unquote() requires that the string to be unquoted to be in quotes ("Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal..."), that's why we pre- and postpended it with a quotation mark.


Title: Rename duplicated index values pandas DataFrame

Body:
I have a DataFrame that contains some duplicated index values:

df1 =  pd.DataFrame( np.random.randn(6,6), columns = pd.date_range('1/1/2010', periods=6), index = {"A", "B", "C", "D", "E", "F"})
df1.rename(index = {"C": "A", "B": "E"}, inplace = 1)

ipdb> df1
      2010-01-01  2010-01-02  2010-01-03  2010-01-04  2010-01-05  2010-01-06
 A   -1.163883    0.593760    2.323342   -0.928527    0.058336   -0.209101
 A   -0.593566   -0.894161   -0.789849    1.452725    0.821477   -0.738937
 E   -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
 F    1.707686    0.323213    0.048503    1.168898    0.002662   -1.988825
 D    0.403028   -0.879873   -1.809991   -1.817214   -0.012758    0.283450
 E   -0.224405   -1.803301    0.582946    0.338941    0.798908    0.714560

I would like to change only the name of the duplicated values and to obtain a DataFrame like the following one:

ipdb> df1
     2010-01-01  2010-01-02  2010-01-03  2010-01-04  2010-01-05  2010-01-06
A   -1.163883    0.593760    2.323342   -0.928527    0.058336   -0.209101
A_dp   -0.593566   -0.894161   -0.789849    1.452725    0.821477   -0.738937
E   -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
F    1.707686    0.323213    0.048503    1.168898    0.002662   -1.988825
D    0.403028   -0.879873   -1.809991   -1.817214   -0.012758    0.283450
E_dp   -0.224405   -1.803301    0.582946    0.338941    0.798908    0.714560

My approach:

(i) Create dictionary with new names

old_names = df1[df1.index.duplicated()].index.values
new_names = df1[df1.index.duplicated()].index.values + "_dp"
dictionary = dict(zip(old_names, new_names))

(ii) Rename only the duplicated values

df1.loc[df1.index.duplicated(),:].rename(index = dictionary, inplace = True)

However this does not seem to work.

Body:
You can use Index.where:

df1.index = df1.index.where(~df1.index.duplicated(), df1.index + '_dp')
print (df1)
      2010-01-01  2010-01-02  2010-01-03  2010-01-04  2010-01-05  2010-01-06
A      -1.163883    0.593760    2.323342   -0.928527    0.058336   -0.209101
A_dp   -0.593566   -0.894161   -0.789849    1.452725    0.821477   -0.738937
E      -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
F       1.707686    0.323213    0.048503    1.168898    0.002662   -1.988825
D       0.403028   -0.879873   -1.809991   -1.817214   -0.012758    0.283450
E_dp   -0.224405   -1.803301    0.582946    0.338941    0.798908    0.714560

And if need remove of duplicated index to unique:

print (df1)
   2010-01-01  2010-01-02  2010-01-03  2010-01-04  2010-01-05  2010-01-06
A   -1.163883    0.593760    2.323342   -0.928527    0.058336   -0.209101
A   -0.593566   -0.894161   -0.789849    1.452725    0.821477   -0.738937
E   -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
E   -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
E   -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
F    1.707686    0.323213    0.048503    1.168898    0.002662   -1.988825
D    0.403028   -0.879873   -1.809991   -1.817214   -0.012758    0.283450
E   -0.224405   -1.803301    0.582946    0.338941    0.798908    0.714560

df1.index = df1.index + df1.groupby(level=0).cumcount().astype(str).replace('0','')
print (df1)
    2010-01-01  2010-01-02  2010-01-03  2010-01-04  2010-01-05  2010-01-06
A    -1.163883    0.593760    2.323342   -0.928527    0.058336   -0.209101
A1   -0.593566   -0.894161   -0.789849    1.452725    0.821477   -0.738937
E    -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
E1   -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
E2   -0.670305   -1.788403    0.134790   -0.270894    0.672948    1.149089
F     1.707686    0.323213    0.048503    1.168898    0.002662   -1.988825
D     0.403028   -0.879873   -1.809991   -1.817214   -0.012758    0.283450
E3   -0.224405   -1.803301    0.582946    0.338941    0.798908    0.714560


问:
git push http-origin mybranchname problems
Hi I have a remote repo that I before could push against with no problem and still can from another computer with the same git remotes.
my remotes is as following:

http-origin http://gitlab.xx.xx/xx.git (fetch)

http-origin http://gitlab.xx.xx/xx.git (push)

when i do my git push http-origin mybranchname i get following error:

remote: Not Found
fatal: repository 'https://gitlab.xx.xx/xx.git' not found

does anyone know why this is happening. I am running os x with terminal with zsh

答: check that links for push/pull are correctly set on Your OS X - write in console from root folder of project git remote -v. Compare it with links shown on gitlab in your repo. If it is correct - try git push --set-upstream origin nameOfBranchYouWantToPush. If this does not work - the problem might be or with permissions, or, if you are using ssh - with rsa keys


问:
Using cout with basic_string<unsigned char>
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

```<code>#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}
</code>```

This doesn't compile with

```<code>error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')
</code>```

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?

答:
The standard defines the following template operator:

```<code>template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os,
               const std::basic_string<CharT, Traits, Allocator>& str);
</code>```

This means you can stream std::string to std::cout, and std::wstring to std::wcout.  You can't stream std::wstring to std::cout.

Your problem is that std::cout uses character type char, not unsigned char.

You can define an additional operator in the global namespace if you like.

```<code>typedef std::basic_string<unsigned char> ustring;

std::ostream& operator << (std::ostream& stream, const ustring& str) {
    if (const auto len = str.size())
       stream.write(reinterpret_cast<const char*>(&str[0]), len);
    return stream;
}
</code>```

Body:
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}

This doesn't compile with

error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?

Body:
The standard defines the following template operator:

template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os,
               const std::basic_string<CharT, Traits, Allocator>& str);

This means you can stream std::string to std::cout, and std::wstring to std::wcout.  You can't stream std::wstring to std::cout.

Your problem is that std::cout uses character type char, not unsigned char.

You can define an additional operator in the global namespace if you like.

typedef std::basic_string<unsigned char> ustring;

std::ostream& operator << (std::ostream& stream, const ustring& str) {
    if (const auto len = str.size())
       stream.write(reinterpret_cast<const char*>(&str[0]), len);
    return stream;
}


问:
mod_fcgid with php opcode caching
I have been using apache web server with mpm-worker and mod_fcgid.

I have read about mod_fcgid that it can not make use of opcode caching.

http://www.brandonturner.net/blog/2009/07/fastcgi_with_php_opcode_cache/

apc cache module seems to be enabled in my php  configuration.

I am not sure if my spawned php codes are never shared.

Should I remove APC? Does it have any overhead?

答:
It does use opcode caching, but the caches are not shared between the PHP processes, so they will be cached once for each process.  It's definitely still worth using APC.

Having read the article, I'll throw my own $0.2c in here w/regards to fgcid vs fastcgi.  We initially deployed a solution much like that described in the article, using fastcgi and having the PHP process spawn multiple children.  This was an attempt to work around the problems of sharing the cache.

However, we experienced periodic complete lockups with this solution; the PHP process would hang and fastcgi would fail to detect it, resulting in our entire app hanging for all users.

We've switched to fcgid again and the lockups ceased entirely.  There is some overhead with a cache per process, but fcgid will only spawn new PHP processes when it needs to, so in practice the overhead is minimal.

We also use the user cache with APC, not just the opcode cache, so for us the tradeoff is definitely worth it (cached data means less work on the server, cached opcodes mean less work on the server) so CPU usage is definitely reduced for a slight memory usage penalty.

Title: mod_fcgid with php opcode caching


问:
Cache (potentially) changing values from the database in java
What is the current recommended approach for storing cached data in Java

I am looking for a particular approach that will update the cache when an insert or an update happens to particular table(s).

Ideally this should happen as quickly as possible so as to avoid any issues when cross referencing data.

Is there a technology that provides this (such as ehcache) or an advised programming standard which i could follow.

Thanks

答: Spring cache abstraction ? There are a lot of implemented cache providers like Ehcache or Redis.</p>


问:
jPlayer "duration" calculated as 1,440 minutes on iOs (for all mp3s)
I have an home-made simple webpage for playing mp3s and viewing pdfs.  I use jPlayer v 2.9.2 to play the mp3s.  On PC it works fine, but on iphone jPlayer gets the wrong value for duration:  all files start out with "1439:59" remaining.  This effectively breaks the scrubber bar.

An example mp3 is here (it's a practise track for my choir):

https://jamtartschoir.updog.co/files/Leeds%20United%20(Amanda%20Palmer)/Leeds%20United%20Bass.mp3

On iOs, when played with jPlayer, the mp3 starts playing, and then half way through it goes back to the start.  This might be another symptom of the same problem.

It occurred to me that the mp3 might need some specially formatted header, or metadata, or something, in order to play properly on iOs.  Has anyone come across a problem like this before?

thanks, Max

EDIT: I think this is something specific to Dropbox, or perhaps to Updog, which is a Dropbox-based free hosting service.  I found an external https-served mp3 which I tried out in my app:

https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3

this is fine - it gets the duration ok.  However, if I download this file, put it in dropbox and then access the dropbox version, I get the duration bug.

https://jamtartschoir.updog.co/files/A%20New%20England%20(Billy%20Bragg)/mpthreetest.mp3

EDIT 2:  I set up a test page to illustrate this issue, using audio tags.

https://jamtartschoir.updog.co/test.html

答:
Does this happen with other .mp3 files? Try http://jplayer.org/audio/m4a/Miaow-07-Bubble.m4a

If the problem doesn't happen then check out the response headers. Try allowing range-requests in your response. I know that chrome needs this, not sure about IOS but this could be the problem.

If this is still a problem with this .mp3 then try one of the exampels from the jPlayer.org website.

If this still persists then it's a jPlayer bug.


问:
How to remove common objects from two lists with linq

Both lists have Objects with ID and Name properties.

List1({1, apple}, {2, orange}, {3, banana}, {4, potato}, {5, tomato})

List2({1, apple}, {2, orange}, {3, banana})

Final output List3({4, potato}, {5, tomato})

答:
Following idea:

Build intersection set

Remove intersection set from base lists

```<code>IEnumerable<int> common = a.Intersect(b).ToList();

a.RemoveAll(x => common.Contains(x));
b.RemoveAll(x => common.Contains(x));
</code>```

Body:
Following idea:

Build intersection set

Remove intersection set from base lists

IEnumerable<int> common = a.Intersect(b).ToList();

a.RemoveAll(x => common.Contains(x));
b.RemoveAll(x => common.Contains(x));


问:
Creating Dataframe from list of Dictionaries, without using pd.concat()
I have data structures that are dictionaries of numpy arrays, and look something like this:

```<code>metric_one =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

metric_two =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}
</code>```

With the following labels:

```<code>['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
</code>```

I'd like to have a dataframe that looks like this:

```<code>   0  1  2  3
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9
</code>```

I can do that by converting each of the dictionaries into dataframes and then concatenating them with pd.concat(). However, that is really slow, especially when the dicionaries to concatenate grow (I need to concatenate about 20 of them). From profiling, it seems that creating the single dataframes before concatenating is actually taking the majority of the time. Therefore I was wondering if there was a better way of doing this, for instance rearranging the dictionaries in a smart way into a big data structure that contains all the dictionaries (maybe in a list? maybe in a big dicionary?) so that we can build only one dataframe by passing this big data structure into the constructor.

Thanks!

答:
In case your dictionaries are of the same shape and have the same keys, you can do the following:

```<code># setup dummy data
metric_one = {0: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    1: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    2: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    3: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

metric_two = {0: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    1: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    2: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    3: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

# store metrics in one list to iterate over
dicts = [metric_one, metric_two]

# define helper function to concat numpy arrays
def iter_key(key, dicts):
    return np.concatenate([sub_dict[key] for sub_dict in dicts])

merged = {key: iter_key(key, dicts) for key in metric_one.keys()}

df = pd.DataFrame(merged, index=labels * len(dicts))
print(df)

    0   1   2   3
a   0   0   0   0
b   1   1   1   1
c   2   2   2   2
d   3   3   3   3
e   4   4   4   4
f   5   5   5   5
g   6   6   6   6
h   7   7   7   7
i   8   8   8   8
j   9   9   9   9
a   0   0   0   0
b   1   1   1   1
c   2   2   2   2
d   3   3   3   3
e   4   4   4   4
f   5   5   5   5
g   6   6   6   6
h   7   7   7   7
i   8   8   8   8
j   9   9   9   9
</code>```

Merging the dicts first is faster than concatenating the pandas data frames. Below you'll find timings for 20 dicts:

```<code>%%timeit
dicts = [metric_one, metric_two]  * 10
def iter_key(key, dicts):
    return np.concatenate([sub_dict[key] for sub_dict in dicts])

merged = {key: iter_key(key, dicts) for key in metric_one.keys()}

df = pd.DataFrame(merged, index=labels * len(dicts))

>>> 1000 loops, best of 3: 630 µs per loop
</code>```

Here the timeit for concat:

```<code>%%timeit
dicts = [metric_one, metric_two]  * 10
df = pd.concat([pd.DataFrame(sub_dict, index=labels) for sub_dict in dicts])

>>> 100 loops, best of 3: 13.6 ms per loop
</code>```

The merge first approach is roughly 20 times faster here.

Body:
I have data structures that are dictionaries of numpy arrays, and look something like this:

metric_one =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

metric_two =
{0: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
1: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
2: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
3: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

With the following labels:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

I'd like to have a dataframe that looks like this:

   0  1  2  3
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9
a  0  0  0  0
b  1  1  1  1
c  2  2  2  2
d  3  3  3  3
e  4  4  4  4
f  5  5  5  5
g  6  6  6  6
h  7  7  7  7
i  8  8  8  8
j  9  9  9  9

I can do that by converting each of the dictionaries into dataframes and then concatenating them with pd.concat(). However, that is really slow, especially when the dicionaries to concatenate grow (I need to concatenate about 20 of them). From profiling, it seems that creating the single dataframes before concatenating is actually taking the majority of the time. Therefore I was wondering if there was a better way of doing this, for instance rearranging the dictionaries in a smart way into a big data structure that contains all the dictionaries (maybe in a list? maybe in a big dicionary?) so that we can build only one dataframe by passing this big data structure into the constructor.

Thanks!

Body:
In case your dictionaries are of the same shape and have the same keys, you can do the following:

# setup dummy data
metric_one = {0: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    1: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    2: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    3: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

metric_two = {0: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    1: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    2: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
    3: np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}

labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

# store metrics in one list to iterate over
dicts = [metric_one, metric_two]

# define helper function to concat numpy arrays
def iter_key(key, dicts):
    return np.concatenate([sub_dict[key] for sub_dict in dicts])

merged = {key: iter_key(key, dicts) for key in metric_one.keys()}

df = pd.DataFrame(merged, index=labels * len(dicts))
print(df)

    0   1   2   3
a   0   0   0   0
b   1   1   1   1
c   2   2   2   2
d   3   3   3   3
e   4   4   4   4
f   5   5   5   5
g   6   6   6   6
h   7   7   7   7
i   8   8   8   8
j   9   9   9   9
a   0   0   0   0
b   1   1   1   1
c   2   2   2   2
d   3   3   3   3
e   4   4   4   4
f   5   5   5   5
g   6   6   6   6
h   7   7   7   7
i   8   8   8   8
j   9   9   9   9

Merging the dicts first is faster than concatenating the pandas data frames. Below you'll find timings for 20 dicts:

%%timeit
dicts = [metric_one, metric_two]  * 10
def iter_key(key, dicts):
    return np.concatenate([sub_dict[key] for sub_dict in dicts])

merged = {key: iter_key(key, dicts) for key in metric_one.keys()}

df = pd.DataFrame(merged, index=labels * len(dicts))

>>> 1000 loops, best of 3: 630 µs per loop

Here the timeit for concat:

%%timeit
dicts = [metric_one, metric_two]  * 10
df = pd.concat([pd.DataFrame(sub_dict, index=labels) for sub_dict in dicts])

>>> 100 loops, best of 3: 13.6 ms per loop

The merge first approach is roughly 20 times faster here.


问:
Page auto reload without refresh
Hi
I want to know How to make the page reload asynchronous, for example if someone has received a message , the last message will appear without refreshing the page. just like facebook. thank you.</p>

答:
You would have to use something like JQuery & Javascript to poll the server for changes and display them on the page in a div.

```<code>setInterval('someFunc()', 1000)

function someFunc()
{

 $.ajax({
            async: true,
            type: "GET",
            url: "www.domain.com/url",
            data: data,
            success: function (html) {
                $("#myDiv").html(html);
            }
        });

}
</code>```

This will update the div with ID myDiv every second with the data from www.domain.com/url passing in data is a param (you will have to define 'data')

Title: Page auto reload without refresh

Body:
You would have to use something like JQuery & Javascript to poll the server for changes and display them on the page in a div.

setInterval('someFunc()', 1000)

function someFunc()
{

 $.ajax({
            async: true,
            type: "GET",
            url: "www.domain.com/url",
            data: data,
            success: function (html) {
                $("#myDiv").html(html);
            }
        });

}

This will update the div with ID myDiv every second with the data from www.domain.com/url passing in data is a param (you will have to define 'data')


问:
CSS Float content creating whitespace and overlapping other div
I'm in the midst of creating a responsive portfolio at the moment and I'm running into a bit of trouble.

Before a certain breakpoint (css media query), the second and third paragraph in the 'About' section of my website are in floats. As the window gets smaller, the text starts to overlap the footer and eventually create a whitespace at the bottom and side. When it reaches the breakpoint, the floats are valued as 'none'.

How can I make it so that the height of the container is determined by how much content is in there (i.e. the normal behaviour)? I've tried a clearfix, but that doesn't seem to work.

https://codepen.io/webdevkid/pen/gmBVMj

HTML

```<code><body>
    <nav>
        <div id="logo"><a id="logo-link" href="index.html"><span id="word-1">Potential </span><span id="word-2">Beginning</span></a><div id="menu-icon"></div></div><div class="clear"></div>
            <ul id="main-links">
                <a href="#"><li><span class="word-position">About</span></li></a>
                <a href="#"><li><span class="word-position">Work</span></li></a>
                <a href="#"><li class="last-child"><span class="word-position">Contact</span></li></a>
            </ul>
    </nav>
    <div id="main-container">
        <div id="introductory-background">
            <div id="introductory-overlay">
                <div id="introductory-content">
                    <div id="introductory-container">
                        <h1 id="role-header">Junior Web Developer</h1>
                        <h3 id="role-support-text">...but that's not all I can do</h3>
                        <a id="read-more" class="no-select">Read More</a>
                    </div>
                </div>
            </div>
        </div>
        <div id="about-section">
            <br />
            <br />
            <div id="photo-frame">
                <div id="picture"></div>
            </div>
            <br />
            <div id="about-text-container">
                <p>Hi There! My name is Ed Garbutt, a Junior Web Developer based in South Buckinghamshire, with a huge passion for all things programming.</p>
                <br />
                <p id="about-left-side" class="side-by-side">Sadly, I'm not like most Developer out thers. I don't drink Red Bull or Monster Cans. I'm not a fan of Start Wars. I don't read Marvel Comic Books, but I am someone who likes going outside here and then.</p>
                <p id="about-right-side" class="side-by-side">All jokes aside, what you <b>will</b> get is someone who prides himself on attention to details, who will always rise to a challenge ans is constantly looking to better himself, building upon his existing knowledge of programming languages and frameworks.</p>
            </div>
        </div>
    </div>
    <footer>
        <p id="footer-text">
            © 2016 Ed Garbutt. All rights reserved.
        </p>
    </footer>
</body>
</code>```

CSS

```<code>    body {
    margin: 0;
}
nav {
  width: 100%;
  height: 50px;
  position: fixed;
  background-color: rgb(40, 40, 40);
  border-bottom-style: solid;
  border-bottom-color: rgb(238, 0, 0);
  border-bottom-width: 7.5px;
  padding-top: 14px;
  z-index: 10;
}

#logo {
    position: relative;
    bottom: 5px;
    font-size: 30px;
    padding-left: 8px;
    float: left;
    font-family: bebas;
}

#word-1 {
    color: rgb(0, 154, 205);
}

#word-2 {
    color: rgb(255, 250, 250);
}

ul#main-links {
  list-style: none;
  margin: 0;
  padding-right: 50px;
  float: right;
  height: 100%;
  border-bottom: 7.5px solid transparent;
  display: block;
font-size: 0;
}

ul#main-links li {
  display: inline-block;
  text-align: center;
  border-bottom-style: solid;
  border-bottom-width: 7.5px;
border-bottom-color: rgb(238, 0, 0);
  color: white;
  font-family: arcon;
  font-size: 18px;
  height: 100%;
    width: 90px;
  position: relative;
  z-index: 2;
}

a:link {
  text-decoration: none;
}

a:visited {
  text-decoration: none;
    color: white;
}

a:active {
  text-decoration: none;
    color: white;
}

a#logo-link {
    text-decoration: none;

}

a#logo-link:visited {
  text-decoration: none;
    color: inherit;
}

a#logo-link:active {
  text-decoration: none;
    color: inherit;
}

ul#main-links > a > li > span.word-position {
  position: relative;
    top: 5px;
}

#menu-icon {
    height: 48px;
    width: 48px;
    display: none;
    cursor: pointer;
    background-image: url("../images/hamburg-white-2.png");
}

#main-container {
    padding-top: 71.4px;
}

@media screen and (min-width: 656px) {
    ul#main-links {
        display: block !important;
    }
}

@media screen and (max-width: 656px) {

    nav {
        height: initial;
    }

    #logo {
        width: 100%;
        float: none;
        padding-left: 0;
        text-align: center;
        bottom: 8px;
    }

    #menu-icon {
        display: inline-block;
/*        float: right;*/
        position: absolute;
        right: 10px;
        top: -2px;
    }

    ul#main-links {
        display: none;
        float: none;
        padding-right: 0;
        padding-left: 0;
        width: 100%;
    }

    ul#main-links li {
        width: 100%;
        display: block;
        border: none;
        padding: 10px 0;
    }

    ul#main-links li:not(.last-child) {
        border-bottom-style: solid;
        border-bottom-color: rgb(238, 0, 0);
        border-bottom-width: 2.5px;
    }

    ul#main-links > a > li > span.word-position {
        top: 0px;
    }

    #main-container {
        padding-top: 62.4px;
    }
}

@media screen and (max-width: 400px) {
   #logo {
        bottom: 7.5px;
        font-size: 23px;
        padding-left: 10px;
        text-align: left;
    }

    #menu-icon {
        height: 32px;
        width: 32px;
        background-image: url("../images/hamburg-white-1.png");
        top: 0.4px;
        right: 20px;
    }

    #main-container {
        padding-top: 52.4px;
    }
}

/* ----INTORDUCTION---- */

#introductory-background {
    background-image: url('../images/eternity-1024x768.jpg');
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 100%;
/*    min-height: 527px;*/
    height: 90vh;
    background-size: 100% 100%;
    overflow: auto;
}

#introductory-overlay {
    display: table;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}

#introductory-content {
    margin-left: auto;
    margin-right: auto;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

#introductory-container {
    position: relative;
    bottom: 60px;
}

h1#role-header {
    display: block;
    position: relative;
    right: 5em;
    opacity: 0;
    font-size: 48px;
    color: rgb(255, 250, 250);
}

h3#role-support-text {
    display: block;
    opacity: 0;
    position: relative;
    top: 20px;
    font-size: 30px;
    color: rgb(255, 250, 250);
}

#read-more {
    border-radius: 38px;
    background-color: rgb(255, 250, 250);
    padding: 0.5em 1.5em;
    font-size: 24px;
    cursor: pointer;
}

@media screen and (max-width: 656px) {

    #introductory-container {
        bottom: 60px;
    }

    h1#role-header {
        font-size: 37px;
    }

    h3#role-support-text {
        top: 15px;
        font-size: 24px;
    }

    #read-more {
        font-size: 19px;
    }
}

@media screen and (max-width: 400px) {

    #introductory-container {
        bottom: 72.5px;
    }

   h1#role-header {
        font-size: 28px;
    }

    h3#role-support-text {
        top: 11px;
        font-size: 20px;
    }

    #read-more {
        font-size: 16px;
    }
}

/* -------------------- */
/* -------ABOUT-------- */

#about-section {
    width: 100%;
    height: 500px;
    background-color: rgb(131, 111, 235);
}

#photo-frame {
    margin: 0 auto;
    background-color: royalblue;
    width: 180px;
    height: 180px;
    border-radius: 100px;
    border-style: solid;
    border-color: beige;
    border-width: 7.5px;
    z-index: 2;
}

#photo-frame > #picture {
    width: 100%;
    height: 100%;
    background-image: url('../images/Ed.png');
    border-radius: 100px;
}

#about-section > #about-text-container {
    margin: 0 auto;
    width: 80%;
}

#about-section > #about-text-container > p {
    margin: 0;
    text-align: center;
/*    padding: 0 3rem;*/
    font-size: 22px;
}

#about-section > #about-text-container > p.side-by-side {
/*    display: inline-block;*/
    width: 45%;
    text-align: justify;
}

#about-section > #about-text-container > p#about-left-side {
    float: left;
}

#about-section > #about-text-container > p#about-right-side{
    float: right;
}

@media screen and (max-width: 868px) {
    #about-section > #about-text-container > p.side-by-side {
    /*    display: inline-block;*/
        width: 100%;
    }

    #about-section > #about-text-container > p#about-left-side {
        float: none;
        padding-bottom: 1.5rem;
    }

    #about-section > #about-text-container > p#about-right-side{
        float: none;
    }
}

@media screen and (max-width: 656px) {
    #photo-frame {
        width: 150px;
        height: 150px;
    }

    #about-section > #about-text-container {
        width: 90%;
    }

    #about-section > #about-text-container > p {
        text-align: justify;
        padding: 0 1.5rem;
        font-size: 20px;
    }
}

@media screen and (max-width: 400px) {
    #photo-frame {
        width: 125px;
        height: 125px;
    }

    #about-section > #about-text-container {
        width: 100%;
    }

    #about-section > #about-text-container > p {
        padding: 0 0.5rem;
        font-size: 18px;
    }
}

/* -------------------- */
/* -------FOOTER------- */

footer {
    width: 100%;
    background-color: black;
}

footer > p#footer-text {
    margin: 0;
    text-align: center;
    font-family: arial;
    color: rgb(169, 169, 169);
    padding: 20px;
    width: 100%;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

/* -------------------- */

.no-select {
    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none;   /* Safari */
    -khtml-user-select: none;    /* Konqueror HTML */
    -moz-user-select: none;      /* Firefox */
    -ms-user-select: none;       /* Internet Explorer/Edge */
    user-select: none;           /* Non-prefixed version, currently supported by Chrome and Opera */
}

.clearfix:before,
.clearfix:after {
    content: " ";
    display: table;
}
.clearfix:after {
    clear: both;
}
.clearfix {
    *zoom: 1;
}
</code>```

答:
So this boils down to your p.side-by-side definition which is set at 45%.

If you want to not have columns on small screen sizes, then the approach would be to only set that 45% value with a break-point above mobile.

Your using a non-mobile first approach that makes this stuff harder (in my opinion). The easier way to go about it is to not add any width styles to those columns, and only add the 45% and the float, once the screen is above (say) 768px. In other words your media queries will generally have min values, not max.

I think a good way to start to think mobile-first is to realise that mobile layouts use kind of "less" CSS than desktops. So you keep it simple, just using semantic html, and then add in styles as the screen size increases to start making columns etc.

Body:
I'm in the midst of creating a responsive portfolio at the moment and I'm running into a bit of trouble.

Before a certain breakpoint (css media query), the second and third paragraph in the 'About' section of my website are in floats. As the window gets smaller, the text starts to overlap the footer and eventually create a whitespace at the bottom and side. When it reaches the breakpoint, the floats are valued as 'none'.

How can I make it so that the height of the container is determined by how much content is in there (i.e. the normal behaviour)? I've tried a clearfix, but that doesn't seem to work.

https://codepen.io/webdevkid/pen/gmBVMj

HTML

Potential Beginning

About

Work

Contact

Junior Web Developer

...but that's not all I can do

                        Read More

Hi There! My name is Ed Garbutt, a Junior Web Developer based in South Buckinghamshire, with a huge passion for all things programming.

Sadly, I'm not like most Developer out thers. I don't drink Red Bull or Monster Cans. I'm not a fan of Start Wars. I don't read Marvel Comic Books, but I am someone who likes going outside here and then.

All jokes aside, what you will get is someone who prides himself on attention to details, who will always rise to a challenge ans is constantly looking to better himself, building upon his existing knowledge of programming languages and frameworks.

            © 2016 Ed Garbutt. All rights reserved.

CSS

    body {
    margin: 0;
}
nav {
  width: 100%;
  height: 50px;
  position: fixed;
  background-color: rgb(40, 40, 40);
  border-bottom-style: solid;
  border-bottom-color: rgb(238, 0, 0);
  border-bottom-width: 7.5px;
  padding-top: 14px;
  z-index: 10;
}

#logo {
    position: relative;
    bottom: 5px;
    font-size: 30px;
    padding-left: 8px;
    float: left;
    font-family: bebas;
}

#word-1 {
    color: rgb(0, 154, 205);
}

#word-2 {
    color: rgb(255, 250, 250);
}

ul#main-links {
  list-style: none;
  margin: 0;
  padding-right: 50px;
  float: right;
  height: 100%;
  border-bottom: 7.5px solid transparent;
  display: block;
font-size: 0;
}

ul#main-links li {
  display: inline-block;
  text-align: center;
  border-bottom-style: solid;
  border-bottom-width: 7.5px;
border-bottom-color: rgb(238, 0, 0);
  color: white;
  font-family: arcon;
  font-size: 18px;
  height: 100%;
    width: 90px;
  position: relative;
  z-index: 2;
}

a:link {
  text-decoration: none;
}

a:visited {
  text-decoration: none;
    color: white;
}

a:active {
  text-decoration: none;
    color: white;
}

a#logo-link {
    text-decoration: none;

}

a#logo-link:visited {
  text-decoration: none;
    color: inherit;
}

a#logo-link:active {
  text-decoration: none;
    color: inherit;
}

ul#main-links > a > li > span.word-position {
  position: relative;
    top: 5px;
}

#menu-icon {
    height: 48px;
    width: 48px;
    display: none;
    cursor: pointer;
    background-image: url("../images/hamburg-white-2.png");
}

#main-container {
    padding-top: 71.4px;
}

@media screen and (min-width: 656px) {
    ul#main-links {
        display: block !important;
    }
}

@media screen and (max-width: 656px) {

    nav {
        height: initial;
    }

    #logo {
        width: 100%;
        float: none;
        padding-left: 0;
        text-align: center;
        bottom: 8px;
    }

    #menu-icon {
        display: inline-block;
/*        float: right;*/
        position: absolute;
        right: 10px;
        top: -2px;
    }

    ul#main-links {
        display: none;
        float: none;
        padding-right: 0;
        padding-left: 0;
        width: 100%;
    }

    ul#main-links li {
        width: 100%;
        display: block;
        border: none;
        padding: 10px 0;
    }

    ul#main-links li:not(.last-child) {
        border-bottom-style: solid;
        border-bottom-color: rgb(238, 0, 0);
        border-bottom-width: 2.5px;
    }

    ul#main-links > a > li > span.word-position {
        top: 0px;
    }

    #main-container {
        padding-top: 62.4px;
    }
}

@media screen and (max-width: 400px) {
   #logo {
        bottom: 7.5px;
        font-size: 23px;
        padding-left: 10px;
        text-align: left;
    }

    #menu-icon {
        height: 32px;
        width: 32px;
        background-image: url("../images/hamburg-white-1.png");
        top: 0.4px;
        right: 20px;
    }

    #main-container {
        padding-top: 52.4px;
    }
}

/* ----INTORDUCTION---- */

#introductory-background {
    background-image: url('../images/eternity-1024x768.jpg');
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 100%;
/*    min-height: 527px;*/
    height: 90vh;
    background-size: 100% 100%;
    overflow: auto;
}

#introductory-overlay {
    display: table;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}

#introductory-content {
    margin-left: auto;
    margin-right: auto;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

#introductory-container {
    position: relative;
    bottom: 60px;
}

h1#role-header {
    display: block;
    position: relative;
    right: 5em;
    opacity: 0;
    font-size: 48px;
    color: rgb(255, 250, 250);
}

h3#role-support-text {
    display: block;
    opacity: 0;
    position: relative;
    top: 20px;
    font-size: 30px;
    color: rgb(255, 250, 250);
}

#read-more {
    border-radius: 38px;
    background-color: rgb(255, 250, 250);
    padding: 0.5em 1.5em;
    font-size: 24px;
    cursor: pointer;
}

@media screen and (max-width: 656px) {

    #introductory-container {
        bottom: 60px;
    }

    h1#role-header {
        font-size: 37px;
    }

    h3#role-support-text {
        top: 15px;
        font-size: 24px;
    }

    #read-more {
        font-size: 19px;
    }
}

@media screen and (max-width: 400px) {

    #introductory-container {
        bottom: 72.5px;
    }

   h1#role-header {
        font-size: 28px;
    }

    h3#role-support-text {
        top: 11px;
        font-size: 20px;
    }

    #read-more {
        font-size: 16px;
    }
}

/* -------------------- */
/* -------ABOUT-------- */

#about-section {
    width: 100%;
    height: 500px;
    background-color: rgb(131, 111, 235);
}

#photo-frame {
    margin: 0 auto;
    background-color: royalblue;
    width: 180px;
    height: 180px;
    border-radius: 100px;
    border-style: solid;
    border-color: beige;
    border-width: 7.5px;
    z-index: 2;
}

#photo-frame > #picture {
    width: 100%;
    height: 100%;
    background-image: url('../images/Ed.png');
    border-radius: 100px;
}

#about-section > #about-text-container {
    margin: 0 auto;
    width: 80%;
}

#about-section > #about-text-container > p {
    margin: 0;
    text-align: center;
/*    padding: 0 3rem;*/
    font-size: 22px;
}

#about-section > #about-text-container > p.side-by-side {
/*    display: inline-block;*/
    width: 45%;
    text-align: justify;
}

#about-section > #about-text-container > p#about-left-side {
    float: left;
}

#about-section > #about-text-container > p#about-right-side{
    float: right;
}

@media screen and (max-width: 868px) {
    #about-section > #about-text-container > p.side-by-side {
    /*    display: inline-block;*/
        width: 100%;
    }

    #about-section > #about-text-container > p#about-left-side {
        float: none;
        padding-bottom: 1.5rem;
    }

    #about-section > #about-text-container > p#about-right-side{
        float: none;
    }
}

@media screen and (max-width: 656px) {
    #photo-frame {
        width: 150px;
        height: 150px;
    }

    #about-section > #about-text-container {
        width: 90%;
    }

    #about-section > #about-text-container > p {
        text-align: justify;
        padding: 0 1.5rem;
        font-size: 20px;
    }
}

@media screen and (max-width: 400px) {
    #photo-frame {
        width: 125px;
        height: 125px;
    }

    #about-section > #about-text-container {
        width: 100%;
    }

    #about-section > #about-text-container > p {
        padding: 0 0.5rem;
        font-size: 18px;
    }
}

/* -------------------- */
/* -------FOOTER------- */

footer {
    width: 100%;
    background-color: black;
}

footer > p#footer-text {
    margin: 0;
    text-align: center;
    font-family: arial;
    color: rgb(169, 169, 169);
    padding: 20px;
    width: 100%;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

/* -------------------- */

.no-select {
    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none;   /* Safari */
    -khtml-user-select: none;    /* Konqueror HTML */
    -moz-user-select: none;      /* Firefox */
    -ms-user-select: none;       /* Internet Explorer/Edge */
    user-select: none;           /* Non-prefixed version, currently supported by Chrome and Opera */
}

.clearfix:before,
.clearfix:after {
    content: " ";
    display: table;
}
.clearfix:after {
    clear: both;
}
.clearfix {
    *zoom: 1;
}


问:
On core_cm4.h why is there casting like ((uint32_t)(int32_t)IRQn)?
In the following code from core_cm4.h why is there a double cast ((uint32_t)(int32_t)IRQn)?

For example in the following function:

```<code>__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
  NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
</code>```

What is the purpose of this?

答:
Since CM4 software implements negative interrupt sources for core, you have to cast value first to 32bit signed integer and later to unsigned 32bit to make proper right shift with padding zeros on the left side of number.

CM4 uses -15 to -1 as CM4-Core sources and from 0 to next as vendor specific sources.

Body:
In the following code from core_cm4.h why is there a double cast ((uint32_t)(int32_t)IRQn)?

For example in the following function:

__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
  NVIC->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}

What is the purpose of this?