问:
Whitelisting inline script with csp sha-256 in firefox
I can not get whitelisting by checksum to work in firefox (52.0.2, windows). Firefox supports content security policy version 2 according to caniuse, so checksumming should be supported.

When chrome blocks an inline script, it prints the needed sha-256 to console.
Adding it to the csp rules successfully whitelists the script.
The checksum is also identical to the one calculated at
https://report-uri.io/home/hash

But firefox refuse to accept it.

I noted that the example in the MDN docs is using base-16 as opposed to base-64 encoding for the checksum.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src

But even with the MDN example I get the same results. (Also chrome rejects with the base-16 encoding). I tried a bunch of variations on the following:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy"
          content="script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'">
    <title>Hello CSP</title>

```

Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'”). Source: var inline = 1;.

答:
I couldn't put this one completely to rest since there was obviously something strange and confusing going on. And I discovered something interesting:

Take a valid sha-256 that works for Chrome and Firefox.

Replace each + with -, and each / with _.

Voila! You have a checksum that works with Chrome but not Firefox. Judging by the Base64 variants, this format is not unreasonable.

It turns out that the Dartium browser, based on Chrome 45, emits the checksum in the "alternative format," which is likely how it got onto my clipboard.

This only works with Chrome:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'sha256-LqkgOOr2rKDFd7Yl4hZ4H8nB0Stbc-RDo573pA7E/XU='">

    <title>Hello CSP</title>

```

Body:
I can not get whitelisting by checksum to work in firefox (52.0.2, windows). Firefox supports content security policy version 2 according to caniuse, so checksumming should be supported.

When chrome blocks an inline script, it prints the needed sha-256 to console.
Adding it to the csp rules successfully whitelists the script.
The checksum is also identical to the one calculated at
https://report-uri.io/home/hash

But firefox refuse to accept it.

I noted that the example in the MDN docs is using base-16 as opposed to base-64 encoding for the checksum.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src

But even with the MDN example I get the same results. (Also chrome rejects with the base-16 encoding). I tried a bunch of variations on the following:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy"
          content="script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'">
    <title>Hello CSP</title>

Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'”). Source: var inline = 1;.

Body:
I couldn't put this one completely to rest since there was obviously something strange and confusing going on. And I discovered something interesting:

Take a valid sha-256 that works for Chrome and Firefox.

Replace each + with -, and each / with _.

Voila! You have a checksum that works with Chrome but not Firefox. Judging by the Base64 variants, this format is not unreasonable.

It turns out that the Dartium browser, based on Chrome 45, emits the checksum in the "alternative format," which is likely how it got onto my clipboard.

This only works with Chrome:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'sha256-LqkgOOr2rKDFd7Yl4hZ4H8nB0Stbc-RDo573pA7E/XU='">

    <title>Hello CSP</title>

    <script type="text/javascript">alert("running");</script>
</head>
</html>


来源: stackexchange

问:
How can I make a "for-loop" with a specific number of loops in Qweb?
I would like to make a loop to print elements an exact amount of times. Something like this:

```<code><t t-for="o.label_qty" >
...
</t>
</code>```

Where o.label_qty is an integer number.

But I can use only a t-foreach loop in qweb:

```<code><t t-foreach="o.pack_operation_ids" t-as="l" >
...
</t>
</code>```

Is there a way to do this?

If not I'm thinking the only solution is to create a dummy list with o.label_qty elements and write it in the foreach.

答:
range() function will raise error for floating value.

For example:

```<code>>>>a=1.0
>>>range(a)
>>>Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   TypeError: range() integer end argument expected, got float.
</code>```

For dynamic variable loops, there are two possibility for looping with specific number.

Integer number (as answered by @Daniel Reis)

Float number (try with following)

```<code><t t-set="i" t-value="int(o.label_qty)"/>
<t t-foreach="range(i)" t-as="l">
...
</t>
</code>```

for more details of range() function.

ContentLicense: CC BY-SA 3.0

Body:
I would like to make a loop to print elements an exact amount of times. Something like this:

<t t-for="o.label_qty" >
...
</t>

Where o.label_qty is an integer number.

But I can use only a t-foreach loop in qweb:

<t t-foreach="o.pack_operation_ids" t-as="l" >
...
</t>

Is there a way to do this?

If not I'm thinking the only solution is to create a dummy list with o.label_qty elements and write it in the foreach.

Body:
range() function will raise error for floating value.

For example:

>>>a=1.0
>>>range(a)
>>>Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   TypeError: range() integer end argument expected, got float.

For dynamic variable loops, there are two possibility for looping with specific number.

Integer number (as answered by @Daniel Reis)

Float number (try with following)

<t t-set="i" t-value="int(o.label_qty)"/>
<t t-foreach="range(i)" t-as="l">
...
</t>

for more details of range() function.


问:
MVC Razor DropDownListFor value not set in model
I'm trying to make a razor view that can post a model to my controller.

I've added a dropdown, however platform is always null when i post to my controller.

What am i doing wrong?

This is my view

```<code>@using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @class = "form-horizontal", @id = "form" }))
{
    @{
        var platformList = new List<SelectListItem>() {
            new SelectListItem(){ Value="I", Text="iOS"},
            new SelectListItem(){ Value="A", Text="Android"},
        };
    }
    <div class="form-group">
        @Html.LabelFor(model => model.platform, "Plattform", new { @for = "inputPlatform", @class = "col-lg-3 control-label" })
        <div class="col-lg-9">
            @Html.DropDownListFor(model => model.platform, platformList, new { @class = "form-control", @id = "inputPlatform" })
        </div>
    </div>
}
</code>```

This is my model

```<code>public class RegistrationModel
{
    public String platform { get; set; }
}
</code>```

My Controller

```<code>[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegistrationModel RegistrationModelViewModel)
{

}
</code>```

答:
I couldn't get your view to work. There appears to be a formatting issue with the drop down declaration. It has an extra comma and was missing a end }. I kept getting a parse error, which is odd as you say you can get the post to work.

Anyway, I've created an example below which works and so I hope is of some use.

Model

```<code> public class RegistrationModel
 {
        public string platform { get; set; }
 }
</code>```

View

```<code>@model TestMVC.Models.RegistrationModel

@using (Html.BeginForm("Register", "Register", FormMethod.Post, new { @class = "form-horizontal", @id = "form" }))
{
    var platformList = new List<SelectListItem>() {new SelectListItem(){ Value="I", Text="iOS"}, new SelectListItem(){ Value="A", Text="Android"}};

    <div class="form-group">
        @Html.LabelFor(model => model.platform, "Plattform", new {@for = "inputPlatform", @class = "col-lg-3 control-label"})
        <div class="col-lg-9">
            @Html.DropDownListFor(model => model.platform, platformList, new {@class = "form-control", @id = "inputPlatform"})
        </div>
    </div>

    <button type="submit"> Submit</button>
}
</code>```

Controller

```<code> public class RegisterController : Controller
    {
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegistrationModel model)
        {
            //Do something here;
        }
    }
</code>```

Body:
I'm trying to make a razor view that can post a model to my controller.

I've added a dropdown, however platform is always null when i post to my controller.

What am i doing wrong?

This is my view

@using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @class = "form-horizontal", @id = "form" }))
{
    @{
        var platformList = new List<SelectListItem>() {
            new SelectListItem(){ Value="I", Text="iOS"},
            new SelectListItem(){ Value="A", Text="Android"},
        };
    }

        @Html.LabelFor(model => model.platform, "Plattform", new { @for = "inputPlatform", @class = "col-lg-3 control-label" })

            @Html.DropDownListFor(model => model.platform, platformList, new { @class = "form-control", @id = "inputPlatform" })

}

This is my model

public class RegistrationModel
{
    public String platform { get; set; }
}

My Controller

[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegistrationModel RegistrationModelViewModel)
{

}

Body:
I couldn't get your view to work. There appears to be a formatting issue with the drop down declaration. It has an extra comma and was missing a end }. I kept getting a parse error, which is odd as you say you can get the post to work.

Anyway, I've created an example below which works and so I hope is of some use.

Model

 public class RegistrationModel
 {
        public string platform { get; set; }
 }

View

@model TestMVC.Models.RegistrationModel

@using (Html.BeginForm("Register", "Register", FormMethod.Post, new { @class = "form-horizontal", @id = "form" }))
{
    var platformList = new List<SelectListItem>() {new SelectListItem(){ Value="I", Text="iOS"}, new SelectListItem(){ Value="A", Text="Android"}};

    <div class="form-group">
        @Html.LabelFor(model => model.platform, "Plattform", new {@for = "inputPlatform", @class = "col-lg-3 control-label"})
        <div class="col-lg-9">
            @Html.DropDownListFor(model => model.platform, platformList, new {@class = "form-control", @id = "inputPlatform"})
        </div>
    </div>

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

Controller

 public class RegisterController : Controller
    {
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegistrationModel model)
        {
            //Do something here;
        }
    }


问:
List passed by ref - help me explain this behaviour
Take a look at the following program:

```<code>class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}
</code>```

I assumed myList would have passed by ref, and the output would

```<code>3
4
</code>```

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

```<code>10
50
100
</code>```

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

```<code>100
50
10
</code>```

答:
This link will help you in understanding pass by reference in C#.
Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.

For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.

If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.

(Edit: this is the updated version of the documentation linked above.)

Body:
Take a look at the following program:

class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

I assumed myList would have passed by ref, and the output would

3
4

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

10
50
100

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

100
50
10

ContentLicense: CC BY-SA 4.0


问:
git flow feature name isn't what it seems
I create a feature branch in git bash (windows) with git flow feature start myname.
I get the message:

- A new branch 'feature/myname' was created, based on 'develop'
- You are now on branch 'feature/myname'

but when I type git branch [tab][tab] the name of the feature is FEATURE/myname. Why is the feature part uppercased and what can I do to fix it it?

答:
Try the below steps.

Go to your project folder.
Type "git flow init -f", It will ask you the below details.

```<code>Which branch should be used for bringing forth production releases?
- develop
- master
Branch name for production releases: [master]

Which branch should be used for integration of the "next release"?
- develop
Branch name for "next release" development: [develop]

How to name your supporting branch prefixes?
Feature branches? [FEATURE/]
Bugfix branches? [bugfix/]
Release branches? [release/]
Hotfix branches? [hotfix/]
Support branches? [support/]
Version tag prefix? [v]
</code>```

For "Feature branches? [FEATURE/]" type feature.

Body:
Try the below steps.

Go to your project folder.
Type "git flow init -f", It will ask you the below details.

Which branch should be used for bringing forth production releases?
- develop
- master
Branch name for production releases: [master]

Which branch should be used for integration of the "next release"?
- develop
Branch name for "next release" development: [develop]

How to name your supporting branch prefixes?
Feature branches? [FEATURE/]
Bugfix branches? [bugfix/]
Release branches? [release/]
Hotfix branches? [hotfix/]
Support branches? [support/]
Version tag prefix? [v]

For "Feature branches? [FEATURE/]" type feature.


问:
How to check formatting of a SHA-1 message-digest
I need some basic validation (sanitation checks) to determine if some input is a valid SHA1 sum or just a (random) string. If possible with simple parsing rules or a Regex.

Are there any rules to what a SHA1 sum should adhere? I cannot find any, but from quick tests, all seem to be hexadecimal and around 40 characters long[1].

I am not interested in tests that prove whether or not the SHA-1 sum was made in a secure, properly random or other manner. Just that the format is correct.

I am also not interested in testing that the digest is an actual representation of some message; Just that it has the format of digest in the first place.

For the curious: this is for an application where I build avatars for users based on a.o. their uuid. I don't, however, want to place those uuids in the URL, but obfuscate them a little. So instead of avatars/baa4833d-b962-4ab1-87c5-283c9820eac4.png, we request avatars/5f2a13cb1d84a2e019842cdb8d0c8b03c9e1e414.png. Where 5f2a... is e.g. Digest::SHA1.hexdigest(uuid + "secrect").

On the receiving side, I am adding some basic protection that sends back a 400 bad request whenever something is obviously false. Such as avatars/haxor.png or avatars/traversal../../../../attempt.png. Note that this is a very much simplified example.

[1] Two tests with different outcome:

Using sha1sum on Ubuntu Linux:

```<code>$ echo "hello" | sha1sum | cut -d" " -f1 | wc -c
41
</code>```

using Ruby's Digest:

```<code>Digest::SHA1.hexdigest("hello").length
=> 40
</code>```

Edit: turns out this is me, being stupid, wc-c includes the newline, as kennytm points out in the comments. Still: is it safe to assume it will be 40 characters, always?

答:
SHA-1 has a 160 bits digest

160 bits rendered is 160 / 8 = 20 bytes.

20 bytes rendered in hexadecimal format has a length of 40 chars (digits), two chars for each byte.
Digits can be [0-9a-f]

So the following regex should correctly validate the Sha1sum rendered as a string in hexadecimal format:

/^[0-9a-f]{40}$/

Body:
I need some basic validation (sanitation checks) to determine if some input is a valid SHA1 sum or just a (random) string. If possible with simple parsing rules or a Regex.

Are there any rules to what a SHA1 sum should adhere? I cannot find any, but from quick tests, all seem to be hexadecimal and around 40 characters long[1].

I am not interested in tests that prove whether or not the SHA-1 sum was made in a secure, properly random or other manner. Just that the format is correct.

I am also not interested in testing that the digest is an actual representation of some message; Just that it has the format of digest in the first place.

For the curious: this is for an application where I build avatars for users based on a.o. their uuid. I don't, however, want to place those uuids in the URL, but obfuscate them a little. So instead of avatars/baa4833d-b962-4ab1-87c5-283c9820eac4.png, we request avatars/5f2a13cb1d84a2e019842cdb8d0c8b03c9e1e414.png. Where 5f2a... is e.g. Digest::SHA1.hexdigest(uuid + "secrect").

On the receiving side, I am adding some basic protection that sends back a 400 bad request whenever something is obviously false. Such as avatars/haxor.png or avatars/traversal../../../../attempt.png. Note that this is a very much simplified example.

[1] Two tests with different outcome:

Using sha1sum on Ubuntu Linux:

$ echo "hello" | sha1sum | cut -d" " -f1 | wc -c
41

using Ruby's Digest:

Digest::SHA1.hexdigest("hello").length
=> 40

Edit: turns out this is me, being stupid, wc-c includes the newline, as kennytm points out in the comments. Still: is it safe to assume it will be 40 characters, always?


问:
Edit cells dynamically in html
I want to create an function that when a button is clicked, all the data in the cells in a row will transform into input tag and when i click another button, it displays the entered data. Can someone help me with this? Is there an easier way without using jQuery?

JS:

//Hash Change -------------------------
function showPage(pageId) {
 $(".page").hide();
 $(pageId).show();
}

location.hash = "";
location.hash = "#main";

$(window).on("hashchange", function(){
//console.log("Hash Changed! "+location.hash);
showPage(location.hash);
})

//Number Characters Only -------------------------
function validate(evt) {
 var theEvent = evt || window.event;
   var key = theEvent.keyCode || theEvent.which;
   key = String.fromCharCode( key );
   var regex = /[0-9]|\./;
   if( !regex.test(key) ) {
     theEvent.returnValue = false;
     if(theEvent.preventDefault)
      theEvent.preventDefault();
   }
}

//Global Variables -------------------------
var positionOffered;
var date;
var name;
var cityAddress;
var cellphone1;
var emailAddress;
var dateOfBirth;
var citizenship;
var age;
var gender;

//Age function -------------------------
function submitBday() {
    var dateOfBirth = document.getElementById('myForm').elements['dateOfBirth'].value;
    var birthday = +new Date(dateOfBirth);
 age = ~~((Date.now() - birthday) / (31557600000));
}

//Main function -------------------------
function sendData() {

 positionOffered = document.getElementById('myForm').elements['positionOffered'].value;
 date = document.getElementById('myForm').elements['date'].value;
 name = document.getElementById('myForm').elements['name'].value;
 cityAddress = document.getElementById('myForm').elements['cityAddress'].value;
 cellphone1 = document.getElementById('myForm').elements['cellphone1'].value;
 emailAddress = document.getElementById('myForm').elements['emailAddress'].value;
 citizenship = document.getElementById('myForm').elements['citizenship'].value;
 gender = document.getElementById('gender').value;
 if (gender == "male") {
  gender = "M";
 }
 else if (gender == "female") {
  gender = "F";
 }

 var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
 var cell3 = row.insertCell(2);
 var cell4 = row.insertCell(3);
 var cell5 = row.insertCell(4);
 var cell6 = row.insertCell(5);
 var cell7 = row.insertCell(6);
 var cell8 = row.insertCell(7);
 var cell9 = row.insertCell(8);
 var cell10 = row.insertCell(9);

    cell1.innerHTML = positionOffered;
    cell1.style.textAlign = "center";
    cell1.style.borderBottom = "thick solid black";
 cell1.style.width = "10%";

    cell2.innerHTML = date;
    cell2.style.textAlign = "center";
    cell2.style.borderBottom = "thick solid black";
 cell2.style.width = "10%";

 cell3.innerHTML = name;
 cell3.style.textAlign = "center";
 cell3.style.borderBottom = "thick solid black";
 cell3.style.width = "10%";

 cell4.innerHTML = gender;
 cell4.style.textAlign = "center";
 cell4.style.borderBottom = "thick solid black";
 cell4.style.width = "10%";

 cell5.innerHTML = age;
 cell5.style.textAlign = "center";
 cell5.style.borderBottom = "thick solid black";
 cell5.style.width = "10%";

 cell6.innerHTML = cityAddress;
 cell6.style.textAlign = "center";
 cell6.style.borderBottom = "thick solid black";
 cell6.style.width = "10%";

 cell7.innerHTML = cellphone1;
 cell7.style.textAlign = "center";
 cell7.style.borderBottom = "thick solid black";
 cell7.style.width = "10%";

 cell8.innerHTML = emailAddress;
 cell8.style.textAlign = "center";
 cell8.style.borderBottom = "thick solid black";
 cell8.style.width = "10%";

 cell9.innerHTML = citizenship;
 cell9.style.textAlign = "center";
 cell9.style.borderBottom = "thick solid black";
 cell9.style.width = "10%";

 cell10.innerHTML = "<input type='button' id='edit_button' class='edit' onclick='edit_row();' value='Edit'><input type='button' class='delete' onclick='delete_row(this)' value='Delete'>";
 cell10.style.textAlign = "center";
 cell10.style.borderBottom = "thick solid black";
 cell10.style.width = "10%";

 reset();

}

//Reset -------------------------
function reset(){
 document.getElementById("myForm").reset();
}

//Delete Row --------------------
function delete_row(currElement) {
     var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
     document.getElementById("myTable").deleteRow(parentRowIndex);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
 <html>

  <head>
   <title>BIO - DATA</title>
   <link rel="stylesheet" type="text/css" href="../css/stylesheet.css">
   <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
   <script src="../js/httpcode.jquery.comjquery-1.11.3.min.js"></script>
   <script src="../js/script.js"></script>
  </head>

  <body>

   <div class="container">

    <div id="main" class="page">

     <center>BIO - DATA</center>
     <div class="header">PERSONAL DATA</div>

     <form id="myForm">

      <div class="main">

       <div class="label">
        <br>Position Desired
        <br>Name
        <br>City Address
        <br>Provincial Address
        <br>Telephone
        <br>E-mail Address
        <br>Date of Birth
        <br>Civil Status
       </div>

       <div class="input">
        <br>:<input class="short" type="text" name="positionOffered">
        <br>:<input class="short" type="text" name="name">
        <br>:<input class="long"  type="text" name="cityAddress">
        <br>:<input class="long"  type="text" name="provincialAddress">
        <br>:<input class="short" type="text" name="telephone" maxlength="15" onkeypress='validate(event)'>
        <br>:<input class="short" type="email" name="emailAddress">
        <br>:<input class="short" type="date" name="dateOfBirth" onchange="submitBday()">
        <br>:<select class="short" id="civilStatus">
          <option hidden></option>
          <option value="single">Single</option>
          <option value="married">Married</option>
          <option value="divorced">Divorced</option>
          <option value="widowed">Widowed</option>
          </select>
       </div>

       <div class="label">
        <br>Date
        <br>Sex
        <br>
        <br>
        <br>Cellphone
        <br>
        <br>Place of Birth
        <br>Citizenship
       </div>

       <div class="input">
        <br>:<input class="short" type="date" name="date">
        <br>:<select class="short" id="gender">
          <option hidden></option>
          <option value="male">Male</option>
          <option value="female">Female</option>
          </select>
        <br>
        <br>
        <br>:<input class="short" name="cellphone1" maxlength="12" onkeypress='validate(event)'>
        <br>:<input class="short" name="cellphone2" maxlength="12" onkeypress='validate(event)'>
        <br>:<input class="short" name="placeOfBirth">
        <br>:<input class="short" name="citizenship">
       </div>

      </div>
      <input id="button" type="reset" class="button" value="Reset">
     </form>
     <input id="button" type="submit" value="Submit" onclick="sendData()">
    </div>
   </div>

   <div class="container2">
    <div id="list" class="page">
     <table id="myTable">
      <tr>
       <td class="table">Position Desired</td>
       <td class="table">Date Filled</td>
       <td class="table">Name</td>
       <td class="table">Sex</td>
       <td class="table">Age</td>
       <td class="table">City Address</td>
       <td class="table">Cellphone </td>
       <td class="table">Email Address</td>
       <td class="table">Citizenship</td>
       <td class="table">Edit/Remove</td>
      </tr>
     </table>
     <button>Back</button>
    </div>
   </div>
  </body>
 </html></code>```

答:
I believe this is what you were looking for:

Pressing the Edit Button will turn all the 's into  tags while persisting the data in each tag.

var row = document.querySelector('.row');
var cells = $(row).children('.cell');

var turnInputButton = document.querySelector("button#turnInput");
var saveButton = document.querySelector("#save");

var inputs;

$(turnInputButton).on('click', function() {
  $.each(cells, function(i) {
    if (cells[i].tagName === 'TD') {
      var temp = cells[i].textContent;
      var input = document.createElement("INPUT");
      input.setAttribute("type", "text");
      input.value = temp;
      $(cells[i]).replaceWith(input);

      inputs = $(row).children('input');
    }
  });
});

$(saveButton).on('click', function() {
  $.each(inputs, function(i) {
    if (inputs[i].tagName === 'INPUT') {
      var temp = inputs[i].value;
      var td = document.createElement("TD");
      td.setAttribute("class", "cell");
      td.textContent = temp;
      $(inputs[i]).replaceWith(td);

      cells = $(row).children('.cell');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
  border: 1px solid blue;
  padding: 5px;
}</code>```

      <button id="turnInput">Edit</button>
      <button id="save">Save</button>

          Position Desired
          Date Filled
          Name
          Sex
          Age
          City Address
          Cellphone

  ```

https://jsfiddle.net/waldalvajr/7wahro8n/

Title: Edit cells dynamically in html

Body:
I want to create an function that when a button is clicked, all the data in the cells in a row will transform into input tag and when i click another button, it displays the entered data. Can someone help me with this? Is there an easier way without using jQuery?

JS:

//Hash Change -------------------------
function showPage(pageId) {
 $(".page").hide();
 $(pageId).show();
}

location.hash = "";
location.hash = "#main";

$(window).on("hashchange", function(){
//console.log("Hash Changed! "+location.hash);
showPage(location.hash);
})

//Number Characters Only -------------------------
function validate(evt) {
 var theEvent = evt || window.event;
   var key = theEvent.keyCode || theEvent.which;
   key = String.fromCharCode( key );
   var regex = /[0-9]|\./;
   if( !regex.test(key) ) {
     theEvent.returnValue = false;
     if(theEvent.preventDefault)
      theEvent.preventDefault();
   }
}

//Global Variables -------------------------
var positionOffered;
var date;
var name;
var cityAddress;
var cellphone1;
var emailAddress;
var dateOfBirth;
var citizenship;
var age;
var gender;

//Age function -------------------------
function submitBday() {
    var dateOfBirth = document.getElementById('myForm').elements['dateOfBirth'].value;
    var birthday = +new Date(dateOfBirth);
 age = ~~((Date.now() - birthday) / (31557600000));
}

//Main function -------------------------
function sendData() {

 positionOffered = document.getElementById('myForm').elements['positionOffered'].value;
 date = document.getElementById('myForm').elements['date'].value;
 name = document.getElementById('myForm').elements['name'].value;
 cityAddress = document.getElementById('myForm').elements['cityAddress'].value;
 cellphone1 = document.getElementById('myForm').elements['cellphone1'].value;
 emailAddress = document.getElementById('myForm').elements['emailAddress'].value;
 citizenship = document.getElementById('myForm').elements['citizenship'].value;
 gender = document.getElementById('gender').value;
 if (gender == "male") {
  gender = "M";
 }
 else if (gender == "female") {
  gender = "F";
 }

 var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
 var cell3 = row.insertCell(2);
 var cell4 = row.insertCell(3);
 var cell5 = row.insertCell(4);
 var cell6 = row.insertCell(5);
 var cell7 = row.insertCell(6);
 var cell8 = row.insertCell(7);
 var cell9 = row.insertCell(8);
 var cell10 = row.insertCell(9);

    cell1.innerHTML = positionOffered;
    cell1.style.textAlign = "center";
    cell1.style.borderBottom = "thick solid black";
 cell1.style.width = "10%";

    cell2.innerHTML = date;
    cell2.style.textAlign = "center";
    cell2.style.borderBottom = "thick solid black";
 cell2.style.width = "10%";

 cell3.innerHTML = name;
 cell3.style.textAlign = "center";
 cell3.style.borderBottom = "thick solid black";
 cell3.style.width = "10%";

 cell4.innerHTML = gender;
 cell4.style.textAlign = "center";
 cell4.style.borderBottom = "thick solid black";
 cell4.style.width = "10%";

 cell5.innerHTML = age;
 cell5.style.textAlign = "center";
 cell5.style.borderBottom = "thick solid black";
 cell5.style.width = "10%";

 cell6.innerHTML = cityAddress;
 cell6.style.textAlign = "center";
 cell6.style.borderBottom = "thick solid black";
 cell6.style.width = "10%";

 cell7.innerHTML = cellphone1;
 cell7.style.textAlign = "center";
 cell7.style.borderBottom = "thick solid black";
 cell7.style.width = "10%";

 cell8.innerHTML = emailAddress;
 cell8.style.textAlign = "center";
 cell8.style.borderBottom = "thick solid black";
 cell8.style.width = "10%";

 cell9.innerHTML = citizenship;
 cell9.style.textAlign = "center";
 cell9.style.borderBottom = "thick solid black";
 cell9.style.width = "10%";

 cell10.innerHTML = "<input type='button' id='edit_button' class='edit' onclick='edit_row();' value='Edit'><input type='button' class='delete' onclick='delete_row(this)' value='Delete'>";
 cell10.style.textAlign = "center";
 cell10.style.borderBottom = "thick solid black";
 cell10.style.width = "10%";

 reset();

}

//Reset -------------------------
function reset(){
 document.getElementById("myForm").reset();
}

//Delete Row --------------------
function delete_row(currElement) {
     var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
     document.getElementById("myTable").deleteRow(parentRowIndex);
}

<!DOCTYPE html>

   <title>BIO - DATA</title>
   <link rel="stylesheet" type="text/css" href="../css/stylesheet.css">

     BIO - DATA

PERSONAL DATA

     <form id="myForm">

Position Desired

Name

City Address

Provincial Address

Telephone

E-mail Address

Date of Birth

Civil Status

:<input class="short" type="text" name="positionOffered">

:<input class="short" type="text" name="name">

:<input class="long"  type="text" name="cityAddress">

:<input class="long"  type="text" name="provincialAddress">

:<input class="short" type="text" name="telephone" maxlength="15" onkeypress='validate(event)'>

:<input class="short" type="email" name="emailAddress">

:<input class="short" type="date" name="dateOfBirth" onchange="submitBday()">

:<select class="short" id="civilStatus">
          <option hidden></option>
          <option value="single">Single</option>
          <option value="married">Married</option>
          <option value="divorced">Divorced</option>
          <option value="widowed">Widowed</option>
          </select>

Date

Sex

Cellphone

Place of Birth

Citizenship

:<input class="short" type="date" name="date">

:<select class="short" id="gender">
          <option hidden></option>
          <option value="male">Male</option>
          <option value="female">Female</option>
          </select>

:<input class="short" name="cellphone1" maxlength="12" onkeypress='validate(event)'>

:<input class="short" name="cellphone2" maxlength="12" onkeypress='validate(event)'>

:<input class="short" name="placeOfBirth">

:<input class="short" name="citizenship">

      <input id="button" type="reset" class="button" value="Reset">
     </form>
     <input id="button" type="submit" value="Submit" onclick="sendData()">

       Position Desired
       Date Filled
       Name
       Sex
       Age
       City Address
       Cellphone
       Email Address
       Citizenship
       Edit/Remove

     <button>Back</button>

Body:
I believe this is what you were looking for:

Pressing the Edit Button will turn all the 's into  tags while persisting the data in each tag.

var row = document.querySelector('.row');
var cells = $(row).children('.cell');

var turnInputButton = document.querySelector("button#turnInput");
var saveButton = document.querySelector("#save");

var inputs;

$(turnInputButton).on('click', function() {
  $.each(cells, function(i) {
    if (cells[i].tagName === 'TD') {
      var temp = cells[i].textContent;
      var input = document.createElement("INPUT");
      input.setAttribute("type", "text");
      input.value = temp;
      $(cells[i]).replaceWith(input);

      inputs = $(row).children('input');
    }
  });
});

$(saveButton).on('click', function() {
  $.each(inputs, function(i) {
    if (inputs[i].tagName === 'INPUT') {
      var temp = inputs[i].value;
      var td = document.createElement("TD");
      td.setAttribute("class", "cell");
      td.textContent = temp;
      $(inputs[i]).replaceWith(td);

      cells = $(row).children('.cell');
    }
  });
});

td {
  border: 1px solid blue;
  padding: 5px;
}

<body>

  <div class="container2">
    <div id="list" class="page">
      <button id="turnInput">Edit</button>
      <button id="save">Save</button>
      <table id="myTable">
        <tr class="row">
          <td class="cell">Position Desired</td>
          <td class="cell">Date Filled</td>
          <td class="cell">Name</td>
          <td class="cell">Sex</td>
          <td class="cell">Age</td>
          <td class="cell">City Address</td>
          <td class="cell">Cellphone </td>
        </tr>
      </table>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

  <script src="app.js"></script>

https://jsfiddle.net/waldalvajr/7wahro8n/


问:
How to make checkbox selected during rendering
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

```<code><input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

and

```<code>//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

答:
Why you want check it after render? If you want it by default you can get it using "checked" html attribute.

If you need this way (i dont know the reasoning behind), if using $(document).ready() or $(window).load() are not working, have you tried to use a timeout?

```<code>$(document).ready(function(){
    setTimeout(function(){
        $("#chkAll").prop("checked",true); // I prefer the jQuery way, since you are using it, but you can use native js if you prefer
    },50);
})
</code>```

This will create a 50ms delay and maybe works for you

Body:
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

<input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

and

//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

Body:
Why you want check it after render? If you want it by default you can get it using "checked" html attribute.

If you need this way (i dont know the reasoning behind), if using $(document).ready() or $(window).load() are not working, have you tried to use a timeout?

$(document).ready(function(){
    setTimeout(function(){
        $("#chkAll").prop("checked",true); // I prefer the jQuery way, since you are using it, but you can use native js if you prefer
    },50);
})

This will create a 50ms delay and maybe works for you


问:
Domain Driven Design: Handling complex entities with many states and relations (Real Estate)
So I'm fairly new to DDD and am trying to build a scalable and flexible system for my current employer (Real Estate Agency) that will help us speed up internal company procedures.

As stated, we're in Real Estate. I'm trying to define our UL and am having problems conceptualising certain complex entities.

For example: in Real Estate, a 'Property Consultant' will visit a potential 'Client's home and provide an 'Appraisal' on their 'Property'. When listed, this 'Appraisal' becomes a 'Listing' which can also become a 'Sold Property' or a 'Withdrawn Property'. There are so many different states in which a 'Property' can be. Should I be defining a 'Property' as an entity or should each separate state (Appraisal, Listing, Sold, Withdrawn) be defined as a separate entity?

The problem gets more complex though, when we add 'Clients' into the mix. A client can be a 'Property Owner', 'Purchaser', 'Buyer', 'Tennant', 'Investor', 'Developer' and many, many more. On top of that, a client can be a combination of more than one of these! Again, should 'Client' be the entity and all these states be represented just as properties of the 'Client' entity or should they be separate entities?

On top of that, what about the relationship of 'Client' entities to 'Property' entities. Its a many-to-many relationship and I see no easy way of combining it. DDD seems to state that an entity should be unique in its existence, therefore meaning that I can't have a 'Property' entity with a list of attached 'Client' entities without making my 'Client' entity behave like a VO. Vice versa when considering 'Client' entities with a list of their associated 'Property' entities.

I've been reading for 8 hours a day for the last 2 weeks on this subject. Its very confusing and I'm yet to untangle the mess. Any help and pointers in the right direction would be greatly appreciated!

答:
I don't do PHP, but I can suggest how to model your classes:

Clients and Roles

Create an interface (or abstract
class) called Role.  Role has a
reference back to a Client

Inherit the following classes from
Role:   Owner, Purchaser, Buyer, Tennant, Investor

For each of these concrete Role classes,
extend the members as necessary (e.g. a Tennant
may have MonthlyRent)

Add a list of Roles to your Client.
Whenever a new Role is added to
Client.Roles, the Role should
reference the Client

The important part: Most of your classes should reference the individual Role object, instead of the Client.  You can access the Client via the Role.

Property states and transitions

Create an interface (or abstract class) called PropertyEvent.
Add a timestamp property to it called OccurredAt.

Inherit the following classes from  PropertyEvent: Appraisal, Listing, Sold, Withdrawn

For each of these concrete PropertyEvent classes, extend the members as necessary (e.g. an
Appraisal will have an associated
AppraisedBy?)

Add a list of PropertyEvents to your
Property.  Whenever the state changes,
create the appropriate Event and add
it to Propery.History.

The important part: This is the notion of a Domain Event. This technique will automatically provide a history of the state changes for the Property.

Note that I haven't focused on entities, or Aggregates, or Value Objects.  You can work those out as you get a better feel for your model.

Hope that helps!

ContentLicense: CC BY-SA 2.5


问:
Ionic 2 reload/refresh comments panel or entire page
I have a post detail page in my IONIC 2 App and there is a comment section, I want whenever there is an approved comment it shows be seen in the recent comment and for this page needs to be reloaded or comment section need to be updated.

Please suggest me the best approach to complete this:-

My comment form html:-

```<code><!-- Comment -->
        <div class="comment">
            <ion-list top_border *ngIf="comments">
                <ion-item text-wrap *ngFor="let comment of comments">
                    <div img_box>
                        <div thumbnail_img>
                            <img [src]="comment.author_avatar_urls[96]">
                        </div >
                        <div class="tag">
                            <h2>{{comment.author_name}}</h2>
                            <span class="blicon-clock"> {{comment.date | date: 'mediumDate'}}</span>
                        </div>
                    </div>
                    <p [innerHTML]="comment.content.rendered"></p>
                </ion-item>
            </ion-list>

            <div id="commentPanel" class="comment_textarea">
                <form (ngSubmit)="PostComment()">
                     <ion-textarea rows="3" [(ngModel)]="usercomment.comment" name="usercomment" placeholder="Write something..."></ion-textarea>
                     <button ion-button>
                      <ion-icon type="submit" ios="ios-arrow-round-forward" md="md-arrow-round-forward"></ion-icon>
                    </button>
                </form>
            </div>
        </div>
        <!-- Comment -->
</code>```

and here is my post function:-

```<code>PostComment() {
        let loader = this.loadingController.create({
            content: "Please wait"
        });
        loader.present();

        let commentdata : { post: number, content: string, author_name: string, author_email: string } = {
            post: this.post.id,
            content: this.usercomment.comment,
            author_name: this.user.user_display_name,
            author_email: this.user.user_email
        };

        this.myService.PostComment(commentdata)
        .subscribe((result) => {
                if(result.status == "approved") {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: "Your comment has been successfully posted.",
                        duration: 2000
                    });
                    toast.present();
                  // TODO Here to page refers
                } else if(result.status == "hold") {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: "Your comment is awaiting approval.",
                        duration: 2000
                    });
                    toast.present();
                } else if(result.message) {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: result.message,
                        duration: 2000
                    });
                    toast.present();
                } else {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: 'There is something wrong, please try again later.',
                        duration: 2000
                    });
                    toast.present();
                }
            this.usercomment.comment = '';
        }, (error) => {
          loader.dismiss();
          let errorMessage = error.json();
          if (errorMessage && errorMessage.message) {
            let message = errorMessage.message.replace(/<(?:.|\n)*?>/gm, '');
            let toast = this.toastController.create({
              message: message,
              duration: 6000,
              position: 'bottom'
            });
            toast.present();
         }
      });
</code>```

Please suggest.

答:
You do not need to refresh page. When the comment is approved, simply push it into comments array.</p>

```<code>[...]
if(result.status == "approved") {
  loader.dismiss();
  let toast = this.toastController.create({
      message: "Your comment has been successfully posted.",
      duration: 2000
  });
  toast.present();
  this.comments.push(commentdata);
}
</code>```

Body:
I have a post detail page in my IONIC 2 App and there is a comment section, I want whenever there is an approved comment it shows be seen in the recent comment and for this page needs to be reloaded or comment section need to be updated.

Please suggest me the best approach to complete this:-

My comment form html:-

            <ion-list top_border *ngIf="comments">
                <ion-item text-wrap *ngFor="let comment of comments">

{{comment.author_name}}

                             {{comment.date | date: 'mediumDate'}}

                </ion-item>
            </ion-list>

                <form (ngSubmit)="PostComment()">
                     <ion-textarea rows="3" [(ngModel)]="usercomment.comment" name="usercomment" placeholder="Write something..."></ion-textarea>
                     <button ion-button>
                      <ion-icon type="submit" ios="ios-arrow-round-forward" md="md-arrow-round-forward"></ion-icon>
                    </button>
                </form>

and here is my post function:-

PostComment() {
        let loader = this.loadingController.create({
            content: "Please wait"
        });
        loader.present();

        let commentdata : { post: number, content: string, author_name: string, author_email: string } = {
            post: this.post.id,
            content: this.usercomment.comment,
            author_name: this.user.user_display_name,
            author_email: this.user.user_email
        };

        this.myService.PostComment(commentdata)
        .subscribe((result) => {
                if(result.status == "approved") {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: "Your comment has been successfully posted.",
                        duration: 2000
                    });
                    toast.present();
                  // TODO Here to page refers
                } else if(result.status == "hold") {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: "Your comment is awaiting approval.",
                        duration: 2000
                    });
                    toast.present();
                } else if(result.message) {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: result.message,
                        duration: 2000
                    });
                    toast.present();
                } else {
                    loader.dismiss();
                    let toast = this.toastController.create({
                        message: 'There is something wrong, please try again later.',
                        duration: 2000
                    });
                    toast.present();
                }
            this.usercomment.comment = '';
        }, (error) => {
          loader.dismiss();
          let errorMessage = error.json();
          if (errorMessage && errorMessage.message) {
            let message = errorMessage.message.replace(/<(?:.|\n)*?>/gm, '');
            let toast = this.toastController.create({
              message: message,
              duration: 6000,
              position: 'bottom'
            });
            toast.present();
         }
      });

Please suggest.

Body:
You do not need to refresh page. When the comment is approved, simply push it into comments array.

[...]
if(result.status == "approved") {
  loader.dismiss();
  let toast = this.toastController.create({
      message: "Your comment has been successfully posted.",
      duration: 2000
  });
  toast.present();
  this.comments.push(commentdata);
}


问:
App not compatible with the device I use to develop it?
I developed and tested my app using various phones and tablets emulators, and 4 real devices : Samsung Galaxy Ace (GT-I8160P) , Samsung Galaxy Tab 2 (GT-P5110 and GT-P3110) and a Storex M977. After 5 months of work and tests, the App works fine on all these devices. So I uploaded it on Google Play. But Google Play indicates that it's not compatible with my tablets. I can't install it using Google Play on my Galaxy Tabs...

I can't figure out what is the problem. I added support-screens section without success. I was a bit desperate so I also added these uses-features with required="false" : GPS, NETWORK, TELEPHONY, WIFI, LOCATION, TOUCHSCREEN even if the app worked fine without these uses-features. Same result. I also removed "TargetSdk". Google Play says that my app is compatible with 2339 devices including some Galaxy Tabs, but not with my tabs. Only the Galaxy Ace can install it from Google Play.

Here is my manifest file (I just replaced package original package name by fr.test.app for confidentiality reasons). What I'm doing wrong ?

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fr.test.app"
android:versionCode="7"
android:versionName="1.2" >

<uses-sdk
    android:minSdkVersion="8"
    />

<supports-screens android:resizeable="true"
              android:smallScreens="true"
              android:normalScreens="true"
              android:largeScreens="true"
              android:xlargeScreens="true"
              android:anyDensity="true"/>

<uses-feature android:name="android.hardware.WIFI" android:required="false" />
<uses-feature android:name="android.hardware.GPS" android:required="false" />
<uses-feature android:name="android.hardware.TELEPHONY" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.LOCATION" android:required="false" />
<uses-feature android:name="android.hardware.NETWORK" android:required="false" />
<uses-feature android:name="android.hardware.TOUCHSCREEN" android:required="false" />

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.CAMERA.FRONT"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<permission android:name="fr.test.app.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="fr.test.app.permission.C2D_MESSAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    >

    <receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <!-- Receives the actual messages. -->
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <!-- Receives the registration id. -->
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="fr.test.app" />
        </intent-filter>
    </receiver>
    <service android:name=".GCMIntentService" />

    <receiver
        android:name=".OnBootReceiver"
        android:enabled="true"
        android:exported="false" android:label="OnBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.MAIN" />
        </intent-filter>
    </receiver>
    <receiver
        android:process=":remote"
        android:name="fr.test.app.Alarm">
    </receiver>
    <receiver
        android:process=":remote"
        android:name="fr.test.app.CamAlarm">
    </receiver>
    <receiver android:name=".MyAdmin" android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin" android:resource="@layout/policies">
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED">
                </action>

            </intent-filter>
        </meta-data>
    </receiver>
    <service
        android:name=".BbSvc" android:enabled="true"
        android:exported="false"
    />

    <service
        android:name=".WpsLoc" android:enabled="true"
        android:exported="false"
    />

    <service
        android:name=".Cam" android:enabled="true"
        android:exported="false"
    />

    <service
        android:name=".MniRec" android:enabled="true"
        android:exported="false"
    />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboardHidden|orientation">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".reminder"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <!--
            <category android:name="android.intent.category.LAUNCHER" />
             <category android:name="android.intent.category.DEFAULT" /> -->
        </intent-filter>
    </activity>
    <provider android:name="fr.test.app.AndroidProvider"
          android:authorities="fr.test.app.AndroidProvider"
          android:exported="false"/>
</application>
</code>```

答:
In some cases Google Play will tell you why the device is not compatible:

Open Google Play on your desktop computer: https://play.google.com/store

Navigate to your app, and click the Install button

Open the dropdown of devices, and see if there's a summary below the incompatible device:

Body:
I developed and tested my app using various phones and tablets emulators, and 4 real devices : Samsung Galaxy Ace (GT-I8160P) , Samsung Galaxy Tab 2 (GT-P5110 and GT-P3110) and a Storex M977. After 5 months of work and tests, the App works fine on all these devices. So I uploaded it on Google Play. But Google Play indicates that it's not compatible with my tablets. I can't install it using Google Play on my Galaxy Tabs...

I can't figure out what is the problem. I added support-screens section without success. I was a bit desperate so I also added these uses-features with required="false" : GPS, NETWORK, TELEPHONY, WIFI, LOCATION, TOUCHSCREEN even if the app worked fine without these uses-features. Same result. I also removed "TargetSdk". Google Play says that my app is compatible with 2339 devices including some Galaxy Tabs, but not with my tabs. Only the Galaxy Ace can install it from Google Play.

Here is my manifest file (I just replaced package original package name by fr.test.app for confidentiality reasons). What I'm doing wrong ?

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fr.test.app"
android:versionCode="7"
android:versionName="1.2" >

<uses-sdk
    android:minSdkVersion="8"
    />

<supports-screens android:resizeable="true"
              android:smallScreens="true"
              android:normalScreens="true"
              android:largeScreens="true"
              android:xlargeScreens="true"
              android:anyDensity="true"/>

<uses-feature android:name="android.hardware.WIFI" android:required="false" />
<uses-feature android:name="android.hardware.GPS" android:required="false" />
<uses-feature android:name="android.hardware.TELEPHONY" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.LOCATION" android:required="false" />
<uses-feature android:name="android.hardware.NETWORK" android:required="false" />
<uses-feature android:name="android.hardware.TOUCHSCREEN" android:required="false" />

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.CAMERA.FRONT"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<permission android:name="fr.test.app.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="fr.test.app.permission.C2D_MESSAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    >

    <receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>

            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="fr.test.app" />
        </intent-filter>
    </receiver>
    <service android:name=".GCMIntentService" />

    <receiver
        android:name=".OnBootReceiver"
        android:enabled="true"
        android:exported="false" android:label="OnBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.MAIN" />
        </intent-filter>
    </receiver>
    <receiver
        android:process=":remote"
        android:name="fr.test.app.Alarm">
    </receiver>
    <receiver
        android:process=":remote"
        android:name="fr.test.app.CamAlarm">
    </receiver>
    <receiver android:name=".MyAdmin" android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin" android:resource="@layout/policies">
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED">
                </action>

            </intent-filter>
        </meta-data>
    </receiver>
    <service
        android:name=".BbSvc" android:enabled="true"
        android:exported="false"
    />

    <service
        android:name=".WpsLoc" android:enabled="true"
        android:exported="false"
    />

    <service
        android:name=".Cam" android:enabled="true"
        android:exported="false"
    />

    <service
        android:name=".MniRec" android:enabled="true"
        android:exported="false"
    />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboardHidden|orientation">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".reminder"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

        </intent-filter>
    </activity>
    <provider android:name="fr.test.app.AndroidProvider"
          android:authorities="fr.test.app.AndroidProvider"
          android:exported="false"/>
</application>


问:
High-frequency scheduling with Python 3
I've used APScheduler in the past to schedule function calls every X seconds with great success. However, I'm looking to call a function multiple times per second, which neither the IntervalTrigger or CronTrigger APScheduler functions seem to allow.

Is there a simple way to set the interval to a fraction of second, or will I need to look at threading options?

答: With APScheduler, providing sub-second accuracy is not very feasible. Do you really need the extra features provided by the library? If not, you could just have a loop where you use time.sleep().</p>

Title: High-frequency scheduling with Python 3


问:
How to set color of text using xlwt
I haven't been able to find documentation on how to set the color of text. How would the following be done in xlwt?

```<code>style = xlwt.XFStyle()

# bold
font = xlwt.Font()
font.bold = True
style.font = font

# background color
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = xlwt.Style.colour_map['pale_blue']
style.pattern = pattern

# color of text
???
</code>```

Another way I have tried, where I've been able to set the font color but not the background color is:

```<code>style = xlwt.easyxf('font: bold 1, color red;')
</code>```

答:
style = xlwt.easyxf('pattern: pattern solid, fore_colour light_blue;'
                                  'font: colour white, bold True;')</p>

```<code>    sheet.write(row, 0, "Code", style)
    sheet.write(row, 1, "Name", style)
    sheet.write(row, 2, "bottle",style)
</code>```

Title: How to set color of text using xlwt

Body:
I haven't been able to find documentation on how to set the color of text. How would the following be done in xlwt?

style = xlwt.XFStyle()

# bold
font = xlwt.Font()
font.bold = True
style.font = font

# background color
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = xlwt.Style.colour_map['pale_blue']
style.pattern = pattern

# color of text
???

Another way I have tried, where I've been able to set the font color but not the background color is:

style = xlwt.easyxf('font: bold 1, color red;')

Body:
style = xlwt.easyxf('pattern: pattern solid, fore_colour light_blue;'
                                  'font: colour white, bold True;')

    sheet.write(row, 0, "Code", style)
    sheet.write(row, 1, "Name", style)
    sheet.write(row, 2, "bottle",style)


问:
Python Optimized Comparison Between List of Dict
I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it.

I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x': VALUE, 'y': VALUE, 'z': VALUE, 'rad': VALUE}].

The size of both lists can run upwards of 100,000 items each.

My current code is posted below, but it's very inefficient.

```<code>    filteredList = []
    for i in range(len(sList)):

            minx = (sList[i]['x']) - (sList[i]['radius'])
            maxx = (sList[i]['x']) + (sList[i]['radius'])
            miny = (sList[i]['y']) - (sList[i]['radius'])
            maxy = (sList[i]['y']) + (sList[i]['radius'])
            minz = (sList[i]['z']) - (sList[i]['radius'])
            maxz = (sList[i]['z']) + (sList[i]['radius'])

            for j in range(len(nList)):
                    if minx <= nList[j]['x'] <= maxx:
                            if miny <= nList[j]['y'] <= maxy:
                                    if minz <= nList[j]['z'] <= maxz:
                                            tmpRad = findRadius(sList[i],nList[j])
                                            if tmpRad <= sList[i]['radius']:
                                                    filteredList.append(int(nList[j]['num']))
</code>```

I'm at a loss and appreciate any ideas.

Edit: Adding extra information about the data format.

List A (nList) -- defines nodes, with locations x,y,z, and identifier num

[{'y': 0.0, 'x': 0.0, 'num': 1.0, 'z': 0.0},

{'y': 0.0, 'x': 1.0, 'num': 2.0, 'z': 0.0},

{'y': 0.0, 'x': 2.0, 'num': 3.0, 'z': 0.0},

{'y': 0.0, 'x': 3.0, 'num': 4.0, 'z': 0.0},

{'y': 0.0, 'x': 4.0, 'num': 5.0, 'z': 0.0},

{'y': 0.0, 'x': 5.0, 'num': 6.0, 'z': 0.0},

{'y': 0.0, 'x': 6.0, 'num': 7.0, 'z': 0.0},

{'y': 0.0, 'x': 7.0, 'num': 8.0, 'z': 0.0},

{'y': 0.0, 'x': 8.0, 'num': 9.0, 'z': 0.0},

{'y': 0.0, 'x': 9.0, 'num': 10.0, 'z': 0.0}]

List B (sList) -- defines spheres using x,y,z, radius

[{'y': 18.0, 'x': 25.0, 'z': 26.0, 'radius': 0.0056470000000000001},

{'y': 29.0, 'x': 23.0, 'z': 45.0, 'radius': 0.0066280000000000002},

{'y': 46.0, 'x': 29.0, 'z': 13.0, 'radius': 0.014350999999999999},

{'y': 0.0, 'x': 20.0, 'z': 25.0, 'radius': 0.014866000000000001},

{'y': 27.0, 'x': 31.0, 'z': 18.0, 'radius': 0.018311999999999998},

{'y': 10.0, 'x': 36.0, 'z': 46.0, 'radius': 0.024702000000000002},

{'y': 27.0, 'x': 13.0, 'z': 48.0, 'radius': 0.027300999999999999},

{'y': 14.0, 'x': 1.0, 'z': 13.0, 'radius': 0.033889000000000002},

{'y': 31.0, 'x': 20.0, 'z': 11.0, 'radius': 0.034118999999999997},

{'y': 23.0, 'x': 28.0, 'z': 8.0, 'radius': 0.036683}]

答:
Actually, you could save all that by:

```<code>filteredList = [int(node['num']) for sphere in sList \
    for node in nList if findRadius(sphere,node)<=sphere['radius']]
</code>```

If the distance from a point to a sphere's globe is less than the sphere's radius, then I guess we can say it is in the sphere, right?

I assume findRadius is defined like:

```<code>def findRadius(sphere,node):
    return ((node['x']-sphere['x'])**2 + \
            (node['y']-sphere['y'])**2 + \
            (node['z']-sphere['z'])**2)**.5
</code>```

Body:
I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it.

I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x': VALUE, 'y': VALUE, 'z': VALUE, 'rad': VALUE}].

The size of both lists can run upwards of 100,000 items each.

My current code is posted below, but it's very inefficient.

    filteredList = []
    for i in range(len(sList)):

            minx = (sList[i]['x']) - (sList[i]['radius'])
            maxx = (sList[i]['x']) + (sList[i]['radius'])
            miny = (sList[i]['y']) - (sList[i]['radius'])
            maxy = (sList[i]['y']) + (sList[i]['radius'])
            minz = (sList[i]['z']) - (sList[i]['radius'])
            maxz = (sList[i]['z']) + (sList[i]['radius'])

            for j in range(len(nList)):
                    if minx <= nList[j]['x'] <= maxx:
                            if miny <= nList[j]['y'] <= maxy:
                                    if minz <= nList[j]['z'] <= maxz:
                                            tmpRad = findRadius(sList[i],nList[j])
                                            if tmpRad <= sList[i]['radius']:
                                                    filteredList.append(int(nList[j]['num']))

I'm at a loss and appreciate any ideas.

Edit: Adding extra information about the data format.

List A (nList) -- defines nodes, with locations x,y,z, and identifier num

[{'y': 0.0, 'x': 0.0, 'num': 1.0, 'z': 0.0},

{'y': 0.0, 'x': 1.0, 'num': 2.0, 'z': 0.0},

{'y': 0.0, 'x': 2.0, 'num': 3.0, 'z': 0.0},

{'y': 0.0, 'x': 3.0, 'num': 4.0, 'z': 0.0},

{'y': 0.0, 'x': 4.0, 'num': 5.0, 'z': 0.0},

{'y': 0.0, 'x': 5.0, 'num': 6.0, 'z': 0.0},

{'y': 0.0, 'x': 6.0, 'num': 7.0, 'z': 0.0},

{'y': 0.0, 'x': 7.0, 'num': 8.0, 'z': 0.0},

{'y': 0.0, 'x': 8.0, 'num': 9.0, 'z': 0.0},

{'y': 0.0, 'x': 9.0, 'num': 10.0, 'z': 0.0}]

List B (sList) -- defines spheres using x,y,z, radius

[{'y': 18.0, 'x': 25.0, 'z': 26.0, 'radius': 0.0056470000000000001},

{'y': 29.0, 'x': 23.0, 'z': 45.0, 'radius': 0.0066280000000000002},

{'y': 46.0, 'x': 29.0, 'z': 13.0, 'radius': 0.014350999999999999},

{'y': 0.0, 'x': 20.0, 'z': 25.0, 'radius': 0.014866000000000001},

{'y': 27.0, 'x': 31.0, 'z': 18.0, 'radius': 0.018311999999999998},

{'y': 10.0, 'x': 36.0, 'z': 46.0, 'radius': 0.024702000000000002},

{'y': 27.0, 'x': 13.0, 'z': 48.0, 'radius': 0.027300999999999999},

{'y': 14.0, 'x': 1.0, 'z': 13.0, 'radius': 0.033889000000000002},

{'y': 31.0, 'x': 20.0, 'z': 11.0, 'radius': 0.034118999999999997},

{'y': 23.0, 'x': 28.0, 'z': 8.0, 'radius': 0.036683}]

Body:
Actually, you could save all that by:

filteredList = [int(node['num']) for sphere in sList \
    for node in nList if findRadius(sphere,node)<=sphere['radius']]

If the distance from a point to a sphere's globe is less than the sphere's radius, then I guess we can say it is in the sphere, right?

I assume findRadius is defined like:

def findRadius(sphere,node):
    return ((node['x']-sphere['x'])**2 + \
            (node['y']-sphere['y'])**2 + \
            (node['z']-sphere['z'])**2)**.5


问:
How to connect two stages of circles using CSS
Folks,

We are trying to connect two lines with different stages but it seems stage2 is moving to different line.

How to connect these two stages(circles) with lines so that they appear on same line. As of now always it is coming to new line.

Code below :

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><font face="Times New Roman" size="1">stage1</font>
<span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
</span>
<hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
<font face="Times New Roman" size="1">stage2</font>
</span>
<span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
</span>
<hr style="height:1px; margin-top:-11px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px"></code>```

答:
You say there in your inline-style:

```<code><span class="circle" style="display:block">
<span class="circle-inner" style="display:block"></span>
</code>```

Block elements cause adjacent elements to be placed on a new line. Instead, try using display:inline-block:

```<code><span class="circle" style="display:inline-block">
<span class="circle-inner" style="display:inline-block"></span>
</code>```

By the way, there is no reason to use an inline-style at all, you can add this definition to your style in the head.

Body:
Folks,

We are trying to connect two lines with different stages but it seems stage2 is moving to different line.

How to connect these two stages(circles) with lines so that they appear on same line. As of now always it is coming to new line.

Code below :

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}

stage1

stage2

Body:
You say there in your inline-style:

<span class="circle" style="display:block">
<span class="circle-inner" style="display:block"></span>

Block elements cause adjacent elements to be placed on a new line. Instead, try using display:inline-block:

<span class="circle" style="display:inline-block">
<span class="circle-inner" style="display:inline-block"></span>

By the way, there is no reason to use an inline-style at all, you can add this definition to your style in the head.


问:
Testing Vue.js components- Laravel Testing
I am looking at testing some Vue.js components, as part of a Laravel application. So, I have a component that is used in a blade template and makes a GET request during the mounted lifecycle hook. Say this request takes 800 ms. Is it possible to use phpunit in this situation- to check the resulting HTML after said request?

I tried using sleep(1) (yes, probably a horrible idea), to give the request time to finish up (not 100% on this methodology), but the expected text was not available on the page after this brief sleep.

Here is what I am hoping to do:

```<code>$this->actingAs($user)
     ->visit('/teams/' . $team->slug . '/players'); // request is made when this route is hit.

$this->see('There are currently no players for this team.')
     ->see('There are currently no temporary players for this team.');
</code>```

The see() calls resulted in error- the HTML was not present. I also checked- through the HTML output by phpunit on error, and all that is available in the HTML is what is inside of the blade template- the Vue component is not rendered at the point in which the see() call is made.

I suppose I am after some advice or direction.

答:
I appreciate that this may not be what you're after or even compatible based on the version of Laravel you're using but have you heard about Laravel Dusk in the latest version (5.4).

https://laravel.com/docs/5.4/dusk

Body:
I am looking at testing some Vue.js components, as part of a Laravel application. So, I have a component that is used in a blade template and makes a GET request during the mounted lifecycle hook. Say this request takes 800 ms. Is it possible to use phpunit in this situation- to check the resulting HTML after said request?

I tried using sleep(1) (yes, probably a horrible idea), to give the request time to finish up (not 100% on this methodology), but the expected text was not available on the page after this brief sleep.

Here is what I am hoping to do:

$this->actingAs($user)
     ->visit('/teams/' . $team->slug . '/players'); // request is made when this route is hit.

$this->see('There are currently no players for this team.')
     ->see('There are currently no temporary players for this team.');

The see() calls resulted in error- the HTML was not present. I also checked- through the HTML output by phpunit on error, and all that is available in the HTML is what is inside of the blade template- the Vue component is not rendered at the point in which the see() call is made.

I suppose I am after some advice or direction.


问:
Calculating aggregate values in a pandas dataframe with multiple columns
I have a Pandas DataFrame with multiple columns.

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
print(df)

first        bar                 baz                 foo                 qux  \
second       one       two       one       two       one       two       one
A      -0.093829 -0.159939 -0.386961 -0.367417  0.625646  1.286186  0.429855
B       0.440266  0.345161  1.798363 -1.265215  0.204303 -1.492993 -1.714360
C       0.689076 -1.211060 -0.265888  0.769467 -0.706941  0.086907 -0.892892

first
second       two
A      -1.006210
B      -0.275578
C      -0.563757
```

<p>I want to calculate the mean and standard deviation, of each column, grouping by the upper column. Once I have calculated the mean and standard deviation I want to double the columns in the lower level, adding to the column name the information related to the statistical operation (mean or standard deviation) as "column name" + "_" + "std/mean".</p>

<pre class="lang-py prettyprint-override"><code>group_cols = df.groupby(df.columns.get_level_values('first'), axis=1)
list_stat_dfs = []
for key, group in group_cols:
    group_descr = group.describe().loc[['mean', 'std'], :]  # Get mean and std from single site
    group_descr.loc[:, (key, 'stats')] = group_descr.index
    group_descr.loc[:, (key, 'first')] = key
    group_descr.columns = group_descr.columns.droplevel(0)  # Remove upper level column (site_name)
    group_descr = group_descr.pivot(columns='stats', index='first')  # Rows to columns
    col_prod = list(product(group_descr.columns.levels[0], group_descr.columns.levels[1]))
    cols = ['_'.join((col[0], col[1])) for col in col_prod]
    group_descr.columns = pd.MultiIndex.from_product(([key], cols))  # From multiple columns to single column
    group_descr.reset_index(inplace=True)
    list_stat_dfs.append(group_descr)

group_descr = pd.concat(list_stat_dfs, axis=1)
print(group_descr)

first       bar                              first       baz            \
         one_mean   one_std  two_mean  two_std        one_mean   one_std
0   bar  0.507185  1.799053 -0.249692  1.41507   baz -0.147664  0.595927

                     first       foo                               first  \
   two_mean   two_std        one_mean   one_std  two_mean   two_std
0  0.160018  1.405113   foo -0.433644  1.245972  0.254995  0.846983   qux

        qux
   one_mean   one_std  two_mean   two_std
0  0.667629  0.315417 -0.757989  0.683273
</code>```

As you can see, I have been able to manage it with a for loop and some line of code. Can someone do the same thing in a more optimized way. I am quite sure that with Pandas, the same thing can be done with few lines of code.

答:
I think you need get mean and std of df, then concat together and reshape by unstack:

```<code>arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))

np.random.seed(1000)
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
print(df)
first        bar                 baz                 foo                 qux  \
second       one       two       one       two       one       two       one
A      -0.804458  0.320932 -0.025483  0.644324 -0.300797  0.389475 -0.107437
B       0.595036 -0.464668  0.667281 -0.806116 -1.196070 -0.405960 -0.182377
C      -0.138422  0.705692  1.271795 -0.986747 -0.334835 -0.099482  0.407192

first
second       two
A      -0.479983
B       0.103193
C       0.919388

df = pd.concat([df.mean(), df.std()], keys=('mean','std')).unstack(1)
df.index =  [[0] * len(df.index), ['_'.join((col[1], col[0])) for col in df.index]]
df = df.unstack()
print (df)
first       bar                                     baz                      \
       one_mean   one_std  two_mean   two_std  one_mean   one_std  two_mean
0     -0.115948  0.700018  0.187319  0.596511  0.637865  0.649139 -0.382846

first                 foo                                     qux           \
        two_std  one_mean   one_std  two_mean   two_std  one_mean  one_std
0      0.894129 -0.610567  0.507346 -0.038656  0.401191  0.039126  0.32095

first
       two_mean   two_std
0      0.180866  0.702911
</code>```

Body:
I have a Pandas DataFrame with multiple columns.

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
print(df)

first        bar                 baz                 foo                 qux  \
second       one       two       one       two       one       two       one
A      -0.093829 -0.159939 -0.386961 -0.367417  0.625646  1.286186  0.429855
B       0.440266  0.345161  1.798363 -1.265215  0.204303 -1.492993 -1.714360
C       0.689076 -1.211060 -0.265888  0.769467 -0.706941  0.086907 -0.892892

first
second       two
A      -1.006210
B      -0.275578
C      -0.563757

I want to calculate the mean and standard deviation, of each column, grouping by the upper column. Once I have calculated the mean and standard deviation I want to double the columns in the lower level, adding to the column name the information related to the statistical operation (mean or standard deviation) as "column name" + "_" + "std/mean".

group_cols = df.groupby(df.columns.get_level_values('first'), axis=1)
list_stat_dfs = []
for key, group in group_cols:
    group_descr = group.describe().loc[['mean', 'std'], :]  # Get mean and std from single site
    group_descr.loc[:, (key, 'stats')] = group_descr.index
    group_descr.loc[:, (key, 'first')] = key
    group_descr.columns = group_descr.columns.droplevel(0)  # Remove upper level column (site_name)
    group_descr = group_descr.pivot(columns='stats', index='first')  # Rows to columns
    col_prod = list(product(group_descr.columns.levels[0], group_descr.columns.levels[1]))
    cols = ['_'.join((col[0], col[1])) for col in col_prod]
    group_descr.columns = pd.MultiIndex.from_product(([key], cols))  # From multiple columns to single column
    group_descr.reset_index(inplace=True)
    list_stat_dfs.append(group_descr)

group_descr = pd.concat(list_stat_dfs, axis=1)
print(group_descr)

first       bar                              first       baz            \
         one_mean   one_std  two_mean  two_std        one_mean   one_std
0   bar  0.507185  1.799053 -0.249692  1.41507   baz -0.147664  0.595927

                     first       foo                               first  \
   two_mean   two_std        one_mean   one_std  two_mean   two_std
0  0.160018  1.405113   foo -0.433644  1.245972  0.254995  0.846983   qux

        qux
   one_mean   one_std  two_mean   two_std
0  0.667629  0.315417 -0.757989  0.683273

As you can see, I have been able to manage it with a for loop and some line of code. Can someone do the same thing in a more optimized way. I am quite sure that with Pandas, the same thing can be done with few lines of code.

Body:
I think you need get mean and std of df, then concat together and reshape by unstack:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))

np.random.seed(1000)
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
print(df)
first        bar                 baz                 foo                 qux  \
second       one       two       one       two       one       two       one
A      -0.804458  0.320932 -0.025483  0.644324 -0.300797  0.389475 -0.107437
B       0.595036 -0.464668  0.667281 -0.806116 -1.196070 -0.405960 -0.182377
C      -0.138422  0.705692  1.271795 -0.986747 -0.334835 -0.099482  0.407192

first
second       two
A      -0.479983
B       0.103193
C       0.919388

df = pd.concat([df.mean(), df.std()], keys=('mean','std')).unstack(1)
df.index =  [[0] * len(df.index), ['_'.join((col[1], col[0])) for col in df.index]]
df = df.unstack()
print (df)
first       bar                                     baz                      \
       one_mean   one_std  two_mean   two_std  one_mean   one_std  two_mean
0     -0.115948  0.700018  0.187319  0.596511  0.637865  0.649139 -0.382846

first                 foo                                     qux           \
        two_std  one_mean   one_std  two_mean   two_std  one_mean  one_std
0      0.894129 -0.610567  0.507346 -0.038656  0.401191  0.039126  0.32095

first
       two_mean   two_std
0      0.180866  0.702911


问:
reinitialize javascript with pjax on back button
Below "done" callback works well when button is clicked. But with browser back button, done callback is not called again.

```<code>$.pjax({
        url: $this.attr("href"),
        container: '#div-section',
        push: true
}).done(function() {
        $object.init();
});
</code>```

is there some another way to fire other javascripts on pjax end other than done ( as it does not work )?

答:
Found solution but there can be I guess only one such handler in page -

```<code>$(document).on("ready pjax:success", function(){
        //initialize all javascripts here
});
</code>```

EDIT

Above solution leads to dual bindings on pjax calls, once inside pjax:success followed by second time inside done event callback. To have bindings executed only one on back / forward  or on pjax , we can do as below. In this case , globalEventDirection can be used to conditionally bind inside pjax:success leaving init to done in case button was clicked. But with back and forward button, init will be done inside pjax:success

```<code>    globalEventDirection = undefined;
    $(document).on("pjax:popstate", function(event){
            globalEventDirection = event.direction;
        });

    $(document).on("pjax:success", function(event){
        if(globalEventDirection === "back" || globalEventDirection === "forward" ) {
            //reinitialize javascript
            globalEventDirection = undefined;
        }
    });
</code>```

Body:
Below "done" callback works well when button is clicked. But with browser back button, done callback is not called again.

$.pjax({
        url: $this.attr("href"),
        container: '#div-section',
        push: true
}).done(function() {
        $object.init();
});

is there some another way to fire other javascripts on pjax end other than done ( as it does not work )?

Body:
Found solution but there can be I guess only one such handler in page -

$(document).on("ready pjax:success", function(){
        //initialize all javascripts here
});

EDIT

Above solution leads to dual bindings on pjax calls, once inside pjax:success followed by second time inside done event callback. To have bindings executed only one on back / forward  or on pjax , we can do as below. In this case , globalEventDirection can be used to conditionally bind inside pjax:success leaving init to done in case button was clicked. But with back and forward button, init will be done inside pjax:success

    globalEventDirection = undefined;
    $(document).on("pjax:popstate", function(event){
            globalEventDirection = event.direction;
        });

    $(document).on("pjax:success", function(event){
        if(globalEventDirection === "back" || globalEventDirection === "forward" ) {
            //reinitialize javascript
            globalEventDirection = undefined;
        }
    });


问:
Android library project debugging quickly
I am developing a library project. Right now my debugging process is something like this :

Make some changes in library code

build it into an aar file

use the aar file in main app project as new library module

then debug the code changes in lib code.

As you can see it's a long process and takes a lot of time to debug library. What is the proper way for library development using android studio?

答:
I would include a demo-app project in parallel to library project:</p>

```<code>//  /settings.gradle
include ':app', ':lib'

//  /app/build.gradle
depencency {
    compile project(':lib')
}
</code>```

Body:
I would include a demo-app project in parallel to library project:

//  /settings.gradle
include ':app', ':lib'

//  /app/build.gradle
depencency {
    compile project(':lib')
}


问:
auto hides keyboard after scrolling ListView on android
Im new on android please help me to auto hide after scrolling the listview here is my code but could not get right solution

xml file :

```<code><ListView
    android:id="@+id/offline_list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#dde1e3"
    android:clickable="true"
    android:focusable="true"
     >
</ListView>
</code>```

code:

```<code>        lvCustomList.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(!hasFocus)
                hideKeyboard(v);

        }

        private void hideKeyboard(View view) {
            // TODO Auto-generated method stub
            InputMethodManager inputMethodManger = (InputMethodManager)getSystemService(Activity
                    .INPUT_METHOD_SERVICE);
            inputMethodManger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    });
</code>```

答:
It is better to use onScrollStateChanged instead of onScroll and by using scrollState == 0. So keyboard will hide when user is really scrolling.

```<code>listview.setOnScrollListener(new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view,
                                         int scrollState) {

            if (scrollState == 0) {
                InputMethodManager inputMethodManger = (InputMethodManager) getActivity().getSystemService(Activity
                        .INPUT_METHOD_SERVICE);
                inputMethodManger.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {

        }
    });
</code>```

Body:
Im new on android please help me to auto hide after scrolling the listview here is my code but could not get right solution

xml file :

<ListView
    android:id="@+id/offline_list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#dde1e3"
    android:clickable="true"
    android:focusable="true"
     >
</ListView>

code:

        lvCustomList.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(!hasFocus)
                hideKeyboard(v);

        }

        private void hideKeyboard(View view) {
            // TODO Auto-generated method stub
            InputMethodManager inputMethodManger = (InputMethodManager)getSystemService(Activity
                    .INPUT_METHOD_SERVICE);
            inputMethodManger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    });

Body:
It is better to use onScrollStateChanged instead of onScroll and by using scrollState == 0. So keyboard will hide when user is really scrolling.

listview.setOnScrollListener(new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view,
                                         int scrollState) {

            if (scrollState == 0) {
                InputMethodManager inputMethodManger = (InputMethodManager) getActivity().getSystemService(Activity
                        .INPUT_METHOD_SERVICE);
                inputMethodManger.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {

        }
    });


问:
How to split the given format into date and time in android
Given Format:
2017-03-08 13:27:00

I want to spilt it into 2 strings
1 for date and 1 for time
for

E.g.

08-03-2017

13:27:00

答:
Try this :</p>

```<code>String datetime= "2017-03-08 13:27:00";
String[] divide= datetime.split("\\s");
String date = divide[0]; //2017-03-08
String time= divide[1]; // 13:27:00
</code>```

Body:
Try this :

String datetime= "2017-03-08 13:27:00";
String[] divide= datetime.split("\\s");
String date = divide[0]; //2017-03-08
String time= divide[1]; // 13:27:00


问:
html - table row like a link
I can't set my table row as link to something. I can use only css and html. I tried different things from div in row to something another, but still can't make it works.</p>

答:
When i want simulate a
 with a link but respecting the html standards, I do this.

HTML:

```<code><table>
    <tr class="trLink">
        <td>
            <a href="#">Something</a>
        </td>
    </tr>
</table>
</code>```

CSS:

```<code>tr.trLink {
    cursor: pointer;
}
tr.trLink:hover {
   /*TR-HOVER-STYLES*/
}

tr.trLink a{
    display: block;
    height: 100%;
    width: 100%;
}
tr.trLink:hover a{
   /*LINK-HOVER-STYLES*/
}
</code>```

In this way, when someone go with his mouse on a TR, all the row (and this links) gets the hover style and he can't see that there are multiple links.

Hope can help someone.

Fiddle HERE

Title: html - table row like a link

Body:
When i want simulate a <tr> with a link but respecting the html standards, I do this.

HTML:

<table>
    <tr class="trLink">
        <td>
            <a href="#">Something</a>
        </td>
    </tr>
</table>

CSS:

tr.trLink {
    cursor: pointer;
}
tr.trLink:hover {
   /*TR-HOVER-STYLES*/
}

tr.trLink a{
    display: block;
    height: 100%;
    width: 100%;
}
tr.trLink:hover a{
   /*LINK-HOVER-STYLES*/
}

In this way, when someone go with his mouse on a TR, all the row (and this links) gets the hover style and he can't see that there are multiple links.

Hope can help someone.

Fiddle HERE