问:
Aria-checked value not switching from true to false when checking the checkbox
My screen reader JAWS 17 is reading Checkbox not checked when I am on the checkbox even though I check it.

I debugged the issue and found out that the aria-checked="false" is not switching to aria-checked="true" when I check it.

I am using Google Chrome 58.0.3029.110 (64-bit)

HTML

```<code><modified-input
         enter-space-press="checked(row)"
         disabled="!row.enabled"
         ng-click="check(row)">
 </modified-input>
</code>```

Directive

```<code>function modifiedInput($window, $rootScope, _) {
        return {
            restrict: 'E',
            scope: {
                value:'=?',
                disabled:'=?',
            },
            template: (
                '<input ' +
                'type="checkbox" ' +
                'ng-disabled="disabled" ' +
                'aria-checked= "false" ' +
                'ng-value="value"/>'
            ),

        };
    }

    modifiedInput.$inject = ["$window", "$rootScope", '_'];
    module.exports = modifiedInput;
</code>```

答:
Use ngAria in your project. It should handle common aria attributes automatically.

Read the official documentation here.

See working plunker here.

Based on the documentation, if you include ngAria in your project and use ng-model, the aria attributes will be handled automatically.

I'd suggest changing the template to this:

```<code>    template: (
        '<input ' +
        'type="checkbox" ' +
        'ng-disabled="disabled" ' +
        'ng-value="value" ' +
        'ng-model="checked"/>'
    )
</code>```

Body:
My screen reader JAWS 17 is reading Checkbox not checked when I am on the checkbox even though I check it.

I debugged the issue and found out that the aria-checked="false" is not switching to aria-checked="true" when I check it.

I am using Google Chrome 58.0.3029.110 (64-bit)

HTML

<modified-input
         enter-space-press="checked(row)"
         disabled="!row.enabled"
         ng-click="check(row)">
 </modified-input>

Directive

function modifiedInput($window, $rootScope, _) {
        return {
            restrict: 'E',
            scope: {
                value:'=?',
                disabled:'=?',
            },
            template: (
                '<input ' +
                'type="checkbox" ' +
                'ng-disabled="disabled" ' +
                'aria-checked= "false" ' +
                'ng-value="value"/>'
            ),

        };
    }

    modifiedInput.$inject = ["$window", "$rootScope", '_'];
    module.exports = modifiedInput;

Body:
Use ngAria in your project. It should handle common aria attributes automatically.

Read the official documentation here.

See working plunker here.

Based on the documentation, if you include ngAria in your project and use ng-model, the aria attributes will be handled automatically.

I'd suggest changing the template to this:

    template: (
        '<input ' +
        'type="checkbox" ' +
        'ng-disabled="disabled" ' +
        'ng-value="value" ' +
        'ng-model="checked"/>'
    )


来源: stackexchange

问:
UIView transition animation not executing
I'm trying to use an animation transition for when a UIView appears on screen.  The UIView appears correctly but the animation doesn't occur when it appears.</p>

```<code>  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let coreView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    coreView.backgroundColor = UIColor.cyan
    coreView.layer.borderColor = UIColor.darkGray.cgColor
    coreView.layer.borderWidth = 8
    coreView.layer.cornerRadius = 15
    coreView.isHidden = true
    self.view.addSubview(coreView)

    //The transition occurs here
    UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {

      coreView.isHidden = false
    }, completion: {_ in})

    }
</code>```

答: Try adding self.view.layoutIfNeeded() after your coreView hiding code in the animation block.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use an animation transition for when a UIView appears on screen.  The UIView appears correctly but the animation doesn't occur when it appears.

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let coreView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    coreView.backgroundColor = UIColor.cyan
    coreView.layer.borderColor = UIColor.darkGray.cgColor
    coreView.layer.borderWidth = 8
    coreView.layer.cornerRadius = 15
    coreView.isHidden = true
    self.view.addSubview(coreView)

    //The transition occurs here
    UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {

      coreView.isHidden = false
    }, completion: {_ in})

    }


问:
CheckBox UITableView with Different Sections
Trying to create a UITableview with checkbox button containing different sections, How do i manage to assigning a unique tag for each button in new sections. Since indexpath.row will be repeated in each new section, Cant use indexpath.row </p>

答:
Example using a UIButton with checked / unchecked background images with an on/off state:

```<code>//
//  TableWithCheckTableViewController.swift
//  SWTemp2
//
//  Created by Don Mag on 6/6/17.
//  Copyright © 2017 DonMag. All rights reserved.
//

import UIKit

class MyCheckTableViewCell: UITableViewCell {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var myCheckButton: UIButton!

    var checkedImage = UIImage(named: "Checked")
    var unCheckedImage = UIImage(named: "UnChecked")

    var isOn: Bool = false {
        didSet {
            myCheckButton.setBackgroundImage(self.isOn ? checkedImage : unCheckedImage, for: .normal)
        }
    }

    var checkTapAction : ((Bool)->Void)?

    @IBAction func buttonTapped(_ sender: Any) {

        self.isOn = !self.isOn

        checkTapAction?(self.isOn)
    }

}

// simple data object
class MyCheckObject: NSObject {
    var theTitle = ""
    var theCheckState = false

    init(_ title: String) {
        theTitle = title
    }
}

class TableWithCheckTableViewController: UITableViewController {

    // array of MyObjects
    var myData = [MyCheckObject]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // just to make it a little easier to see the rows scroll
        tableView.rowHeight = 60

        // create 40 data objects for the table
        for i in 1...40 {
            let d = MyCheckObject("Data Item: \(i)")
            myData.append(d)
        }

        tableView.reloadData()

    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCheckTableViewCell", for: indexPath) as! MyCheckTableViewCell

        // Configure the cell...
        let d = myData[indexPath.row]
        cell.myLabel.text = d.theTitle
        cell.isOn = d.theCheckState

        // set a "Callback Closure" in the cell
        cell.checkTapAction = {
            (isOn) in
            // update our Data Array to the new state of the switch in the cell
            self.myData[indexPath.row].theCheckState = isOn
        }

        return cell
    }

}
</code>```

Body:
Example using a UIButton with checked / unchecked background images with an on/off state:

//
//  TableWithCheckTableViewController.swift
//  SWTemp2
//
//  Created by Don Mag on 6/6/17.
//  Copyright © 2017 DonMag. All rights reserved.
//

import UIKit

class MyCheckTableViewCell: UITableViewCell {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var myCheckButton: UIButton!

    var checkedImage = UIImage(named: "Checked")
    var unCheckedImage = UIImage(named: "UnChecked")

    var isOn: Bool = false {
        didSet {
            myCheckButton.setBackgroundImage(self.isOn ? checkedImage : unCheckedImage, for: .normal)
        }
    }

    var checkTapAction : ((Bool)->Void)?

    @IBAction func buttonTapped(_ sender: Any) {

        self.isOn = !self.isOn

        checkTapAction?(self.isOn)
    }

}

// simple data object
class MyCheckObject: NSObject {
    var theTitle = ""
    var theCheckState = false

    init(_ title: String) {
        theTitle = title
    }
}

class TableWithCheckTableViewController: UITableViewController {

    // array of MyObjects
    var myData = [MyCheckObject]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // just to make it a little easier to see the rows scroll
        tableView.rowHeight = 60

        // create 40 data objects for the table
        for i in 1...40 {
            let d = MyCheckObject("Data Item: \(i)")
            myData.append(d)
        }

        tableView.reloadData()

    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCheckTableViewCell", for: indexPath) as! MyCheckTableViewCell

        // Configure the cell...
        let d = myData[indexPath.row]
        cell.myLabel.text = d.theTitle
        cell.isOn = d.theCheckState

        // set a "Callback Closure" in the cell
        cell.checkTapAction = {
            (isOn) in
            // update our Data Array to the new state of the switch in the cell
            self.myData[indexPath.row].theCheckState = isOn
        }

        return cell
    }

}


问:
Javascript cookies not working
I'm trying to use a cookie to save the color chosen by the user to set the body of my site's pages. Now the cookie is being set fine but for some reason I seem to get it working. Can anyone see where I'm going wrong here?

Thanks.

Console Error:

Uncaught TypeError: Cannot set property 'className' of null

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
var bgColour = getCookie('bgColour');

if (bgColour == "01") {
  document.getElementById("body").className = "bgColor01";
}
if (bgColour == "02") {
  document.getElementById("body").className = "bgColor02";
}
if (bgColour == "03") {
  document.getElementById("body").className = "bgColor03";
}
if (bgColour == "04") {
  document.getElementById("body").className = "bgColor04";
}
if (bgColour == "05") {
  document.getElementById("body").className = "bgColor05";
}

function color1() {
  document.cookie = "bgColour=01";
}

function color2() {
  document.cookie = "bgColour=02";
}

function color3() {
  document.cookie = "bgColour=03";
}

function color4() {
  document.cookie = "bgColour=04";
}

function color5() {
  document.cookie = "bgColour=05";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.bgColor00 {
  background-color: #f6f4fb;
}

.bgColor01 {
  background-color: #80b3ff;
}

.bgColor02 {
  background-color: #afe9af;
}

.bgColor03 {
  background-color: #ffb380;
}

.bgColor04 {
  background-color: #ffaaaa;
}

.bgColor05 {
  background-color: #eeaaff;
}</code>```

  <button onClick="color1()">Blue</button>
  <button onClick="color2()">Green</button>
  <button onClick="color3()">Orange</button>
  <button onClick="color4()">Red</button>
  <button onClick="color5()">Purple</button>

```

答:
I think that your problem is that you place the script outside the  tag. I tried doing like this:

```<code><html>
<style>
body {
  margin: 0;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.bgColor00 {
  background-color: #f6f4fb;
}

.bgColor01 {
  background-color: #80b3ff;
}

.bgColor02 {
  background-color: #afe9af;
}

.bgColor03 {
  background-color: #ffb380;
}

.bgColor04 {
  background-color: #ffaaaa;
}

.bgColor05 {
  background-color: #eeaaff;
}
</style>
<body id="body">
  <button onClick="color1()">Blue</button>
  <button onClick="color2()">Green</button>
  <button onClick="color3()">Orange</button>
  <button onClick="color4()">Red</button>
  <button onClick="color5()">Purple</button>
</body>

<script type='text/javascript'>

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
var bgColour = getCookie('bgColour');

if (bgColour == "01") {
  document.getElementById("body").className = "bgColor01";
}
if (bgColour == "02") {
  document.getElementById("body").className = "bgColor02";
}
if (bgColour == "03") {
  document.getElementById("body").className = "bgColor03";
}
if (bgColour == "04") {
  document.getElementById("body").className = "bgColor04";
}
if (bgColour == "05") {
  document.getElementById("body").className = "bgColor05";
}

function color1() {
  document.cookie = "bgColour=01";
}

function color2() {
  document.cookie = "bgColour=02";
}

function color3() {
  document.cookie = "bgColour=03";
}

function color4() {
  document.cookie = "bgColour=04";
}

function color5() {
  document.cookie = "bgColour=05";
}
</script>
</html>
</code>```

And it works (no error occurs), the only issue is that is not dynamic the change, you have to refresh the page. Maybe a location.reload will work for you, or you will need to call the :

```<code>document.getElementById("body").className = "bgColor0X";
</code>```

inside each colorX() function. Then, the color will change at the click moment, not only on reload.

I made this working example: https://codepen.io/jpaulet/pen/LLVjGO
Hope it helps!

Title: Javascript cookies not working

Body:
I'm trying to use a cookie to save the color chosen by the user to set the body of my site's pages. Now the cookie is being set fine but for some reason I seem to get it working. Can anyone see where I'm going wrong here?

Thanks.

Console Error:

Uncaught TypeError: Cannot set property 'className' of null

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
var bgColour = getCookie('bgColour');

if (bgColour == "01") {
  document.getElementById("body").className = "bgColor01";
}
if (bgColour == "02") {
  document.getElementById("body").className = "bgColor02";
}
if (bgColour == "03") {
  document.getElementById("body").className = "bgColor03";
}
if (bgColour == "04") {
  document.getElementById("body").className = "bgColor04";
}
if (bgColour == "05") {
  document.getElementById("body").className = "bgColor05";
}

function color1() {
  document.cookie = "bgColour=01";
}

function color2() {
  document.cookie = "bgColour=02";
}

function color3() {
  document.cookie = "bgColour=03";
}

function color4() {
  document.cookie = "bgColour=04";
}

function color5() {
  document.cookie = "bgColour=05";
}

body {
  margin: 0;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.bgColor00 {
  background-color: #f6f4fb;
}

.bgColor01 {
  background-color: #80b3ff;
}

.bgColor02 {
  background-color: #afe9af;
}

.bgColor03 {
  background-color: #ffb380;
}

.bgColor04 {
  background-color: #ffaaaa;
}

.bgColor05 {
  background-color: #eeaaff;
}

  <button onClick="color1()">Blue</button>
  <button onClick="color2()">Green</button>
  <button onClick="color3()">Orange</button>
  <button onClick="color4()">Red</button>
  <button onClick="color5()">Purple</button>

Body:
I think that your problem is that you place the script outside the <html> tag. I tried doing like this:

<html>
<style>
body {
  margin: 0;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.bgColor00 {
  background-color: #f6f4fb;
}

.bgColor01 {
  background-color: #80b3ff;
}

.bgColor02 {
  background-color: #afe9af;
}

.bgColor03 {
  background-color: #ffb380;
}

.bgColor04 {
  background-color: #ffaaaa;
}

.bgColor05 {
  background-color: #eeaaff;
}
</style>
<body id="body">
  <button onClick="color1()">Blue</button>
  <button onClick="color2()">Green</button>
  <button onClick="color3()">Orange</button>
  <button onClick="color4()">Red</button>
  <button onClick="color5()">Purple</button>
</body>

<script type='text/javascript'>

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
var bgColour = getCookie('bgColour');

if (bgColour == "01") {
  document.getElementById("body").className = "bgColor01";
}
if (bgColour == "02") {
  document.getElementById("body").className = "bgColor02";
}
if (bgColour == "03") {
  document.getElementById("body").className = "bgColor03";
}
if (bgColour == "04") {
  document.getElementById("body").className = "bgColor04";
}
if (bgColour == "05") {
  document.getElementById("body").className = "bgColor05";
}

function color1() {
  document.cookie = "bgColour=01";
}

function color2() {
  document.cookie = "bgColour=02";
}

function color3() {
  document.cookie = "bgColour=03";
}

function color4() {
  document.cookie = "bgColour=04";
}

function color5() {
  document.cookie = "bgColour=05";
}
</script>
</html>

And it works (no error occurs), the only issue is that is not dynamic the change, you have to refresh the page. Maybe a location.reload will work for you, or you will need to call the :

document.getElementById("body").className = "bgColor0X";

inside each colorX() function. Then, the color will change at the click moment, not only on reload.

I made this working example: https://codepen.io/jpaulet/pen/LLVjGO
Hope it helps!


问:
Find strings with maximum vowels
I want to find strings with maximum vowels in Python, but I don't know how.

Examples

Input

```<code>['Zak6aa','kak','ll','ak']
</code>```

Output:

```<code>['Zak6aa']
</code>```

Another if two or more strings tie for max vowels:

```<code>['Zaa', 'bii','ak']
</code>```

output is:

```<code>['Zaa', 'bii']
</code>```

My try:

```<code>def maxv(string):
    sam=0
    seq=[]
    for i in range(len(string)):
        k=0
        v=0
        for char in string[i]:
             if char in "aeiouy":
                v = v+1
        k=(len(string[i]))-v
        if (v >=k):
            seq=seq+[string[i]]
    return seq
</code>```

答:
Thanks everybody

How to print the number of swaps in selection sort in Python?
For example
output `

[1, 2, 3, 4, 5, 6, 7, 9, 8]

`
input

1

because there is 1 swap 9 with 8.

```<code>  def min(list, fromw):
      m = fromw
      for i in range(fromw + 1,len(list)):
          if list[i] < list[m]:
              m = i
      return m

def select(list):
    for promt in range(len(list)):
        where = min(list, promt)
        list[where], list[promt] = list[promt], list[where]
    return list
</code>```

Title: Find strings with maximum vowels

Body:
I want to find strings with maximum vowels in Python, but I don't know how.

Examples

Input

['Zak6aa','kak','ll','ak']

Output:

['Zak6aa']

Another if two or more strings tie for max vowels:

['Zaa', 'bii','ak']

output is:

['Zaa', 'bii']

My try:

def maxv(string):
    sam=0
    seq=[]
    for i in range(len(string)):
        k=0
        v=0
        for char in string[i]:
             if char in "aeiouy":
                v = v+1
        k=(len(string[i]))-v
        if (v >=k):
            seq=seq+[string[i]]
    return seq

Body:
Thanks everybody

How to print the number of swaps in selection sort in Python?
For example
output `

[1, 2, 3, 4, 5, 6, 7, 9, 8]

`
input

1

because there is 1 swap 9 with 8.

  def min(list, fromw):
      m = fromw
      for i in range(fromw + 1,len(list)):
          if list[i] < list[m]:
              m = i
      return m

def select(list):
    for promt in range(len(list)):
        where = min(list, promt)
        list[where], list[promt] = list[promt], list[where]
    return list


问:
Can I get this sales comparison into a single column?
Here is my data:

```<code>CREATE TABLE SALES (
    ts TIMESTAMP NOT NULL,
    name VARCHAR(50) NOT NULL,
    quantity INTEGER,
    price DECIMAL(2,2)
);

INSERT INTO SALES VALUES
    ("2017-02-08 13:38:02", "apple", 6, 4.38),
    ("2017-02-08 13:38:02", "banana", 10, 3.50),
    ("2017-02-08 13:38:02", "orange", 8, 2.98),
    ("2017-02-08 09:21:52", "banana", 6, 2.67),
    ("2017-02-08 09:21:52", "pear", 3, 2.00),
    ("2017-02-07 15:21:32", "apple", 6, 4.38),
    ("2017-02-07 15:21:32", "banana", 6, 2.67),
    ("2017-02-07 11:03:16", "orange", 8, 2.98),
    ("2017-02-07 11:03:16", "banana", 4, 1.17);
</code>```

I'd like to get items that sold today but not yesterday.

I can get them in 2 columns using:

```<code>select
    name,
    SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-08' then quantity  else 0 end) as today,
    SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-07' then quantity  else 0 end) as yday
from sales
group by name
having yday = 0
</code>```

Result:

```<code>| name | today | yday
---------------------
| pear |   3   |  0
</code>```

But how could I get just 2 columns, 1 for name and 1 called "sold_today_but_not_yday" with a True/False value? Is that possible? (preferably without using subqueries).

答:
You can use a case:

```<code>select name,
       (case when SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-08' then quantity  else 0 end) > 0 and
                  SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-07' then quantity  else 0 end) = 0
             then 1 else 0
        end) as isTodayNotYesterday
from sales
group by name;
</code>```

Body:
Here is my data:

CREATE TABLE SALES (
    ts TIMESTAMP NOT NULL,
    name VARCHAR(50) NOT NULL,
    quantity INTEGER,
    price DECIMAL(2,2)
);

INSERT INTO SALES VALUES
    ("2017-02-08 13:38:02", "apple", 6, 4.38),
    ("2017-02-08 13:38:02", "banana", 10, 3.50),
    ("2017-02-08 13:38:02", "orange", 8, 2.98),
    ("2017-02-08 09:21:52", "banana", 6, 2.67),
    ("2017-02-08 09:21:52", "pear", 3, 2.00),
    ("2017-02-07 15:21:32", "apple", 6, 4.38),
    ("2017-02-07 15:21:32", "banana", 6, 2.67),
    ("2017-02-07 11:03:16", "orange", 8, 2.98),
    ("2017-02-07 11:03:16", "banana", 4, 1.17);

I'd like to get items that sold today but not yesterday.

I can get them in 2 columns using:

select
    name,
    SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-08' then quantity  else 0 end) as today,
    SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-07' then quantity  else 0 end) as yday
from sales
group by name
having yday = 0

Result:

| name | today | yday
---------------------
| pear |   3   |  0

But how could I get just 2 columns, 1 for name and 1 called "sold_today_but_not_yday" with a True/False value? Is that possible? (preferably without using subqueries).

Body:
You can use a case:

select name,
       (case when SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-08' then quantity  else 0 end) > 0 and
                  SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-07' then quantity  else 0 end) = 0
             then 1 else 0
        end) as isTodayNotYesterday
from sales
group by name;


问:
Disable Manual Zooming on UIScrollView
I have a project with a UIScrollView which I want to control the zooming programmatically but not via user interaction.  I have tried setting the multipleTouchedEnabled property to false.  This doesn't work.  When I pinch on the scroll view, the scrollViewDidZoom and viewForZoomingInScrollView are called.  I have also tried subclassing UIScrollView and overriding addGestureRecognizer and disabling the gesture which passes a [gesture [isKindOfClass: [UIPinchGestureRecognizer class]].  After breakpointing on that override, no gestures are matched.

So how can I have zooming on the scroll view but not allow manual interaction with the zooming.  I still need single finger panning for normal scrolling.

答: Try to set scrollView.pinchGestureRecognizer.enabled = NO;</p>

Title: Disable Manual Zooming on UIScrollView


问:
Anesrake run error when executing multiple target variables
I currently am trying to execute the anesrake function (part of the anesrake package https://cran.r-project.org/web/packages/anesrake/index.html which weights population attribute sets based on sample attribute sets) within R to approximate weight rankings for multiple sets of variables.

I have a table of sample data testData:

```<code>Index   GENDER   AGE
1       Female   18-24
2       Female   35-64
3       Male     65+
</code>```

Note: age range has 6 levels- 18-24,25-34,35-44,45-54,55-64,65+

I then have a set of 2 lists for my population data:

```<code>GENDER <- c(.49,.51)
AGE <- c(.08,.1,.12,.2,.2,.3)
</code>```

I then create a set of target variables and a CASEID column on the original table:

```<code>targets <- list(GENDER, AGE)
names(targets) <- c("GENDER", "AGE")
testData$CASEID <- 1:length(testData$GENDER)
</code>```

I finally get to see the variance in my population data vs my sample data:

```<code>> anesrakefinder(targets, testData, choosemethod = "total")
   GENDER       AGE
0.1495337 0.3668394
</code>```

But when I use the anesrake function to do the final analysis, I get thrown errors:

```<code>> anesrake(inputter=targets,dataframe=testData,caseid=testData$CASEID)
Error in rakeonvar.default(mat[, i], inputter[[i]], weightvec) :
  number of variable levels does not match number of weighting levels
In addition: Warning message:
In rakeonvar.default(mat[, i], inputter[[i]], weightvec) :
  NAs introduced by coercion
</code>```

I've been following two 'tutorials' on how to utilize anesrake but I'm still coming up short. These are the tutorials below:

http://sdaza.com/survey/2012/08/25/raking/

http://surveyinsights.org/wp-content/uploads/2014/07/Full-anesrake-paper.pdf

Any help that you could provide on this would be greatly, greatly appreciated.

Cheers,

Stu

答:
You need to label the levels of the target variables the same as the levels of the data variables using the following example- </p>

```<code>names(targets$agecat1) <- levels(rak2$agecat1)
names(targets$newpayer) <- levels(rak2$newpayer)
</code>```

Body:
I currently am trying to execute the anesrake function (part of the anesrake package https://cran.r-project.org/web/packages/anesrake/index.html which weights population attribute sets based on sample attribute sets) within R to approximate weight rankings for multiple sets of variables.

I have a table of sample data testData:

Index   GENDER   AGE
1       Female   18-24
2       Female   35-64
3       Male     65+

Note: age range has 6 levels- 18-24,25-34,35-44,45-54,55-64,65+

I then have a set of 2 lists for my population data:

GENDER <- c(.49,.51)
AGE <- c(.08,.1,.12,.2,.2,.3)

I then create a set of target variables and a CASEID column on the original table:

targets <- list(GENDER, AGE)
names(targets) <- c("GENDER", "AGE")
testData$CASEID <- 1:length(testData$GENDER)

I finally get to see the variance in my population data vs my sample data:

> anesrakefinder(targets, testData, choosemethod = "total")
   GENDER       AGE
0.1495337 0.3668394

But when I use the anesrake function to do the final analysis, I get thrown errors:

> anesrake(inputter=targets,dataframe=testData,caseid=testData$CASEID)
Error in rakeonvar.default(mat[, i], inputter[[i]], weightvec) :
  number of variable levels does not match number of weighting levels
In addition: Warning message:
In rakeonvar.default(mat[, i], inputter[[i]], weightvec) :
  NAs introduced by coercion

I've been following two 'tutorials' on how to utilize anesrake but I'm still coming up short. These are the tutorials below:

http://sdaza.com/survey/2012/08/25/raking/

http://surveyinsights.org/wp-content/uploads/2014/07/Full-anesrake-paper.pdf

Any help that you could provide on this would be greatly, greatly appreciated.

Cheers,

Stu

Body:
You need to label the levels of the target variables the same as the levels of the data variables using the following example-

names(targets$agecat1) <- levels(rak2$agecat1)
names(targets$newpayer) <- levels(rak2$newpayer)


问:
SonarQube does not create graphs on project dashboards
SonarQube Metrics graphs are not being displayed on my project dashboards behind the total numbers and Quality Gate ratings.

Current versions of SonarQube and plugins and MySQL 5.7. I am creating a new SQ project through its Administration->Projects->Management->Create Project and then performing analyses as follows (anything capitalized is either a variable or anonymized): *

```<code>MSBuild.SonarQube.Runner.exe begin /k:KEY /v:VERSION /d:sonar.host.url=http://localhost:9000/ /d:sonar.login=TOKEN /d:sonar.projectDate=YYYY-MM-DDTHH:MM:SS+0000
MSBuild.exe /maxcpucount /nr:false /nologo /target:rebuild /verbosity:quiet PROJECT\PROJECT.sln
MSBuild.SonarQube.Runner.exe end /d:sonar.login=TOKEN
</code>```

I have tried VERSION equal to a constant value "1.0" and VERSION equal to a string of the UNIX time (seconds since 1/1/1970) of each git commit I analyze. I've also tried configuring project leak periods of the last 90 days and also previous_analysis, though I think that would only affect the graphs in the right column. If someone could tell me what I am doing incorrectly, I would appreciate it.

* These are examples of the commands executed by a Python script that is iterating over a list of git commit hashes and their associated timestamps, in increasing order, to populate the project history. The python script in turn is mimicking a Jenkins job that will eventually take over calling SonarQube.

Background Tasks page:

答:
Your project homepage screenshot shows the graph in the leak period, but not extending left into the Overall section.

This is going to be a question of your analysis date and your definition of "leak period". If your leak period is set to previous_version, then you need to take a look at the sonar.version values in your analyses. So far, it looks like all your analyses are leak period analyses, which is why nothing has filtered left into the overall view.

Body:
SonarQube Metrics graphs are not being displayed on my project dashboards behind the total numbers and Quality Gate ratings.

Current versions of SonarQube and plugins and MySQL 5.7. I am creating a new SQ project through its Administration->Projects->Management->Create Project and then performing analyses as follows (anything capitalized is either a variable or anonymized): *

MSBuild.SonarQube.Runner.exe begin /k:KEY /v:VERSION /d:sonar.host.url=http://localhost:9000/ /d:sonar.login=TOKEN /d:sonar.projectDate=YYYY-MM-DDTHH:MM:SS+0000
MSBuild.exe /maxcpucount /nr:false /nologo /target:rebuild /verbosity:quiet PROJECT\PROJECT.sln
MSBuild.SonarQube.Runner.exe end /d:sonar.login=TOKEN

I have tried VERSION equal to a constant value "1.0" and VERSION equal to a string of the UNIX time (seconds since 1/1/1970) of each git commit I analyze. I've also tried configuring project leak periods of the last 90 days and also previous_analysis, though I think that would only affect the graphs in the right column. If someone could tell me what I am doing incorrectly, I would appreciate it.

* These are examples of the commands executed by a Python script that is iterating over a list of git commit hashes and their associated timestamps, in increasing order, to populate the project history. The python script in turn is mimicking a Jenkins job that will eventually take over calling SonarQube.

Background Tasks page:


答:
Instead of manipulating isHidden property of the coreView use the alpha property.

Try replacing coreView.isHidden = true with coreView.alpha = 0 and in the animation block replace coreView.isHidden = false with coreView.alpha = 1

That should be it I guess. It should animate. Thanks.

Title: UIView transition animation not executing


问:
How can I correctly use variable variable names in ng-repeat in angular?
HTML:

```<code><ul>
  <li ng-repeat="comic in comiclist">
    <span>{{ comic.title }} : {{comic.id}}</span>
    <div >
      <img ng-src="{{comic.thumbnail.path}}.{{comic.thumbnail.extension}}"/>
    </div>
    <div>
      <ul>
        <li ng-repeat="character in charlist + {{comic.id}}">
          <span>{{character.name}}</span>
        </li>
      </ul>
    </div>
  </li>
</ul>
</code>```

JS with angular

```<code>var App = angular.module('MarvelApp', []);
  App.controller('MainController', function($scope,$window, $http) {
      $scope.GetSeries = function(){
        $http.get('http://gateway.marvel.com/v1/public/series?')
        .then(function(response){
        $scope.serieslist = response.data.data.results;
        });
      };
    $scope.GetComics = function(){
      $http.get('http://gateway.marvel.com/v1/public/series/' + $scope.selectedseries + '/comics?')
      .then(function(response){
          $scope.comiclist = response.data.data.results;
      });
      //comic in comiclist contains comic.id
      //which needs to go to GetCharacter()
    }
    $scope.GetCharacter = function(comicid){
      $http.get('http://gateway.marvel.com/v1/public/comics/' + comicid + '/characters')
      .then(function(response){
          $scope.['charlist' + comicid]  = response.data.data.results;
       //this list needs to be displayed in the second ng-repeat
      });
    };
  });
</code>```

I'd like to get the character list to display in the right div. How I had it set up before, (without $scope.['charlist' + comicid]) it was overriding the other ng-repeats too.

Also, whenever GetComics() gets called it does it automatically.

答:
I don't think $scope.[] is valid syntax (unless I've been missing out on a nifty trick).

You should instead name an "associative array" under $scope something like:

```<code>$scope.charlist[comicid] = ... ;
</code>```

Your ng-repeat would then look something like:

```<code><li ng-repeat="character in charlist[comic.id]">
</code>```

EDIT As mentioned in the comments, $scope.charlist must be defined before the above lines can be used. This can happen in a few ways:

Make a check before you set it: if(!$scope.charlist) $scope.charlist = [];

Define it somewhere in the controller with $scope.charlist = [];

Of course there's any number of ways you can do this, but these make these I believe make the most sense, the first of which catches invalid states i.e. if for some reason $scope.charlist is set to null it would create a new "associative array".

Body:
HTML:

    {{ comic.title }} : {{comic.id}}

          {{character.name}}

JS with angular

var App = angular.module('MarvelApp', []);
  App.controller('MainController', function($scope,$window, $http) {
      $scope.GetSeries = function(){
        $http.get('http://gateway.marvel.com/v1/public/series?')
        .then(function(response){
        $scope.serieslist = response.data.data.results;
        });
      };
    $scope.GetComics = function(){
      $http.get('http://gateway.marvel.com/v1/public/series/' + $scope.selectedseries + '/comics?')
      .then(function(response){
          $scope.comiclist = response.data.data.results;
      });
      //comic in comiclist contains comic.id
      //which needs to go to GetCharacter()
    }
    $scope.GetCharacter = function(comicid){
      $http.get('http://gateway.marvel.com/v1/public/comics/' + comicid + '/characters')
      .then(function(response){
          $scope.['charlist' + comicid]  = response.data.data.results;
       //this list needs to be displayed in the second ng-repeat
      });
    };
  });

I'd like to get the character list to display in the right div. How I had it set up before, (without $scope.['charlist' + comicid]) it was overriding the other ng-repeats too.

Also, whenever GetComics() gets called it does it automatically.

Body:
I don't think $scope.[] is valid syntax (unless I've been missing out on a nifty trick).

You should instead name an "associative array" under $scope something like:

$scope.charlist[comicid] = ... ;

Your ng-repeat would then look something like:

<li ng-repeat="character in charlist[comic.id]">

EDIT As mentioned in the comments, $scope.charlist must be defined before the above lines can be used. This can happen in a few ways:

Make a check before you set it: if(!$scope.charlist) $scope.charlist = [];

Define it somewhere in the controller with $scope.charlist = [];

Of course there's any number of ways you can do this, but these make these I believe make the most sense, the first of which catches invalid states i.e. if for some reason $scope.charlist is set to null it would create a new "associative array".


问:
Avoiding nesting maps when "pivoting" multidimensional array
I have data in the format

```<code>[
  {
    "timeline_map": {
      "2017-05-06": 770,
      "2017-05-07": 760,
      "2017-05-08": 1250
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 590,
      "2017-05-07": 210,
      "2017-05-08": 300
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 890,
      "2017-05-07": 2200,
      "2017-05-08": 1032
         ...
    }
  }
]
</code>```

that in order to use in a google chart I need to change to the format

```<code>[
  ["2017-05-06", 770, 590, 890, ...],
  ["2017-05-07", 760, 210, 2200, ...],
  ["2017-05-08", 1250, 300, 1032, ...]
]
</code>```

I wrote the following to make the transformation

```<code>let mapped = _.map(
  chartData.results[0].timeline_map, (timestampVal, timestampKey) => (
  [timestampKey].concat(
    _.map(
      chartData.results, lineData => (
        lineData.timeline_map[timestampKey]
        )
      )
    )
  )
)
</code>```

This works, but I'm thinking that nesting the maps is not a good idea because how it will increase the amount of looping by the square off the length of the array being mapped. Is there a better way to achieve the desired result here.

JSBIN

答:
You could use a closure over a hash table and assign the values accordingly to the date keys.

var data = [{ timeline_map: { "2017-05-06": 770, "2017-05-07": 760, "2017-05-08": 1250 } }, { timeline_map: { "2017-05-06": 590, "2017-05-07": 210, "2017-05-08": 300 } }, { timeline_map: { "2017-05-06": 890, "2017-05-07": 2200, "2017-05-08": 1032 } }],
    grouped = data.reduce(function (hash) {
        return function (r, o) {
            Object.keys(o.timeline_map).forEach(function (k) {
                if (!hash[k]) {
                    hash[k] = [k];
                    r.push(hash[k]);
                }
                hash[k].push(o.timeline_map[k]);
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have data in the format

[
  {
    "timeline_map": {
      "2017-05-06": 770,
      "2017-05-07": 760,
      "2017-05-08": 1250
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 590,
      "2017-05-07": 210,
      "2017-05-08": 300
         ...
    }
  },
  {
    "timeline_map": {
      "2017-05-06": 890,
      "2017-05-07": 2200,
      "2017-05-08": 1032
         ...
    }
  }
]

that in order to use in a google chart I need to change to the format

[
  ["2017-05-06", 770, 590, 890, ...],
  ["2017-05-07", 760, 210, 2200, ...],
  ["2017-05-08", 1250, 300, 1032, ...]
]

I wrote the following to make the transformation

let mapped = _.map(
  chartData.results[0].timeline_map, (timestampVal, timestampKey) => (
  [timestampKey].concat(
    _.map(
      chartData.results, lineData => (
        lineData.timeline_map[timestampKey]
        )
      )
    )
  )
)

This works, but I'm thinking that nesting the maps is not a good idea because how it will increase the amount of looping by the square off the length of the array being mapped. Is there a better way to achieve the desired result here.

JSBIN

Body:
You could use a closure over a hash table and assign the values accordingly to the date keys.

var data = [{ timeline_map: { "2017-05-06": 770, "2017-05-07": 760, "2017-05-08": 1250 } }, { timeline_map: { "2017-05-06": 590, "2017-05-07": 210, "2017-05-08": 300 } }, { timeline_map: { "2017-05-06": 890, "2017-05-07": 2200, "2017-05-08": 1032 } }],
    grouped = data.reduce(function (hash) {
        return function (r, o) {
            Object.keys(o.timeline_map).forEach(function (k) {
                if (!hash[k]) {
                    hash[k] = [k];
                    r.push(hash[k]);
                }
                hash[k].push(o.timeline_map[k]);
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
HTML page to Server side stored proceedure call
I am new to client server programming but not programming in general, I have searched the web before asking this but I cannot seem to get a good answer so here is what I want to do.

I want to create a HTML page it will have a button and an edit box (I can do this)
When the button is pressed I want it to call a stored procedure on an SQL box and return the result in some form (popup windows will do here).

My problem is that I do not understand how to get from my HTML page to the server, do I need to call an aspx page followed by an aspx.cs page and and execute the stored_proceedure from there, if so how do I get from HTML to aspx and back, or is there some other method?
I assumed this would be simple to do but after researching I am finding it's not.

Any help example or links would be great, many thanks

James

答:
You can use an Ajax call to get from the html page to the .cs file to call your stored procedure. An example is here: Calling webmethod ina aspx.cs file using jquery ajax

Then in the success function of the ajax call, you can create a dialog box with the information returned from the stored procedure.


问:
Traverse up and down multi-dimensional array in Angular 2 / TypeScript
```<code>[
  {id: 1,
  name: "test 1",
  children: [
               {id: 2,
               name: "test 1-sub",
               children: []}
            ]
}]
</code>```

Assuming a json array of something like the above where each element may or may not have children, and it can go up to 9 levels deep.

If I want to know where on the tree I am, and be able to go up or down the tree.  I know on the way down I can simple go to the index of the selected child element to see them.  How would I go back up the tree?

Basically I'm thinking I'll have two elements on the page.  The main array that contains on the data, one element to indicate the current array I'm working with.

```<code>codes: any = [];
currentCode: any = {};
</code>```

To make this easier to read and navigate I am only going to display one level of the tree at a time, so main code, with it's child elements below it.

Do I need to store a map of the path I took to get where I am and walk down from the top each time to get to the point I want to be at?

I hope this isn't too confusing.

答:
Assuming that:

Ids are unique

You only need to get to the parent and don't really need the whole path

There are two options. If you could change the json or keep a copy of it, you can add a _parent field for each node. If you don't want to do that you can maintain a map for which the keys are the ids and the values are the parent references.

In either way you can populate the extra data by traversing the tree recursively.

Body:
[
  {id: 1,
  name: "test 1",
  children: [
               {id: 2,
               name: "test 1-sub",
               children: []}
            ]
}]

Assuming a json array of something like the above where each element may or may not have children, and it can go up to 9 levels deep.

If I want to know where on the tree I am, and be able to go up or down the tree.  I know on the way down I can simple go to the index of the selected child element to see them.  How would I go back up the tree?

Basically I'm thinking I'll have two elements on the page.  The main array that contains on the data, one element to indicate the current array I'm working with.

codes: any = [];
currentCode: any = {};

To make this easier to read and navigate I am only going to display one level of the tree at a time, so main code, with it's child elements below it.

Do I need to store a map of the path I took to get where I am and walk down from the top each time to get to the point I want to be at?

I hope this isn't too confusing.


问:
How do I install WindowsAzure.Storage in Visual Studio 2013?
Note: this answer didn't help me because I don't have the same dll: System.Collections.Immutable 1.1.37

I'm using Visual Studio 2013 and .net 4.5 and following this tutorial: Get started with Azure Blob storage using .NET
I am trying to install WindowsAzure.Storage but get this error:

Attempting to resolve dependency 'Microsoft.Data.OData (≥ 5.8.2)'.
  Attempting to resolve dependency 'System.Spatial (= 5.8.2)'.
  Attempting to resolve dependency 'Microsoft.Data.Edm (= 5.8.2)'.
  Attempting to resolve dependency 'Newtonsoft.Json (≥ 6.0.8)'.
  Attempting to resolve dependency 'Microsoft.Data.Services.Client (≥ 5.8.2)'.
  Attempting to resolve dependency 'System.Net.Requests (≥ 4.0.11)'.
  Attempting to resolve dependency 'System.ComponentModel.EventBasedAsync (≥ > 4.0.11)'.
  Attempting to resolve dependency 'System.Dynamic.Runtime (≥ 4.0.0)'.
  Attempting to resolve dependency 'System.Linq.Queryable (≥ 4.0.0)'.
  The 'System.Linq.Queryable 4.0.0' package requires NuGet client version '3.0' or above, but the current NuGet version is '2.12.0.817'.

when I upgrade Nuget per the red error in the image, it takes me to Extensions and Updates asking to update this:

I don't know the relation between what I am looking for and this, but I went ahead and followed that update anyway, but get the error:

Where should I proceed from here!?

based on comment form Simsons, I already checked that my processor supports Virtualization:

答:
When you try to install the WindowsAzure.Storage package through NuGet, this is the key error;

Attempting to resolve dependency 'System.Linq.Queryable (≥ 4.0.0)'. The 'System.Linq.Queryable 4.0.0' package requires NuGet client version '3.0' or above, but the current NuGet version is '2.12.0.817'

Unfortunately, System.Linq.Queryable 4.0.0 requires NuGet 3.0 or above. So this isn't going to work on Visual Studio 2013.

Luckily, the newer System.Linq.Queryable 4.3.0 only requires NuGet 2.12 which is available for Visual Studio 2013.

So, to successfully install WindowsAzure.Storage in Visual Studio 2013 via NuGet:

Download and Install NuGet 2.12 if you don't already have it. (OP has confirmed already having this version)

In NuGet, Install System.Linq.Queryable 4.3.0

In NuGet, Install WindowsAzure.Storage


问:
UI logic unit test
I have tens of conditions to check that set boolean values for seven or eight ui buttons enabled property.

So I setup boolean variables for each of the buttons (for example, isAction1Allowed, isAction2Allowed, etc.

How would I write a unit test for this case?

Currently, I have one method that contains all the logic which is nice but not sure how to turn into unit test (keep in mind very new to MVC and unit testing)

```<code>public void StateChecker() {  //This method resides in HtmlHelper
  bool isAllowed1 = false;
  bool isAllowed2 = false;
  bool isAllowed3 = false;

  if (condition1) {
    isAllowed1 = true;
  }
  else
  {
    isAllowed2 = true;
  }

  if (condition2) {
    isAllowed4 = true;
    isAllowed2 = true;
  }

// At the end of the method
Button1.Enabled = isAllowed1;
Button2.Enabled = isAllowed2;
Button3.Enabled = isAllowed3;

}
</code>```

Will I have to break the method up? Is there a better way to do what I'm trying to do? Remember there are a lot more conditions and buttons than the example shows but this is the gist of it. Basically, it's a small workflow or state machine.

答:
Normally you should use view models which are classes specifically adapted to your views. Those classes may contain such UI properties. It's up to the controller to populate them from the domain model classes, so you could would test them as any other class.

Personally I use AutoMapper to convert between my domain model classes and my views models, so it I unit test my mapper classes which are responsible for this conversion.

ContentLicense: CC BY-SA 4.0

Title: UI logic unit test

Body:
I have tens of conditions to check that set boolean values for seven or eight ui buttons enabled property.

So I setup boolean variables for each of the buttons (for example, isAction1Allowed, isAction2Allowed, etc.

How would I write a unit test for this case?

Currently, I have one method that contains all the logic which is nice but not sure how to turn into unit test (keep in mind very new to MVC and unit testing)

public void StateChecker() {  //This method resides in HtmlHelper
  bool isAllowed1 = false;
  bool isAllowed2 = false;
  bool isAllowed3 = false;

  if (condition1) {
    isAllowed1 = true;
  }
  else
  {
    isAllowed2 = true;
  }

  if (condition2) {
    isAllowed4 = true;
    isAllowed2 = true;
  }

// At the end of the method
Button1.Enabled = isAllowed1;
Button2.Enabled = isAllowed2;
Button3.Enabled = isAllowed3;

}

Will I have to break the method up? Is there a better way to do what I'm trying to do? Remember there are a lot more conditions and buttons than the example shows but this is the gist of it. Basically, it's a small workflow or state machine.

ContentLicense: CC BY-SA 2.5


问:
Unit testing a signed assembly in C#
I'm attempting to write some unit tests for a strongly named assembly. The unit tests are in a UnitTests project, the code is in a Plugins project, and they are both part of the same solution. Plugins is strongly signed. UnitTests has a reference to Plugins and everything compiles nicely.

When I try to run a test the test fails with an exception, "Could not load file or assembly... Strong name validation failed"

If I disable signing for Plugins the tests work, but signing is required for how the plugins are used. How can I solve this?

答:
This ended up being the result of another error I was encountering. Sometimes when building Plugins the build would fail with,

Assembly signing failed; output may not be signed -- Error signing assembly -- The process cannot access the file because it is being used by another process.

Building again would more often than not fix this error. It turns out that on the second build the Plugins.dll would sometimes remain and be only delay signed. UnitTests would take this delay signed dll and understandably complain.

To check if this is the issue you are running into open up a developer command prompt and run, "sn -vf Plugins.dll". If the output is, "Plugins.dll is a delay-signed or test-signed assembly", you may have the some problem.

The workaround that I am using is to repeatedly attempt to sign Plugins.dll until it works. To do this I first ran:

sn -i ../../FakeXRMTesting.pfx keyContainer

To set up a key container so sn could work without a password. Next I set Plugins.dll to Delay Sign Only and added a post-build event

:repeat

C:\"Program Files (x86)"\"Microsoft SDKs"\Windows\v8.0A\bin\"NETFX 4.0 Tools"\sn.exe -Rc Plugins.dll keyContainer || goto :repeat

Normally it fails 4-5 before working. This is quite clearly a cludge and stopping whatever program is accessing the dll from doing so would be preferred.

Title: Unit testing a signed assembly in C#


问:
Why get_allocator returns a copy and not a reference
I am using a custom allocator, which has a small simple state internally. When I use it with std::vector, I was surprised to see that get_allocator() actually returns copy to the allocator.

This is documented here: http://en.cppreference.com/w/cpp/container/vector/get_allocator

What is the reason for this?

One reason I can imagine is that get_allocator is a const member, I wouldn't mind getting a const reference to the allocator. Besided the internal allocator could have been declared mutable.

Am I missing something?
Is there a workaround to get the internal allocator of std::vector<T, special_allocator<T>> to inspect the state of the allocator?

Note: There is also the possibility that if the allocator is stateful then, perhaps one is supposed to use references all the way? Like std::vector<T, special_allocator<T>&>

答:
Stateful allocators are supposed to copy with retaining their state.

For example, when you pass an allocator for a map, it is rebound to another allocator type, but still retains the state you've passed to it.

Or two distinct containers share allocator state, yet they have different allocator instance.

Typically, you have allocator that has pointer to your state. Make pointer to your state a parameter of allocator constructor, and pass it as a parameter of your container constructor.


问:
jquery how to fill select option in my form
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

```<code><form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
</code>```

In this little code i receive a json with data from my database:

```<code>        var data = JSON.parse(response);
        console.log(data);
</code>```

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

```<code>var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
</code>```

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

```<code>    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }
</code>```

答:
You can loop your data and append option html to your select.

```<code>var select = document.getelementById('activity_2');
$(select).html('');
for (var i in data) {
    $(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}
</code>```

Body:
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>

In this little code i receive a json with data from my database:

        var data = JSON.parse(response);
        console.log(data);

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }

Body:
You can loop your data and append option html to your select.

var select = document.getelementById('activity_2');
$(select).html('');
for (var i in data) {
    $(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}


问:
How can I get the timezone offset without the DST formatted correctly?
I have not found a way to get the timezone offset without  Daylight Savings Time interference.

```<code>LocalDateTime dt = LocalDateTime.now();
...
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();
</code>```

This would seem like it works, but the initial DataTime might be influenced by DST.

There is also this:

```<code>int rawOffset = tZone.getRawOffset();
</code>```

However, this is always a positive number, so we don't ever get -05:00 back.

So what I want is a way to get the offset without DST interference. Any thoughts?

答:
First of all, keep in mind that offsets change over time (even the standard ones), basically because of governments, laws and other external factors.

That's why the API requires an Instant as a reference: to know what was the standard offset at that specific moment (no matter if the Instant is in the past, present or future). You can't say what the offset is without knowing when in time you are. And that's why @Joachim's answer is the correct one.

But as you told in the comments that you don't want to depend on Instant.now(), I've done the code below - and keep in mind that the solution is not 100% ideal, because of the reasons above. It's just the best I've got following your criteria.

You can do that using the java.time.zone.ZoneRules class, that you can get directly from your ZoneId instance:

```<code>// pick a timezone with DST
ZoneId zone = ZoneId.of("America/Sao_Paulo");
// get rules
ZoneRules rules = zone.getRules();
// check if offset changes over time (if it returns false, it means is not fixed, so it has DST)
System.out.println(rules.isFixedOffset()); // false
</code>```

In the code above, rules.isFixedOffset() returns false, which means that the corresponding timezone's offset changes over time (so, it has DST changes).

To know when those DST changes occur, you must get all the transitions:

```<code>// get all transitions (all dates where DST starts or ends)
List<ZoneOffsetTransition> transitions = rules.getTransitions();
transitions.stream().forEach(System.out::println);
</code>```

This prints lots of lines (as this timezone has DST almost every year). Here's a sample of the last 2 lines:

Transition[Overlap at 2039-02-20T00:00-02:00 to -03:00

  Transition[Gap at 2039-10-16T00:00-03:00 to -02:00]

This means that in 2039-02-20 at midnight, the offset will change from -02:00 to -03:00 (DST ends - clocks move back 1 hour), and in 2039-10-16 at midnight the offset will change from -03:00 to -02:00 (DST starts - clocks move forward 1 hour).

So, if you want to know the offset when it's not DST, you just get the last transition, check if it's a gap or overlap and get the offset after or before:

```<code>// get the last transition
ZoneOffsetTransition last = transitions.get(transitions.size() - 1);

// find the offset without DST interference
ZoneOffset offsetWithoutDST;

// overlap means that clock moves back 1 hour (when DST ends)
if(last.isOverlap()) {
    // DST ends, get the offset after it
    offsetWithoutDST = last.getOffsetAfter();
} else {
    // DST starts, get the offset before it
    offsetWithoutDST = last.getOffsetBefore();
}
System.out.println(offsetWithoutDST);
</code>```

In this case, it prints -03:00, which is the "normal" offset for America/Sao_Paulo timezone (when it's not DST).

PS: please note that DST and even standard offsets can vary a lot over time.

Just because the offset is one today, it doesn't mean it was always the same: governments can change the offset at any time, and in very past dates - like before 1900 - the offsets were much more messy than today (every city had its own time, with offsets like -03:06:28 and so on).

The code above gets the standard (non-DST) offset for the current timezone's rules. If you want to know what was the non-DST offset 30 years ago, you can use @Joachim's answer (passing an Instant of 30 years ago as a parameter).

Body:
I have not found a way to get the timezone offset without  Daylight Savings Time interference.

LocalDateTime dt = LocalDateTime.now();
...
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();

This would seem like it works, but the initial DataTime might be influenced by DST.

There is also this:

int rawOffset = tZone.getRawOffset();

However, this is always a positive number, so we don't ever get -05:00 back.

So what I want is a way to get the offset without DST interference. Any thoughts?

Body:
First of all, keep in mind that offsets change over time (even the standard ones), basically because of governments, laws and other external factors.

That's why the API requires an Instant as a reference: to know what was the standard offset at that specific moment (no matter if the Instant is in the past, present or future). You can't say what the offset is without knowing when in time you are. And that's why @Joachim's answer is the correct one.

But as you told in the comments that you don't want to depend on Instant.now(), I've done the code below - and keep in mind that the solution is not 100% ideal, because of the reasons above. It's just the best I've got following your criteria.

You can do that using the java.time.zone.ZoneRules class, that you can get directly from your ZoneId instance:

// pick a timezone with DST
ZoneId zone = ZoneId.of("America/Sao_Paulo");
// get rules
ZoneRules rules = zone.getRules();
// check if offset changes over time (if it returns false, it means is not fixed, so it has DST)
System.out.println(rules.isFixedOffset()); // false

In the code above, rules.isFixedOffset() returns false, which means that the corresponding timezone's offset changes over time (so, it has DST changes).

To know when those DST changes occur, you must get all the transitions:

// get all transitions (all dates where DST starts or ends)
List<ZoneOffsetTransition> transitions = rules.getTransitions();
transitions.stream().forEach(System.out::println);

This prints lots of lines (as this timezone has DST almost every year). Here's a sample of the last 2 lines:

Transition[Overlap at 2039-02-20T00:00-02:00 to -03:00

  Transition[Gap at 2039-10-16T00:00-03:00 to -02:00]

This means that in 2039-02-20 at midnight, the offset will change from -02:00 to -03:00 (DST ends - clocks move back 1 hour), and in 2039-10-16 at midnight the offset will change from -03:00 to -02:00 (DST starts - clocks move forward 1 hour).

So, if you want to know the offset when it's not DST, you just get the last transition, check if it's a gap or overlap and get the offset after or before:

// get the last transition
ZoneOffsetTransition last = transitions.get(transitions.size() - 1);

// find the offset without DST interference
ZoneOffset offsetWithoutDST;

// overlap means that clock moves back 1 hour (when DST ends)
if(last.isOverlap()) {
    // DST ends, get the offset after it
    offsetWithoutDST = last.getOffsetAfter();
} else {
    // DST starts, get the offset before it
    offsetWithoutDST = last.getOffsetBefore();
}
System.out.println(offsetWithoutDST);

In this case, it prints -03:00, which is the "normal" offset for America/Sao_Paulo timezone (when it's not DST).

PS: please note that DST and even standard offsets can vary a lot over time.

Just because the offset is one today, it doesn't mean it was always the same: governments can change the offset at any time, and in very past dates - like before 1900 - the offsets were much more messy than today (every city had its own time, with offsets like -03:06:28 and so on).

The code above gets the standard (non-DST) offset for the current timezone's rules. If you want to know what was the non-DST offset 30 years ago, you can use @Joachim's answer (passing an Instant of 30 years ago as a parameter).


问:
Animated QGraphicsItem with dashed pen
I'd like to create a rotating circle drawn with a Qt:DotLine pen, using the Graphics View Framework. Using QGraphicsItemAnimation, I can rotate other shapes but not the circle. The program below demonstrates the problem: instead of the rectangle and the circle rotating together, the circle jerks around while the rectangle rotates gracefully.

```<code>#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QTimeLine>
#include <QGraphicsItemAnimation>

QRectF rect (int r)
{
    return QRectF (-r, -r, r * 2, r * 2);
}

void setupRot (QTimeLine *timeline, QGraphicsItem *item)
{
    QGraphicsItemAnimation *animation = new QGraphicsItemAnimation;
    animation->setItem(item);
    animation->setTimeLine(timeline);
    animation->setRotationAt (1, 360);

    QObject::connect (timeline, SIGNAL(finished()), animation, SLOT(deleteLater()));
}

int main(int argc, char *argv[])
{
    QApplication app (argc, argv);

    QGraphicsScene scene;

    QTimeLine *timeline = new QTimeLine;
    timeline->setDuration (3000);
    timeline->setCurveShape (QTimeLine::LinearCurve);
    QObject::connect (timeline, SIGNAL(finished()), timeline, SLOT(deleteLater()));

    setupRot (timeline, scene.addEllipse (rect (50), QPen (QBrush (QColor ("blue")), 8, Qt::DotLine)));
    setupRot (timeline, scene.addRect (rect (60)));
    scene.addEllipse (rect (40), QPen (QBrush (QColor ("red")), 8));

    scene.setSceneRect (-100, -100, 200, 200);
    QGraphicsView view (&scene);
    view.show ();
    timeline->setLoopCount (0);
    timeline->start();
    return app.exec ();
}
</code>```

p.s.: I've found some sample code on the web where people are creating intermediate animation steps manually, like this:

```<code>const int steps = 100;
for (int i = 0; i < steps; ++i)
    animation->setRotationAt (i / (float)steps, 360 / (float)steps * i);
</code>```

Is this just a sign of people not understanding the concept of interpolation, or is there some advantage of setting (seemingly superfluous) control points?

答: Which version/platform? If I run your code as is (or slowed down 2x), the dotted circle rotation looks as good as the rectangle in Windows with Qt 4.7.</p>

Title: Animated QGraphicsItem with dashed pen

Body:
I'd like to create a rotating circle drawn with a Qt:DotLine pen, using the Graphics View Framework. Using QGraphicsItemAnimation, I can rotate other shapes but not the circle. The program below demonstrates the problem: instead of the rectangle and the circle rotating together, the circle jerks around while the rectangle rotates gracefully.

#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QTimeLine>
#include <QGraphicsItemAnimation>

QRectF rect (int r)
{
    return QRectF (-r, -r, r * 2, r * 2);
}

void setupRot (QTimeLine *timeline, QGraphicsItem *item)
{
    QGraphicsItemAnimation *animation = new QGraphicsItemAnimation;
    animation->setItem(item);
    animation->setTimeLine(timeline);
    animation->setRotationAt (1, 360);

    QObject::connect (timeline, SIGNAL(finished()), animation, SLOT(deleteLater()));
}

int main(int argc, char *argv[])
{
    QApplication app (argc, argv);

    QGraphicsScene scene;

    QTimeLine *timeline = new QTimeLine;
    timeline->setDuration (3000);
    timeline->setCurveShape (QTimeLine::LinearCurve);
    QObject::connect (timeline, SIGNAL(finished()), timeline, SLOT(deleteLater()));

    setupRot (timeline, scene.addEllipse (rect (50), QPen (QBrush (QColor ("blue")), 8, Qt::DotLine)));
    setupRot (timeline, scene.addRect (rect (60)));
    scene.addEllipse (rect (40), QPen (QBrush (QColor ("red")), 8));

    scene.setSceneRect (-100, -100, 200, 200);
    QGraphicsView view (&scene);
    view.show ();
    timeline->setLoopCount (0);
    timeline->start();
    return app.exec ();
}

p.s.: I've found some sample code on the web where people are creating intermediate animation steps manually, like this:

const int steps = 100;
for (int i = 0; i < steps; ++i)
    animation->setRotationAt (i / (float)steps, 360 / (float)steps * i);

Is this just a sign of people not understanding the concept of interpolation, or is there some advantage of setting (seemingly superfluous) control points?


问:
Can not draw or change pixels' color on QImage
I'm new to QT and now facing a problem with function QImage::setPixel and QPainter::drawPoint

I have mainwindow and a widget in it, called drawing area. The drawing area using layout with a label in it, which contains QImage converted to QPixmap. Unfortunately the functions I use to draw points give no result.

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

area = new DrawingArea(this);
area->setGeometry(0,0,this->width(),this->height()/2);
area->show();

button = new QPushButton("Draw", this);
int bwidth = 100, bheight = 50;
button->setGeometry(200, 300, bwidth, bheight);
connect(button, SIGNAL(clicked(bool)), this, SLOT(getPoint()));
}

MainWindow::~MainWindow()
{
delete ui;
delete button;
delete area;
}

void MainWindow::getPoint(){
area->clearPoints();
area->makePoint(ui->textEdit->toPlainText().toInt(), ui->textEdit_2-
>toPlainText().toInt());
area->makePoint(ui->textEdit_3->toPlainText().toInt(), ui->textEdit_4-
>toPlainText().toInt());
area->makePoint(ui->textEdit_5->toPlainText().toInt(), ui->textEdit_6-
>toPlainText().toInt());
area->showPoints();
}
</code>```

DrawinArea.cpp

```<code>#include "drawingarea.h"
#include <QHBoxLayout>
#include <QPen>
#include <QPainter>

DrawingArea::DrawingArea(QWidget *parent) : QWidget(parent)
{
setBackgroundRole(QPalette::Base);
setAutoFillBackground(true);

canvas = new QImage(600, 500, QImage::Format_RGB32);
QRgb val = qRgb(189,149,39);
canvas->fill(Qt::gray);
canvas->setPixel(4,4,val);
canvas->setPixel(5,4,val);

imgDisplayer = new QLabel;
imgDisplayer->setPixmap(QPixmap::fromImage(*canvas));

displayer = new QLabel;

auto *layout = new QHBoxLayout(this);
layout->addWidget(imgDisplayer);
layout->addWidget(displayer);
}

void DrawingArea::paintEvent(QPaintEvent * /* event */){
//
}
void DrawingArea::clearPoints(){
points.clear();
}

void DrawingArea::makePoint(int x, int y){
Point *temp = new Point(x,y);
points.push_back(*temp);
free(temp);
}

void DrawingArea::showPoints(){

displayer->clear();
QPainter painter(canvas);
QPen pen;
pen.setWidth(1);
pen.setColor(Qt::red);
painter.setBrush(Qt::NoBrush);
painter.setPen(pen);
painter.end();
QString text;
for(size_t i = 0; i < points.size();i++){
    text+= ("P" + QString::number(i) + " (X: " +
QString::number(points[i].x) +
            "; Y: " + QString::number(points[i].y) + ");\n");
    painter.drawPoint(points[i].x, points[i].y);
}
imgDisplayer->setPixmap(QPixmap::fromImage(*canvas));
displayer->setText(text);
displayer->setGeometry(300, 80, 100,100);

displayer->show();
imgDisplayer->show();

}

DrawingArea::~DrawingArea(){
delete canvas;
delete displayer;
delete imgDisplayer;
}
</code>```

答:
Here is a minimal example. Hope that helps :)

mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
</code>```

mainwindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QImage>
#include <QPainter>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->drawButton, &QPushButton::clicked, [=](){ // Lambda to keep example small. You may also just have a own method
        auto x = ui->xLineEdit->text().toInt();
        auto y = ui->yLineEdit->text().toInt();

        const QPixmap *pixmap = ui->imageLabel->pixmap();
        QImage image(QSize(600, 400), QImage::Format_RGB32);
        if (pixmap) {
            image = pixmap->toImage();
        } else {
            image.fill(Qt::gray);
        }

        QPainter painter(&image);
        auto pen = painter.pen();
        pen.setColor(Qt::red);
        pen.setWidth(5);
        painter.setPen(pen);
        painter.drawPoint(x, y);
        ui->imageLabel->setPixmap(QPixmap::fromImage(image));
        ui->textLabel->setText(ui->textLabel->text().append("\nP(%1,%2)").arg(QString::number(x), QString::number(y)));
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}
</code>```

mainwindow.ui:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>521</width>
    <height>450</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <layout class="QHBoxLayout" name="horizontalLayout">
      <item>
       <widget class="QLabel" name="imageLabel">
        <property name="sizePolicy">
         <sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
          <horstretch>0</horstretch>
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
        <property name="text">
         <string/>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QLabel" name="textLabel">
        <property name="text">
         <string>Points:</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QGridLayout" name="gridLayout">
      <item row="1" column="0">
       <widget class="QLabel" name="label_2">
        <property name="text">
         <string>y:</string>
        </property>
       </widget>
      </item>
      <item row="1" column="1">
       <widget class="QLineEdit" name="yLineEdit"/>
      </item>
      <item row="0" column="1">
       <widget class="QLineEdit" name="xLineEdit"/>
      </item>
      <item row="0" column="0">
       <widget class="QLabel" name="label">
        <property name="text">
         <string>x:</string>
        </property>
       </widget>
      </item>
      <item row="0" column="2">
       <spacer name="horizontalSpacer">
        <property name="orientation">
         <enum>Qt::Horizontal</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>40</width>
          <height>20</height>
         </size>
        </property>
       </spacer>
      </item>
     </layout>
    </item>
    <item>
     <widget class="QPushButton" name="drawButton">
      <property name="text">
       <string>Draw</string>
      </property>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>521</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>
</code>```

Best regards

Body:
I'm new to QT and now facing a problem with function QImage::setPixel and QPainter::drawPoint

I have mainwindow and a widget in it, called drawing area. The drawing area using layout with a label in it, which contains QImage converted to QPixmap. Unfortunately the functions I use to draw points give no result.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

area = new DrawingArea(this);
area->setGeometry(0,0,this->width(),this->height()/2);
area->show();

button = new QPushButton("Draw", this);
int bwidth = 100, bheight = 50;
button->setGeometry(200, 300, bwidth, bheight);
connect(button, SIGNAL(clicked(bool)), this, SLOT(getPoint()));
}

MainWindow::~MainWindow()
{
delete ui;
delete button;
delete area;
}

void MainWindow::getPoint(){
area->clearPoints();
area->makePoint(ui->textEdit->toPlainText().toInt(), ui->textEdit_2-
>toPlainText().toInt());
area->makePoint(ui->textEdit_3->toPlainText().toInt(), ui->textEdit_4-
>toPlainText().toInt());
area->makePoint(ui->textEdit_5->toPlainText().toInt(), ui->textEdit_6-
>toPlainText().toInt());
area->showPoints();
}

DrawinArea.cpp

#include "drawingarea.h"
#include <QHBoxLayout>
#include <QPen>
#include <QPainter>

DrawingArea::DrawingArea(QWidget *parent) : QWidget(parent)
{
setBackgroundRole(QPalette::Base);
setAutoFillBackground(true);

canvas = new QImage(600, 500, QImage::Format_RGB32);
QRgb val = qRgb(189,149,39);
canvas->fill(Qt::gray);
canvas->setPixel(4,4,val);
canvas->setPixel(5,4,val);

imgDisplayer = new QLabel;
imgDisplayer->setPixmap(QPixmap::fromImage(*canvas));

displayer = new QLabel;

auto *layout = new QHBoxLayout(this);
layout->addWidget(imgDisplayer);
layout->addWidget(displayer);
}

void DrawingArea::paintEvent(QPaintEvent * /* event */){
//
}
void DrawingArea::clearPoints(){
points.clear();
}

void DrawingArea::makePoint(int x, int y){
Point *temp = new Point(x,y);
points.push_back(*temp);
free(temp);
}

void DrawingArea::showPoints(){

displayer->clear();
QPainter painter(canvas);
QPen pen;
pen.setWidth(1);
pen.setColor(Qt::red);
painter.setBrush(Qt::NoBrush);
painter.setPen(pen);
painter.end();
QString text;
for(size_t i = 0; i < points.size();i++){
    text+= ("P" + QString::number(i) + " (X: " +
QString::number(points[i].x) +
            "; Y: " + QString::number(points[i].y) + ");\n");
    painter.drawPoint(points[i].x, points[i].y);
}
imgDisplayer->setPixmap(QPixmap::fromImage(*canvas));
displayer->setText(text);
displayer->setGeometry(300, 80, 100,100);

displayer->show();
imgDisplayer->show();

}

DrawingArea::~DrawingArea(){
delete canvas;
delete displayer;
delete imgDisplayer;
}

Body:
Here is a minimal example. Hope that helps :)

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QImage>
#include <QPainter>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->drawButton, &QPushButton::clicked, [=](){ // Lambda to keep example small. You may also just have a own method
        auto x = ui->xLineEdit->text().toInt();
        auto y = ui->yLineEdit->text().toInt();

        const QPixmap *pixmap = ui->imageLabel->pixmap();
        QImage image(QSize(600, 400), QImage::Format_RGB32);
        if (pixmap) {
            image = pixmap->toImage();
        } else {
            image.fill(Qt::gray);
        }

        QPainter painter(&image);
        auto pen = painter.pen();
        pen.setColor(Qt::red);
        pen.setWidth(5);
        painter.setPen(pen);
        painter.drawPoint(x, y);
        ui->imageLabel->setPixmap(QPixmap::fromImage(image));
        ui->textLabel->setText(ui->textLabel->text().append("\nP(%1,%2)").arg(QString::number(x), QString::number(y)));
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

mainwindow.ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>521</width>
    <height>450</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <layout class="QHBoxLayout" name="horizontalLayout">
      <item>
       <widget class="QLabel" name="imageLabel">
        <property name="sizePolicy">
         <sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
          <horstretch>0</horstretch>
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
        <property name="text">
         <string/>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QLabel" name="textLabel">
        <property name="text">
         <string>Points:</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QGridLayout" name="gridLayout">
      <item row="1" column="0">
       <widget class="QLabel" name="label_2">
        <property name="text">
         <string>y:</string>
        </property>
       </widget>
      </item>
      <item row="1" column="1">
       <widget class="QLineEdit" name="yLineEdit"/>
      </item>
      <item row="0" column="1">
       <widget class="QLineEdit" name="xLineEdit"/>
      </item>
      <item row="0" column="0">
       <widget class="QLabel" name="label">
        <property name="text">
         <string>x:</string>
        </property>
       </widget>
      </item>
      <item row="0" column="2">
       <spacer name="horizontalSpacer">
        <property name="orientation">
         <enum>Qt::Horizontal</enum>
        </property>
        <property name="sizeHint" stdset="0">
         <size>
          <width>40</width>
          <height>20</height>
         </size>
        </property>
       </spacer>
      </item>
     </layout>
    </item>
    <item>
     <widget class="QPushButton" name="drawButton">
      <property name="text">
       <string>Draw</string>
      </property>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>521</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

Best regards


问:
Properties file vs environment variable
Hey i wondered what is the difference between .properties file to environment variable in java.

.Properties file

```<code>arg1=text1

arg2=text2
</code>```

environment variable

```<code>java -jar -arg1=text1 -arg2=text2 myJAR.jar
</code>```

答:
Passing arguments in this way is not overridable at runtime :

```<code>java -jar -arg1=text1 -arg2=text2 myJAR.jar
</code>```

as the values are passed when the application is started.

You have to restart the application to change the values.

Besides, passing a lot of arguments may be error prone.

Valuing properties in this way may be overridable at runtime  :

```<code>.Properties file
arg1=text1
arg2=text2
</code>```

As the values are located in a external file that may be modified during the runtime of the application. Of course a way foreseen to take into consideration the file modification during the runtime has to be implemented in the application.

For example, Logback (with Joran implementation) provides a way
to change the Logback configuration file at runtime :
https://logback.qos.ch/manual/configuration.html#joranDirectly

Title: Properties file vs environment variable

Body:
Hey i wondered what is the difference between .properties file to environment variable in java.

.Properties file

arg1=text1

arg2=text2

environment variable

java -jar -arg1=text1 -arg2=text2 myJAR.jar

Body:
Passing arguments in this way is not overridable at runtime :

java -jar -arg1=text1 -arg2=text2 myJAR.jar

as the values are passed when the application is started.

You have to restart the application to change the values.

Besides, passing a lot of arguments may be error prone.

Valuing properties in this way may be overridable at runtime  :

.Properties file
arg1=text1
arg2=text2

As the values are located in a external file that may be modified during the runtime of the application. Of course a way foreseen to take into consideration the file modification during the runtime has to be implemented in the application.

For example, Logback (with Joran implementation) provides a way
to change the Logback configuration file at runtime :
https://logback.qos.ch/manual/configuration.html#joranDirectly