问:
How to get list of volume names from PVC list using ansible?
In my machines , 4 pvc are created. Now i need to get all volume name associated with the pvc in a list. Then those list will be passed to storage array and i will ensure that the volumes are created in storage server.

```<code>- name: Verify whether the PVC is created
    command: "kubectl get pvc pvc{{local_uuid}}-{{item}} -o json"
    with_sequence: start=1 end=4
    register: result

- set_fact:
      pvcstatus: "{{ (item.stdout |from_json).status.phase }}"
      volume_name: "{{(item.stdout |from_json).spec.volumeName}}"
    with_items: "{{ result.results}}"

 - debug: var=volume_name
</code>```

But when i run the above tasks , volume_name is having last volumename alone instead of all the volumes as a list. How to get all the volume names in a list?

答:
Your set_fact task is setting volume_name to a single value in each iteration...so of course, when the loop completes, the variable has the value from the final iteration. That's the expected behavior.  If you want a list, you need to create a list.  You can do this by appending to a list in your set_fact loop:

```<code>- set_fact:
    volume_name: "{{ volume_name|default([]) + [(item.stdout |from_json).spec.volumeName] }}"
  with_items: "{{ result.results}}"
</code>```

The expression volume_name|default([]) will evaluate to an empty list when volume_name is undefined (which is the case on the first iteration of the loop).

I tested this out using the following playbook:

```<code>---
- hosts: localhost
  gather_facts: false
  vars:
    result:
      results:
        - stdout: '{"spec": {"volumeName": "volume1"}}'
        - stdout: '{"spec": {"volumeName": "volume2"}}'
        - stdout: '{"spec": {"volumeName": "volume3"}}'
  tasks:
    - debug:
        var: result

    - set_fact:
        volume_name: "{{ volume_name|default([]) + [(item.stdout |from_json).spec.volumeName] }}"
      with_items: "{{ result.results}}"

    - debug:
        var: volume_name
</code>```

Which results in:

```<code>TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
    "volume_name": [
        "volume1",
        "volume2",
        "volume3"
    ]
}
</code>```

Body:
In my machines , 4 pvc are created. Now i need to get all volume name associated with the pvc in a list. Then those list will be passed to storage array and i will ensure that the volumes are created in storage server.

- name: Verify whether the PVC is created
    command: "kubectl get pvc pvc{{local_uuid}}-{{item}} -o json"
    with_sequence: start=1 end=4
    register: result

- set_fact:
      pvcstatus: "{{ (item.stdout |from_json).status.phase }}"
      volume_name: "{{(item.stdout |from_json).spec.volumeName}}"
    with_items: "{{ result.results}}"

 - debug: var=volume_name

But when i run the above tasks , volume_name is having last volumename alone instead of all the volumes as a list. How to get all the volume names in a list?

Body:
Your set_fact task is setting volume_name to a single value in each iteration...so of course, when the loop completes, the variable has the value from the final iteration. That's the expected behavior.  If you want a list, you need to create a list.  You can do this by appending to a list in your set_fact loop:

- set_fact:
    volume_name: "{{ volume_name|default([]) + [(item.stdout |from_json).spec.volumeName] }}"
  with_items: "{{ result.results}}"

The expression volume_name|default([]) will evaluate to an empty list when volume_name is undefined (which is the case on the first iteration of the loop).

I tested this out using the following playbook:

---
- hosts: localhost
  gather_facts: false
  vars:
    result:
      results:
        - stdout: '{"spec": {"volumeName": "volume1"}}'
        - stdout: '{"spec": {"volumeName": "volume2"}}'
        - stdout: '{"spec": {"volumeName": "volume3"}}'
  tasks:
    - debug:
        var: result

    - set_fact:
        volume_name: "{{ volume_name|default([]) + [(item.stdout |from_json).spec.volumeName] }}"
      with_items: "{{ result.results}}"

    - debug:
        var: volume_name

Which results in:

TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
    "volume_name": [
        "volume1",
        "volume2",
        "volume3"
    ]
}


来源: stackexchange

问:
How to identify if certain keys are present in dictonary?
I have dictonary named as Entity which look like this:

```<code>Entity = {'ORG': 'ABC','PERSON': 'Ankit','ORDINAL': '150th','DATE': 'quarterly', 'MONEY': 'dollars'}
</code>```

Now I have to create other dictionary which will contain below value according to condition.

```<code>Class = {'Signal':'<Condition>'}
</code>```

The condition is:

If Entity key consists of ORG and PERSON then in Class dictionary value "Medium" should be updated.

If Entity key consists of ORG, PERSON, and MONEY then in Class dictionary value "Strong" should be updated.

If Entity key doesn't consist of above keys then in Class dictionary value "Weak" should be updated.

How should I make the condition for the above problem?

I want an output in Class dictionary like below,

If in Entity dictionary there are ORG and PERSIN keys then Class dictionary should be like,

```<code>Class = {'Signal' : 'Medium'}
</code>```

答:
You can use the .keys() function on the dictionary to check before accessing the data structure. For example:

```<code>def does_key_exist(elem, dict):
    return elem in dict.keys()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have dictonary named as Entity which look like this:

Entity = {'ORG': 'ABC','PERSON': 'Ankit','ORDINAL': '150th','DATE': 'quarterly', 'MONEY': 'dollars'}

Now I have to create other dictionary which will contain below value according to condition.

Class = {'Signal':'<Condition>'}

The condition is:

If Entity key consists of ORG and PERSON then in Class dictionary value "Medium" should be updated.

If Entity key consists of ORG, PERSON, and MONEY then in Class dictionary value "Strong" should be updated.

If Entity key doesn't consist of above keys then in Class dictionary value "Weak" should be updated.

How should I make the condition for the above problem?

I want an output in Class dictionary like below,

If in Entity dictionary there are ORG and PERSIN keys then Class dictionary should be like,

Class = {'Signal' : 'Medium'}

Body:
You can use the .keys() function on the dictionary to check before accessing the data structure. For example:

def does_key_exist(elem, dict):
    return elem in dict.keys()


问:
How to extract columns with varying names of a data frame into a list?
I have a data frame df with one date column and 50 other columns with individual stock prices that are named after the respective stock.
The first couple of columns of the data frame basically look like this:

```<code>df
Date        Adidas  Allianz  Shell  IBM  ...
2015-12-01  130     45       200    39
2015-12-02  131     46       199    40
...
</code>```

I want to perform several actions (like calculating the daily return etc.) for which I always want a new column for the output.

As I want to retain an overview, my idea was to extract each stock column together with the Date column and put them in a new data frame to basically create 50 new data frames, one for each stock. Then, I would create a list of these 50 data frames to then perform all following actions with lapply-functions on the list.
I do not want to type each column name into R individually, so is there any function with which I can extract one column after the other and put them into a new data frame always together with the Date column?

My new data should look kind of like this:

```<code>list

dfAdidas
Date        Adidas
2015-12-01  130
2015-12-02  131
...

dfAllianz
Date        Allianz
2015-12-01  45
2015-12-02  46
...
</code>```

and so on.

Thankful for any tips or recommendations how to do this easier!

Body:
I have a data frame df with one date column and 50 other columns with individual stock prices that are named after the respective stock.
The first couple of columns of the data frame basically look like this:

df
Date        Adidas  Allianz  Shell  IBM  ...
2015-12-01  130     45       200    39
2015-12-02  131     46       199    40
...

I want to perform several actions (like calculating the daily return etc.) for which I always want a new column for the output.

As I want to retain an overview, my idea was to extract each stock column together with the Date column and put them in a new data frame to basically create 50 new data frames, one for each stock. Then, I would create a list of these 50 data frames to then perform all following actions with lapply-functions on the list.
I do not want to type each column name into R individually, so is there any function with which I can extract one column after the other and put them into a new data frame always together with the Date column?

My new data should look kind of like this:

list

dfAdidas
Date        Adidas
2015-12-01  130
2015-12-02  131
...

dfAllianz
Date        Allianz
2015-12-01  45
2015-12-02  46
...

and so on.

Thankful for any tips or recommendations how to do this easier!

Body:
An option with base R is to loop over the index and use that index for subsetting columns

lapply(2:ncol(df), function(i) df[c(1, i)])
#[[1]]
#        Date Adidas
#1 2015-12-01    130
#2 2015-12-02    131

#[[2]]
#        Date Allianz
#1 2015-12-01      45
#2 2015-12-02      46

#[[3]]
#        Date Shell
#1 2015-12-01   200
#2 2015-12-02   199

#[[4]]
#        Date IBM
#1 2015-12-01  39
#2 2015-12-02  40

data

df <- structure(list(Date = c("2015-12-01", "2015-12-02"), Adidas = 130:131,
Allianz = 45:46, Shell = 200:199, IBM = 39:40),
 class = "data.frame", row.names = c(NA, -2L))


问:
How to get text instead of value in ASP.NET MVC calculated field for list item?
In the following model class I am attempting to create a calculated field called FullAddress.  I am able to get it to work, but right now it displays the values and not the text for 4 different ID fields.  I would like to display the text instead of the value for the following fields:

TLRoadDirectionID

TLRoadTypeID

VendorAddUnitTypeOneID

VendorAddUnitTypeTwoID

I received some great help earlier on correctly creating FullAddress, so I know that if I were to change the fields to:

TLRoadDirection.Direction

TLRoadType.RdType

TLUnitTypeOne.UnitType

TLUnitTypeTwo.UnitType

then it works as expected, but only if all of those 4 fields contain a value and are not null or empty.  But these fields will not always have values for each record.

So, how can I modify this calculated field to show the text for each when there is text to show, and not get a null reference exception when any or all of these 4 fields are null or empty?

Below is the class (please let me know if additional information is required):

```<code>using System;
using System.ComponentModel.DataAnnotations;
using System.Web;

namespace VendorMgr.Models
{
public class Vendor
{
    [Display(Name = "Vendor ID")]
    public int ID { get; set; }

    private string _createdBy = HttpContext.Current.User.Identity.Name;
    [Required]
    [Display(Name = "Created By")]
    public string VendorCreatedBy
    {
        get
        {
            return (_createdBy == HttpContext.Current.User.Identity.Name) ? HttpContext.Current.User.Identity.Name : _createdBy;
        }
        set
        {
            _createdBy = HttpContext.Current.User.Identity.Name;
        }
    }

    private DateTime _createdOn = DateTime.Now;
    [Required]
    [Display(Name = "Date Created")]
    [DataType(DataType.DateTime)]
    public DateTime VendorCreatedDt
    {
        get
        {
            return (_createdOn == DateTime.Now) ? DateTime.Now : _createdOn;
        }
        set
        {
            _createdOn = value;
        }
    }

    [Required]
    [StringLength(128)]
    [Display(Name = "Vendor Name")]
    public string VendorName { get; set; }

    [Display(Name = "Phone Number")]
    [DataType(DataType.PhoneNumber)]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
    public string VendorPhoneNumber { get; set; }

    [Display(Name = "Email")]
    [StringLength(255)]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string VendorEmail { get; set; }

    [Display(Name = "Address Number")]
    [StringLength(10)]
    public string VendorAddNum { get; set; }

    [Display(Name = "Direction")]
    public int? TLRoadDirectionID { get; set; }

    [Display(Name = "Road Name")]
    [StringLength(128)]
    public string VendorAddName { get; set; }

    [Display(Name = "Road Type")]
    public int? TLRoadTypeID { get; set; }

    [Display(Name = "Unit Type")]
    public int? VendorAddUnitTypeOneID { get; set; }

    [Display(Name = "Unit")]
    [StringLength(20)]
    public string VendorAddUnitOne { get; set; }

    [Display(Name = "Unit Type")]
    public int? VendorAddUnitTypeTwoID { get; set; }

    [Display(Name = "Unit")]
    [StringLength(20)]
    public string VendorAddUnitTwo { get; set; }

    [Display(Name = "Full Address")]
    public string FullAddress
    {
        get
        {
            return $"{VendorAddNum} {TLRoadDirectionID} {VendorAddName} {TLRoadTypeID} {VendorAddUnitTypeOneID} {TLUnitTypeOne.UnitType} {VendorAddUnitOne} {VendorAddUnitTypeTwoID} {VendorAddUnitTwo}";
        }
    }

    [Display(Name = "City")]
    [StringLength(128)]
    public string VendorAddCity { get; set; }

    [Display(Name = "State")]
    public int? TLStateAcronymnID { get; set; }

    [Display(Name = "Zip Code")]
    [StringLength(20)]
    public string VendorZipCode { get; set; }

    [Display(Name = "Country")]
    public int? TLCountryID { get; set; }

    [Display(Name = "Active")]
    public bool VendorActive { get; set; }

    public virtual TLRoadDirection TLRoadDirection { get; set; }
    public virtual TLRoadType TLRoadType { get; set; }
    public virtual TLUnitType TLUnitTypeOne { get; set; }
    public virtual TLUnitType TLUnitTypeTwo { get; set; }
    public virtual TLStateAcronymn TLStateAcronymn { get; set; }
    public virtual TLCountry TLCountry { get; set; }
}
</code>```

}

答: I chose to just handle this in the view instead of the model class.</p>

Body:
In the following model class I am attempting to create a calculated field called FullAddress.  I am able to get it to work, but right now it displays the values and not the text for 4 different ID fields.  I would like to display the text instead of the value for the following fields:

TLRoadDirectionID

TLRoadTypeID

VendorAddUnitTypeOneID

VendorAddUnitTypeTwoID

I received some great help earlier on correctly creating FullAddress, so I know that if I were to change the fields to:

TLRoadDirection.Direction

TLRoadType.RdType

TLUnitTypeOne.UnitType

TLUnitTypeTwo.UnitType

then it works as expected, but only if all of those 4 fields contain a value and are not null or empty.  But these fields will not always have values for each record.

So, how can I modify this calculated field to show the text for each when there is text to show, and not get a null reference exception when any or all of these 4 fields are null or empty?

Below is the class (please let me know if additional information is required):

using System;
using System.ComponentModel.DataAnnotations;
using System.Web;

namespace VendorMgr.Models
{
public class Vendor
{
    [Display(Name = "Vendor ID")]
    public int ID { get; set; }

    private string _createdBy = HttpContext.Current.User.Identity.Name;
    [Required]
    [Display(Name = "Created By")]
    public string VendorCreatedBy
    {
        get
        {
            return (_createdBy == HttpContext.Current.User.Identity.Name) ? HttpContext.Current.User.Identity.Name : _createdBy;
        }
        set
        {
            _createdBy = HttpContext.Current.User.Identity.Name;
        }
    }

    private DateTime _createdOn = DateTime.Now;
    [Required]
    [Display(Name = "Date Created")]
    [DataType(DataType.DateTime)]
    public DateTime VendorCreatedDt
    {
        get
        {
            return (_createdOn == DateTime.Now) ? DateTime.Now : _createdOn;
        }
        set
        {
            _createdOn = value;
        }
    }

    [Required]
    [StringLength(128)]
    [Display(Name = "Vendor Name")]
    public string VendorName { get; set; }

    [Display(Name = "Phone Number")]
    [DataType(DataType.PhoneNumber)]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
    public string VendorPhoneNumber { get; set; }

    [Display(Name = "Email")]
    [StringLength(255)]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string VendorEmail { get; set; }

    [Display(Name = "Address Number")]
    [StringLength(10)]
    public string VendorAddNum { get; set; }

    [Display(Name = "Direction")]
    public int? TLRoadDirectionID { get; set; }

    [Display(Name = "Road Name")]
    [StringLength(128)]
    public string VendorAddName { get; set; }

    [Display(Name = "Road Type")]
    public int? TLRoadTypeID { get; set; }

    [Display(Name = "Unit Type")]
    public int? VendorAddUnitTypeOneID { get; set; }

    [Display(Name = "Unit")]
    [StringLength(20)]
    public string VendorAddUnitOne { get; set; }

    [Display(Name = "Unit Type")]
    public int? VendorAddUnitTypeTwoID { get; set; }

    [Display(Name = "Unit")]
    [StringLength(20)]
    public string VendorAddUnitTwo { get; set; }

    [Display(Name = "Full Address")]
    public string FullAddress
    {
        get
        {
            return $"{VendorAddNum} {TLRoadDirectionID} {VendorAddName} {TLRoadTypeID} {VendorAddUnitTypeOneID} {TLUnitTypeOne.UnitType} {VendorAddUnitOne} {VendorAddUnitTypeTwoID} {VendorAddUnitTwo}";
        }
    }

    [Display(Name = "City")]
    [StringLength(128)]
    public string VendorAddCity { get; set; }

    [Display(Name = "State")]
    public int? TLStateAcronymnID { get; set; }

    [Display(Name = "Zip Code")]
    [StringLength(20)]
    public string VendorZipCode { get; set; }

    [Display(Name = "Country")]
    public int? TLCountryID { get; set; }

    [Display(Name = "Active")]
    public bool VendorActive { get; set; }

    public virtual TLRoadDirection TLRoadDirection { get; set; }
    public virtual TLRoadType TLRoadType { get; set; }
    public virtual TLUnitType TLUnitTypeOne { get; set; }
    public virtual TLUnitType TLUnitTypeTwo { get; set; }
    public virtual TLStateAcronymn TLStateAcronymn { get; set; }
    public virtual TLCountry TLCountry { get; set; }
}

}


问:
How to align the child of a FlatButton
I am trying to align 2 Texts and an Image as a child of a FlatButton (like this) but somehow the elements don't align as they should.

I tried using Stack, Align, Rows and so on but I weren't really successful (I am also a beginner when it comes to dart or flutter)

```<code>new ButtonTheme(
          minWidth: 171,
          height: 176,
          child:new Container(
                decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(19),
                gradient: new LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color(0xFF8F94FB),
                    Color(0xFF5D62D4)
                  ]
                )
                ),
                child: FlatButton(
                  onPressed: () => handleButtonClick(),
                  shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(19)
                  ),
                  child: new Stack(
                    children: <Widget>[
                      Align(
                        alignment: Alignment.bottomLeft,
                        child: Image.asset('assets/daily_icon.png', width: 109, height: 109),
                      )
                    ],
                  ),
                  ),
              ),
          ),
</code>```

This is the result:Image

答:
Replace your FlatButton with below code and see if it works for you.</p>

```<code>     FlatButton(
                padding: const EdgeInsets.all(0),
                onPressed: () => {

                },
                shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(19)
                ),
                child: new Stack(
                  children: <Widget>[
                    Container(
                      width: 109,
                      height: 109,
                      child: Align(
                        alignment: Alignment.bottomLeft,
                        child: Image.asset('assets/demo.png',fit: BoxFit.fitHeight,),
                      ),
                    ),

                  ],
                ),
              ),
</code>```

Title: How to align the child of a FlatButton

Body:
I am trying to align 2 Texts and an Image as a child of a FlatButton (like this) but somehow the elements don't align as they should.

I tried using Stack, Align, Rows and so on but I weren't really successful (I am also a beginner when it comes to dart or flutter)

new ButtonTheme(
          minWidth: 171,
          height: 176,
          child:new Container(
                decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(19),
                gradient: new LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color(0xFF8F94FB),
                    Color(0xFF5D62D4)
                  ]
                )
                ),
                child: FlatButton(
                  onPressed: () => handleButtonClick(),
                  shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(19)
                  ),
                  child: new Stack(
                    children: <Widget>[
                      Align(
                        alignment: Alignment.bottomLeft,
                        child: Image.asset('assets/daily_icon.png', width: 109, height: 109),
                      )
                    ],
                  ),
                  ),
              ),
          ),

This is the result:Image

Body:
Replace your FlatButton with below code and see if it works for you.

     FlatButton(
                padding: const EdgeInsets.all(0),
                onPressed: () => {

                },
                shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(19)
                ),
                child: new Stack(
                  children: <Widget>[
                    Container(
                      width: 109,
                      height: 109,
                      child: Align(
                        alignment: Alignment.bottomLeft,
                        child: Image.asset('assets/demo.png',fit: BoxFit.fitHeight,),
                      ),
                    ),

                  ],
                ),
              ),


问:
How get days name from two days in swift
I have two dates, date1 and date2 and I want days between date1 and date 2

Example:

```<code>let date1 = 28-May-2019,
let date2 = 31-May-2019
</code>```

The expected output

[Tue, Web Thr, Fri]

答:
Try this -</p>

```<code>func getWeekdays(dateOne firstDateStr: String, dateTwo secondDateStr: String) -> [String] {

    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "dd-MMM-yyyy"

    guard let firstDate = dateformatter.date(from: firstDateStr),
        let secondDate = dateformatter.date(from: secondDateStr) else {
            return []
    }

    let calendar = Calendar.current
    let numberOfDays: Int

    if firstDate > secondDate {
        numberOfDays = (calendar.dateComponents([.day], from: secondDate, to: firstDate).day ?? 0)
    } else {
        numberOfDays = (calendar.dateComponents([.day], from: firstDate, to: secondDate).day ?? 0)
    }
    dateformatter.dateFormat = "EEE"

    let days = (0...numberOfDays).compactMap { day -> String? in
        if let date = calendar.date(byAdding: .day, value: day, to: firstDate) {
            return dateformatter.string(from: date)
        }
        return nil
    }
    print(days)

    return days
}
</code>```

Body:
I have two dates, date1 and date2 and I want days between date1 and date 2

Example:

let date1 = 28-May-2019,
let date2 = 31-May-2019

The expected output

[Tue, Web Thr, Fri]

Body:
Try this -

func getWeekdays(dateOne firstDateStr: String, dateTwo secondDateStr: String) -> [String] {

    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "dd-MMM-yyyy"

    guard let firstDate = dateformatter.date(from: firstDateStr),
        let secondDate = dateformatter.date(from: secondDateStr) else {
            return []
    }

    let calendar = Calendar.current
    let numberOfDays: Int

    if firstDate > secondDate {
        numberOfDays = (calendar.dateComponents([.day], from: secondDate, to: firstDate).day ?? 0)
    } else {
        numberOfDays = (calendar.dateComponents([.day], from: firstDate, to: secondDate).day ?? 0)
    }
    dateformatter.dateFormat = "EEE"

    let days = (0...numberOfDays).compactMap { day -> String? in
        if let date = calendar.date(byAdding: .day, value: day, to: firstDate) {
            return dateformatter.string(from: date)
        }
        return nil
    }
    print(days)

    return days
}


问:
Selenium Web driver is not able to find the div class in Google Chrome webstore
I want to crawl some data from Google Chrome Website. But I am facing a problem whenever trying to use selenium webdriver. When I use following code I get an error stating that this element doesn't exist in the site.

```<code>button = driver.find_element_by_class_name("a-d-l-L")
</code>```

Snapshot of the website:

And also, how to get data from a pop up window (this window comes up when I press a button). Following screen can be found on the next page. I want to store the data that is showing in the pop up message.

答: Google has special permissions on the Chrome Webstore, as of now you can't use Selenium to automate any page on the Chrome Webstore website.</p>

Body:
I want to crawl some data from Google Chrome Website. But I am facing a problem whenever trying to use selenium webdriver. When I use following code I get an error stating that this element doesn't exist in the site.

button = driver.find_element_by_class_name("a-d-l-L")

Snapshot of the website:

And also, how to get data from a pop up window (this window comes up when I press a button). Following screen can be found on the next page. I want to store the data that is showing in the pop up message.


问:
Django code only works in debug
Very confused about this one. This code in views.py works, but only when I'm debugging using Pycharm. If I just do runserver I get a 500 error.

views.py:

```<code>def add_post(request):
if request.method == 'POST':
    form = PostForm(request.POST)
    cd = form.cleaned_data
    if form.is_valid():
        print "valid"
        post = Post(nickname=cd['nickname'], body=cd['body'], category=cd['category'])
        post.save()

        return HttpResponse("success")

return HttpResponseServerError("fail")
</code>```

Error as seen in Chrome Inspector

```<code>     <th>Exception Value:</th>
  <td>```'PostForm' object has no attribute 'cleaned_data'```</td>
</code>```

No attribute cleaned_data? But why...?

答: The cleaned_data attribute becomes available after calling is_valid() on a form. You should move cd = form.cleaned_data to below the if.

ContentLicense: CC BY-SA 3.0

Title: Django code only works in debug

Body:
Very confused about this one. This code in views.py works, but only when I'm debugging using Pycharm. If I just do runserver I get a 500 error.

views.py:

def add_post(request):
if request.method == 'POST':
    form = PostForm(request.POST)
    cd = form.cleaned_data
    if form.is_valid():
        print "valid"
        post = Post(nickname=cd['nickname'], body=cd['body'], category=cd['category'])
        post.save()

        return HttpResponse("success")

return HttpResponseServerError("fail")

Error as seen in Chrome Inspector

     Exception Value:

'PostForm' object has no attribute 'cleaned_data'

No attribute cleaned_data? But why...?


问:
Pandas still converts ints to float when I make a dictionary
Pandas still makes ints into floats when I try to make a mixed-type series into a dictionary.

The suggested workarounds don't work for me. I've tried casting to object and using iteritems, and both together. I'm using pandas version 0.24.2

```<code>test_series = pd.Series([1,1.3])
result = [{index:value} for index,value in test_series.astype(object).iteritems()]
print (results)
</code>```

Expected :

```<code>[{0: 1}, {1: 1.3}]
</code>```

Actual :

```<code>[{0: 1.0}, {1: 1.3}]
</code>```

答:
You can use the function is_integer() to check if your float is an integer

```<code>test_series = pd.Series([int(1),1.3])
results = [{index:int(value)} if value.is_integer() else {index:value} for index,value in test_series.iteritems()]
print (results)
</code>```

Out :

```<code>[{0: 1}, {1: 1.3}]
</code>```

Body:
Pandas still makes ints into floats when I try to make a mixed-type series into a dictionary.

The suggested workarounds don't work for me. I've tried casting to object and using iteritems, and both together. I'm using pandas version 0.24.2

test_series = pd.Series([1,1.3])
result = [{index:value} for index,value in test_series.astype(object).iteritems()]
print (results)

Expected :

[{0: 1}, {1: 1.3}]

Actual :

[{0: 1.0}, {1: 1.3}]

Body:
You can use the function is_integer() to check if your float is an integer

test_series = pd.Series([int(1),1.3])
results = [{index:int(value)} if value.is_integer() else {index:value} for index,value in test_series.iteritems()]
print (results)

Out :

[{0: 1}, {1: 1.3}]


问:
IE crossing out pseudo element CSS?
I've been trying to get a few pseudo elements to work on IE, but it just doesn't let me.

It crosses out the CSS and acts like it's not there, which kinda aggrevates me.

Would anyone know what I'm doing wrong?

.newbutton {
  border-radius: 50%;
  width: 74px;
  height: 74px;
  position: relative;
  background-color: black;
  margin: 60px 0px 25px 17px;
  overflow: visible;
}

.newbutton:before {
  content: "f";
  width: 80px;
  height: 80px;
  position: absolute;
  border-radius: 50%;
  z-index: -1;
  top: 37px;
  left: 37px;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  -webkit-animation-name: fadecolor;
  -webkit-animation-duration: 5s;
  -webkit-animation-iteration-count: infinite;
  animation-name: fadecolor;
  animation-duration: 5s;
  animation-iteration-count: infinite;
}

.newbutton:after {
  content: "";
  width: 80px;
  height: 80px;
  position: absolute;
  border-radius: 50%;
  z-index: -2;
  top: -3px;
  left: -3px;
  background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#01BAE8), to(#0183D5));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="starttour">
  <div class="newbutton headerbutton">
    <span class="iconhead icon-02-arrow-icon"></span>
  </div>
  <p>START TOUR</p>
</div></code>```

Screenshot of what happens:

答:
Check out this link  "http://stackoverflow.com/questions/2587669/can-i-use-the-after-pseudo-element-on-an-input-field", as quoted from this link

:after and :before are not supported in Internet Explorer 7 and under, on any elements.

It's also not meant to be used on replaced elements such as form elements (inputs) and image elements.

In other words it's impossible with pure CSS.

/*
 * The trick is here:
 * this selector says "take the first dom element after
 * the input text (+) and set its before content to the
 * value (:before).
 */

input#myTextField + *:before {
       content: "";
    }
```

Title: IE crossing out pseudo element CSS?

Body:
I've been trying to get a few pseudo elements to work on IE, but it just doesn't let me.

It crosses out the CSS and acts like it's not there, which kinda aggrevates me.

Would anyone know what I'm doing wrong?

.newbutton {
  border-radius: 50%;
  width: 74px;
  height: 74px;
  position: relative;
  background-color: black;
  margin: 60px 0px 25px 17px;
  overflow: visible;
}

.newbutton:before {
  content: "f";
  width: 80px;
  height: 80px;
  position: absolute;
  border-radius: 50%;
  z-index: -1;
  top: 37px;
  left: 37px;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  -webkit-animation-name: fadecolor;
  -webkit-animation-duration: 5s;
  -webkit-animation-iteration-count: infinite;
  animation-name: fadecolor;
  animation-duration: 5s;
  animation-iteration-count: infinite;
}

.newbutton:after {
  content: "";
  width: 80px;
  height: 80px;
  position: absolute;
  border-radius: 50%;
  z-index: -2;
  top: -3px;
  left: -3px;
  background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#01BAE8), to(#0183D5));
}

START TOUR

Screenshot of what happens:


问:
@Inject fields are all null inside mocked object
I'm trying to write a UI test using Espresso, I have a view model that I need to mock. But inside this mocked viewmodel there're several @Inject fields that are null, which causing all sorts of trouble.

Here's the view model itself (Names changed and stuff for simplicity but the code is exactly the same)

```<code>public class MyViewModel extends ViewModel {

    private final MyFieldRepository myFieldRepository;

    @Inject
    public MyViewModel(MyFieldRepository myField) {
        this.myFieldRepository = myField; //remains null
    }

    public void start() { //NPE here
        myFieldRepository.startAPI() //... async call code
    }
}
</code>```

And the view model Dagger Module

```<code>@Module
public class MyViewModelModule {
    @Provides
    @IntoMap
    @ViewModelKey(MyViewModel.class)
    public ViewModel providesMyViewModel() {
        MyViewModel myViewModel = Mockito.mock(MyViewModel.class);
        return pinPadViewModel;
    }
}
</code>```

And finally the field module (that I wanted to be injected)

```<code>@Module
public class MyFieldRepositoryModule {
    @Provides
    @AppScoped
    public MyFieldRepository providesMyField() {
        MyFieldRepository myField = Mockito.mock(MyFieldRepository.class);
        return myField;
    }
}
</code>```

And here's the component code:

```<code>@AppScoped
@Component(modules = {
        MyViewModelModule.class,
        MyFieldModule.class,
})

public interface TestAppComponent extends AndroidInjector<TestApp> {
    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);

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

I want to find a way for myField to be injected by Dagger using MyFieldModule.

答:
You have to Use ViewModelProvider.Factory to provide dependency </p>

```<code>@Singleton
class ViewModelFactory @Inject constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(modelClass: Class<T>): T = viewModels[modelClass]?.get() as T
}
</code>```

Body:
I'm trying to write a UI test using Espresso, I have a view model that I need to mock. But inside this mocked viewmodel there're several @Inject fields that are null, which causing all sorts of trouble.

Here's the view model itself (Names changed and stuff for simplicity but the code is exactly the same)

public class MyViewModel extends ViewModel {

    private final MyFieldRepository myFieldRepository;

    @Inject
    public MyViewModel(MyFieldRepository myField) {
        this.myFieldRepository = myField; //remains null
    }

    public void start() { //NPE here
        myFieldRepository.startAPI() //... async call code
    }
}

And the view model Dagger Module

@Module
public class MyViewModelModule {
    @Provides
    @IntoMap
    @ViewModelKey(MyViewModel.class)
    public ViewModel providesMyViewModel() {
        MyViewModel myViewModel = Mockito.mock(MyViewModel.class);
        return pinPadViewModel;
    }
}

And finally the field module (that I wanted to be injected)

@Module
public class MyFieldRepositoryModule {
    @Provides
    @AppScoped
    public MyFieldRepository providesMyField() {
        MyFieldRepository myField = Mockito.mock(MyFieldRepository.class);
        return myField;
    }
}

And here's the component code:

@AppScoped
@Component(modules = {
        MyViewModelModule.class,
        MyFieldModule.class,
})

public interface TestAppComponent extends AndroidInjector<TestApp> {
    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);

        TestAppComponent build();
    }
}

I want to find a way for myField to be injected by Dagger using MyFieldModule.

Body:
You have to Use ViewModelProvider.Factory to provide dependency

@Singleton
class ViewModelFactory @Inject constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(modelClass: Class<T>): T = viewModels[modelClass]?.get() as T
}


问:
Issue while hitting Post Method api in swift
I'm trying to call an API in which I'm trying to send some parameters and array of images, but when I hit the API I get an error, Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance 0xfb47bab3e1e91166'. I have checked through breakpoint it crashes on parameters, I'm confused why it is giving this error, my code for the API is this,

```<code>func addAPI()
{
    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]

    let parameters :[String: Any]  = ["name":productNameTxt.text!,
                                      "price":priceTxt.text!,
                                      "size": sizeTxt.text!,
                                      "weight":weightTxt.text!,
                                      "quality":qualityTxt.text!,
                                      "brand":brandTxt.text!,
                                      "shippingCost":shippingCostTxt.text!,
                                      "details":detailTxt.text!,
                                      "material_id":materialId,
                                      "material_type_id": subMaterialId,
                                      "maxQuantity":4]

    Alamofire.upload(multipartFormData: { multipartFormData in

        for (key, value) in parameters {
            if let data = ((value) as AnyObject).data(using: String.Encoding.utf8.rawValue) {
                multipartFormData.append(data, withName: key)

            }
        }

        for (index, image) in self.imageArray.enumerated() {
            multipartFormData.append(image.pngData()!, withName: "file", fileName: "image\(index).png", mimeType: "image/png")
        }
</code>```

//            for i in 0..

```<code>    },
                     to: addProductUrl,method:HTTPMethod.post,
                     headers:headers, encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload
                                .validate()
                                .responseJSON { response in
                                    switch response.result {
                                    case .success(let value):
                                      //  compBlock(value as AnyObject,true)
                                        print("responseObject: \(value)")
                                    case .failure(let responseError):
                                        print("responseError: \(responseError)")
                                    }
                            }
                        case .failure(let encodingError):
                            print("encodingError: \(encodingError)")
                            let errorDesc = (encodingError as NSError).localizedDescription
                            //failure(errorDesc as NSString,false)
                        }
    })

}
</code>```

What is this error for and how I can remove it?

答:
From here

```<code>if let data = ((value) as AnyObject).data(using: String.Encoding.utf8.rawValue) {
</code>```

then any passed value have to be converted to Data and since you specify an integer ( NSNumber when wrapped inside json)    hence the crash so change 4 to "4" and

```<code>"material_id":"\(materialId)",
</code>```

Body:
I'm trying to call an API in which I'm trying to send some parameters and array of images, but when I hit the API I get an error, Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance 0xfb47bab3e1e91166'. I have checked through breakpoint it crashes on parameters, I'm confused why it is giving this error, my code for the API is this,

func addAPI()
{
    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]

    let parameters :[String: Any]  = ["name":productNameTxt.text!,
                                      "price":priceTxt.text!,
                                      "size": sizeTxt.text!,
                                      "weight":weightTxt.text!,
                                      "quality":qualityTxt.text!,
                                      "brand":brandTxt.text!,
                                      "shippingCost":shippingCostTxt.text!,
                                      "details":detailTxt.text!,
                                      "material_id":materialId,
                                      "material_type_id": subMaterialId,
                                      "maxQuantity":4]

    Alamofire.upload(multipartFormData: { multipartFormData in

        for (key, value) in parameters {
            if let data = ((value) as AnyObject).data(using: String.Encoding.utf8.rawValue) {
                multipartFormData.append(data, withName: key)

            }
        }

        for (index, image) in self.imageArray.enumerated() {
            multipartFormData.append(image.pngData()!, withName: "file", fileName: "image\(index).png", mimeType: "image/png")
        }

//            for i in 0..

    },
                     to: addProductUrl,method:HTTPMethod.post,
                     headers:headers, encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload
                                .validate()
                                .responseJSON { response in
                                    switch response.result {
                                    case .success(let value):
                                      //  compBlock(value as AnyObject,true)
                                        print("responseObject: \(value)")
                                    case .failure(let responseError):
                                        print("responseError: \(responseError)")
                                    }
                            }
                        case .failure(let encodingError):
                            print("encodingError: \(encodingError)")
                            let errorDesc = (encodingError as NSError).localizedDescription
                            //failure(errorDesc as NSString,false)
                        }
    })

}

What is this error for and how I can remove it?

Body:
From here

if let data = ((value) as AnyObject).data(using: String.Encoding.utf8.rawValue) {

then any passed value have to be converted to Data and since you specify an integer ( NSNumber when wrapped inside json)    hence the crash so change 4 to "4" and

"material_id":"\(materialId)",


问:
Pull huge data from MySQL
Trying to pull huge data [about 200,000 rows] from MySQL using PHP.
Getting the error: PHP Fatal error:  Allowed memory size of xxxxx bytes exhausted

I have an application which generates almost 80-90 thousand trasnactions every month. This is a growing application, so I can expect the numbers to grow rapidly.
While generating the monthly or quaterly report, I am getting the memory size error. I tried to increase the allowed memory and it worked.
But I know allowing more memory is a temprary fix and is not a good practice in long run.

I need some help in scaling this application.

In my opinion, breaking the query result into multiple manageable chunks and join them together should solve the problem.

Is there any alternative/better solution?

Does NoSQL helps here? how?

Edit:

Here is the way data is used:
The transaction table containes all transaction details along with the references to master data like user-id, place/location id, type of transacation.

The report will:

Pull the records from transaction table

Replace master references appropriately [replace user-id with name, address, etc]

Dump the data in csv/xls format

Store/download the file

Thanks

答:
A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over. for example</p>

```<code>function getRecords()
{
  $sql = 'SELECT field1, field2,field3 FROM table';
  $results=$db->query($sql);
  while ($row = $results->fetch_assoc())) {
    yield $row;
 }
}

foreach ($this->getRecords() as $record) {
  //process records here
}
</code>```

Title: Pull huge data from MySQL

Body:
A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over. for example

function getRecords()
{
  $sql = 'SELECT field1, field2,field3 FROM table';
  $results=$db->query($sql);
  while ($row = $results->fetch_assoc())) {
    yield $row;
 }
}

foreach ($this->getRecords() as $record) {
  //process records here
}


答:
The following code gives you the days between two dates and should account for trickeries with the calendar.</p>

```<code>let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
let dateFrom = dateFormatter.date(from: "28-May-2019")!
let dateTo = dateFormatter.date(from: "31-May-2019")!

var days: [String] = []
var date = dateFrom
while date <= dateTo {
    let day = dayFormatter.string(from: date)
    days.append(day)
    date = calendar.date(byAdding: .day, value: 1, to: date)!
}
print(days)
</code>```

Title: How get days name from two days in swift

Body:
The following code gives you the days between two dates and should account for trickeries with the calendar.

let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
let dateFrom = dateFormatter.date(from: "28-May-2019")!
let dateTo = dateFormatter.date(from: "31-May-2019")!

var days: [String] = []
var date = dateFrom
while date <= dateTo {
    let day = dayFormatter.string(from: date)
    days.append(day)
    date = calendar.date(byAdding: .day, value: 1, to: date)!
}
print(days)


问:
Is it possible to generate small executables with MINGW g++?
I understand that MINGW-g++ compiles larger executables because it statically links many things. On the other hand MSVC++ links dynamically against DLLs from the VCRedist package, and that is why it produces way smaller executables.

However, is it possible to compile with g++ in a similar manner on windows? Not necessarily MINGW-g++ but something that I can use with Qt Creator (I didn't add Qt as a tag because it's irrelevant to the question).

答:
MinGW is perfectly capable of linking to the msvcrt runtime dynamically. The only mess you're not getting rid of this way is GCC/MinGW startup code, which is not very large.

A small C++ test program (simple iostream hello world program, note: I got the same results for a plain C printf version).

```<code>#include <iostream>

using namespace std;

int main()
{
cout << "Hello World!" << endl;
return 0;
}
</code>```

Commandlines:

```<code>g++ main.cpp -MD -Os -s -o test.exe
cl /MD /Os main.cpp /link /out:test2.exe
</code>```

Executable file sizes:

GCC: 13kB

MSVC: 6kB

Although this is double, all necessary startup code accounts for the large difference; for larger programs, the difference is negligible.

Body:
MinGW is perfectly capable of linking to the msvcrt runtime dynamically. The only mess you're not getting rid of this way is GCC/MinGW startup code, which is not very large.

A small C++ test program (simple iostream hello world program, note: I got the same results for a plain C printf version).

#include <iostream>

using namespace std;

int main()
{
cout << "Hello World!" << endl;
return 0;
}

Commandlines:

g++ main.cpp -MD -Os -s -o test.exe
cl /MD /Os main.cpp /link /out:test2.exe

Executable file sizes:

GCC: 13kB

MSVC: 6kB

Although this is double, all necessary startup code accounts for the large difference; for larger programs, the difference is negligible.


问:
Glob only returning first file in folder
I'm trying to extract all .txt files in a folder using Glob, when I run the below code on it's own, it returns all files:

```<code>import os
for f in os.listdir(folder):
    if f.endswith('.txt'):
       #Do Something
</code>```

However, when I add this into a function and call it only the first .txt file in the folder is returned. I can't figure out why, can anyone help?

```<code>def read_files(path):
    list = []
    import os
    for f in os.listdir(folder):
        if f.endswith('.txt'):
           list.append(os.path.join(folder, f))
           return list
</code>```

答: you return from your function immediately after processing your first file. You need to dedent return list to be outside of the for loop.

Body:
I'm trying to extract all .txt files in a folder using Glob, when I run the below code on it's own, it returns all files:

import os
for f in os.listdir(folder):
    if f.endswith('.txt'):
       #Do Something

However, when I add this into a function and call it only the first .txt file in the folder is returned. I can't figure out why, can anyone help?

def read_files(path):
    list = []
    import os
    for f in os.listdir(folder):
        if f.endswith('.txt'):
           list.append(os.path.join(folder, f))
           return list


问:
PDO general error: 2006 mysql server has gone away
I am using linux and tried to create some tables using php 7.2 but it will give an error as follows, when I execute command. Can anyone help me to fix this problem?

[PDOException] SQLSTATE[HY000] [2006] MySQL server has gone away

  [ErrorException] PDO::__construct(): MySQL server has gone away

```<code>class Database extends PDO{
    function __construct(){
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        try{
            parent::__construct(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',DB_USER,DB_PASS, $options);
        }catch (PDOException $e) {
            echo "Got PDOException\n";
            var_dump($this);
        }

    }
}
</code>```

I can not set the instructions for this page to the class I have
https://dev.mysql.com/doc/refman/8.0/en/gone-away.html

Body:
I am using linux and tried to create some tables using php 7.2 but it will give an error as follows, when I execute command. Can anyone help me to fix this problem?

[PDOException] SQLSTATE[HY000] [2006] MySQL server has gone away

  [ErrorException] PDO::__construct(): MySQL server has gone away

class Database extends PDO{
    function __construct(){
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        try{
            parent::__construct(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',DB_USER,DB_PASS, $options);
        }catch (PDOException $e) {
            echo "Got PDOException\n";
            var_dump($this);
        }

    }
}

I can not set the instructions for this page to the class I have
https://dev.mysql.com/doc/refman/8.0/en/gone-away.html

Body: $db->exec('SET session wait_timeout=60');


问:
How to replace a column value which is missing?
I have a dataset whose first two values of a column are, apparently missing, and I cannot change it!
Here is the dataset print:

```<code>                 data/hora  HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
0                                NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
1                                NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2  2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
3  2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
4  2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
5  2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
6  2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
7  2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
8  2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
9  2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN
</code>```

AS you can see, for the rows 0 and 1 in the column 'data/hora' there are no values. I want to replace them with information in the column 3. I have tried many things, all of them had failed.

Such as:

```<code>df_74034.replace({df_74034.iloc[0,0] : '2017-08-18\t09:22:33'}, inplace=True)
</code>```

Then I tried:

```<code>df_74034.at[0, 'data/hora'] = 0
</code>```

And I got:

```<code>A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  return super(DataFrame, self).rename(**kwargs)
/home/marlon/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py:2584: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.loc[index, col] = value
</code>```

Thanks for any help!

答:
I've solved my own problem. Here it goes:

We cannot change the data frame because it is, in fact, a copy of a data frame. Therefore, the methods we were imploying didn't work - to understand why to check http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html.

Hence, I had to change directly the data frame df from which df_74034 came from. There I've just applied:

```<code>    df.reset_index(level=0, inplace=True)
df_74034.rename(index=str, columns={"index": "data/hora"}, inplace=True)
</code>```

Then I printed df_74034 and got their index, an so:

```<code>df.loc[69333, 'index'] = '2017-08-18\t09:22:33'
df.loc[69334, 'index'] = '2017-10-03\t11:08:26'
df.loc[69333, 'HumTechRoom'] = '65.9'
df.loc[69334, 'HumTechRoom'] = '60.5'
</code>```

which gave me:

```<code> data/hora  HumExamRoom HumTechRoom Machine  TempExamRoom TempTechRoom
69333  2017-08-18\t09:22:33          NaN        65.9   74034           NaN          NaN
69334  2017-10-03\t11:08:26          NaN        60.5   74034           NaN          NaN
69335  2018-02-17\t01:45:24          NaN        69.7   74034           NaN          NaN
69336  2018-02-17\t01:45:55          NaN        67.5   74034           NaN          NaN
69337  2018-02-17\t01:46:29          NaN        65.4   74034           NaN          NaN
69338  2018-02-17\t01:47:20          NaN        63.3   74034           NaN          NaN
69339  2018-02-17\t01:48:35          NaN        61.3   74034           NaN          NaN
69340  2018-02-17\t01:49:08          NaN        63.4   74034           NaN          NaN
69341  2018-02-17\t01:49:31          NaN        65.5   74034           NaN          NaN
69342  2018-02-17\t01:49:55          NaN        67.6   74034           NaN          NaN
</code>```

I know there should be a more elegant and smart way to do what I've done. But it has worked for me.

Body:
I have a dataset whose first two values of a column are, apparently missing, and I cannot change it!
Here is the dataset print:

                 data/hora  HumExamRoom                      HumTechRoom Machine  TempExamRoom TempTechRoom
0                                NaN  2017-08-18\t09:22:33\t65.9   74034           NaN          NaN
1                                NaN  2017-10-03\t11:08:26\t60.5   74034           NaN          NaN
2  2018-02-17\t01:45:24          NaN                             69.7   74034           NaN          NaN
3  2018-02-17\t01:45:55          NaN                             67.5   74034           NaN          NaN
4  2018-02-17\t01:46:29          NaN                             65.4   74034           NaN          NaN
5  2018-02-17\t01:47:20          NaN                             63.3   74034           NaN          NaN
6  2018-02-17\t01:48:35          NaN                             61.3   74034           NaN          NaN
7  2018-02-17\t01:49:08          NaN                             63.4   74034           NaN          NaN
8  2018-02-17\t01:49:31          NaN                             65.5   74034           NaN          NaN
9  2018-02-17\t01:49:55          NaN                             67.6   74034           NaN          NaN

AS you can see, for the rows 0 and 1 in the column 'data/hora' there are no values. I want to replace them with information in the column 3. I have tried many things, all of them had failed.

Such as:

df_74034.replace({df_74034.iloc[0,0] : '2017-08-18\t09:22:33'}, inplace=True)

Then I tried:

df_74034.at[0, 'data/hora'] = 0

And I got:

A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  return super(DataFrame, self).rename(**kwargs)
/home/marlon/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py:2584: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.loc[index, col] = value

Thanks for any help!

Body:
I've solved my own problem. Here it goes:

We cannot change the data frame because it is, in fact, a copy of a data frame. Therefore, the methods we were imploying didn't work - to understand why to check http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html.

Hence, I had to change directly the data frame df from which df_74034 came from. There I've just applied:

    df.reset_index(level=0, inplace=True)
df_74034.rename(index=str, columns={"index": "data/hora"}, inplace=True)

Then I printed df_74034 and got their index, an so:

df.loc[69333, 'index'] = '2017-08-18\t09:22:33'
df.loc[69334, 'index'] = '2017-10-03\t11:08:26'
df.loc[69333, 'HumTechRoom'] = '65.9'
df.loc[69334, 'HumTechRoom'] = '60.5'

which gave me:

 data/hora  HumExamRoom HumTechRoom Machine  TempExamRoom TempTechRoom
69333  2017-08-18\t09:22:33          NaN        65.9   74034           NaN          NaN
69334  2017-10-03\t11:08:26          NaN        60.5   74034           NaN          NaN
69335  2018-02-17\t01:45:24          NaN        69.7   74034           NaN          NaN
69336  2018-02-17\t01:45:55          NaN        67.5   74034           NaN          NaN
69337  2018-02-17\t01:46:29          NaN        65.4   74034           NaN          NaN
69338  2018-02-17\t01:47:20          NaN        63.3   74034           NaN          NaN
69339  2018-02-17\t01:48:35          NaN        61.3   74034           NaN          NaN
69340  2018-02-17\t01:49:08          NaN        63.4   74034           NaN          NaN
69341  2018-02-17\t01:49:31          NaN        65.5   74034           NaN          NaN
69342  2018-02-17\t01:49:55          NaN        67.6   74034           NaN          NaN

I know there should be a more elegant and smart way to do what I've done. But it has worked for me.


问:
How to generate Elasticsearch security users via Ansible
We just installed Elasticsearch 7.x. We want to use the x-pack security module. We already automated everything via Ansible but we have a problem creating/setting the built in users with password:

ElsticSearch how to:

Run on system: /usr/share/elasticsearch/bin/elasticsearch-setup-passwords interactive or auto.

Then you are asked for a password for each user in ElasticSearch. Are there any possibilities to automate this? Like some autoanswer question in Ansible or anything else?

Thanks

答:
If you use the auto mode, then random passwords are generated and written to the console that you can maybe read.

Another solution is to call the Change password API in order to change user passwords after the fact.


问:
Is it possible to link one and the same set of source data with different models of tables?
Suppose I have a source data structure of type QString. My goal is to display this data in different tables (QTableView) presented by different models (QAbstractTableModel). I would like to see the data change in these tables when the source data changes, but without explicitly calling setData (...) for each table model.
Is it possible?

------UPD------- It took to add the code for my example. How to do it in the comments I do not know.

I do not know how to use the same model for different tables.
If you know, show me please how to do it. Here is my test example.

```<code>#TableTest.pro

    QT += widgets
    DEFINES += QT_DEPRECATED_WARNINGS

    SOURCES += \
            main.cpp

    HEADERS += \
        main.h
    # Default rules for deployment.
    qnx: target.path = /tmp/$${TARGET}/bin
    else: unix:!android: target.path = /opt/$${TARGET}/bin
    !isEmpty(target.path): INSTALLS += target

// main.h
    #include <QObject>
    #include <QTimer>
    #include <QString>
    #include <QColor>
    #include <QTableView>
    #include <QHeaderView>
    #include <QStandardItemModel>
    #include <QStringList>

    #define UPDATE_INTERVAL 200
    #define MAP_WIDTH 600
    #define MAP_HEIGHT 400
    #define RAND_HALF (RAND_MAX / 2)

    #ifndef MAIN_H
    #define MAIN_H

    class CTestObject : public QObject
    {
        Q_OBJECT

    public:

        CTestObject(QString name, QString user);
        void setData(double x, double y, double speed, const QString &zone);
        void setData(double speed, double azimuth);

        QString Name;
        QString User;
        double CoordX;
        double CoordY;
        double Speed;
        double Azimuth;
        double Weight;
        QColor Color;
        QString Zone;

    signals:
        void changed(CTestObject*);
    };
    //--------------------------------------------- All Objects Table
    class CAllObjectsTable : public QStandardItemModel
    {
        Q_OBJECT

    public:
        CAllObjectsTable(QString Title, QStringList ColumnHeaders);
        void addRecord(CTestObject *object);
        void deleteRecord(CTestObject *object);

        QTableView *view;

    public slots:
        virtual void updateRecordData(CTestObject *object);

    protected:
        QVector<CTestObject*> Objects; // local array pointers to objects (each table has its own set)
    };
    //--------------------------------------------- Table Zone
    class CZoneTable : public CAllObjectsTable
    {
        Q_OBJECT

    public:
        CZoneTable(QString Title, QStringList ColumnHeaders) : CAllObjectsTable(Title, ColumnHeaders){}
        void addRecord(CTestObject *object);

    public slots:
        virtual void updateRecordData(CTestObject *object) override;
    };
    //-------------------------------------------- Users Table
    class CUsersTable : public CAllObjectsTable
    {
        Q_OBJECT

    public:
        CUsersTable(QString Title, QStringList ColumnHeaders) : CAllObjectsTable(Title, ColumnHeaders){}
        void addRecord(CTestObject *object);

    public slots:
        virtual void updateRecordData(CTestObject *object) override;
    };

    #endif // MAIN_H

// main.cpp
#include <QApplication>
#include <QtMath>
#include <QDebug>
#include "main.h"

void tmrUpdateEvent();
QVector<CTestObject*> g_Objects; // Global source objects array
CAllObjectsTable *AllObjectsTable;
CZoneTable *ZoneObjectsTable;
CUsersTable *UsersTable;
//-----------------------------------------------------------------
int main(int argc, char *argv[])
{
QApplication app(argc, argv);

    // create objects
    g_Objects.append(new CTestObject("ObjectA", "John"));
    g_Objects.append(new CTestObject("ObjectB", "Peter"));
    g_Objects.append(new CTestObject("ObjectC", "Mike"));
    g_Objects.append(new CTestObject("ObjectD", "Alice"));
    g_Objects.append(new CTestObject("ObjectE", "Megan"));

    // create tables
    AllObjectsTable = new CAllObjectsTable("All Objects", QStringList() << "Object" << "X" << "Y" << "Speed" << "Zone");

    for(int c =0; c < g_Objects.size(); c++)
        AllObjectsTable->addRecord(g_Objects[c]);

    ZoneObjectsTable = new CZoneTable("Zone B1", QStringList() << "Object" << "Weight" << "Speed" << "Azimuth" << "X" << "Y");
    UsersTable = new CUsersTable("Users", QStringList() << "User" << "Object" << "Zone" << "X" << "Y");

    tmrUpdateEvent();

return app.exec();
}
//------------------------------------------------ Table AllObjects
CAllObjectsTable::CAllObjectsTable(QString Title, QStringList ColumnHeaders)
{
    // model
    this->setHorizontalHeaderLabels(ColumnHeaders);

    // view
    view = new QTableView;
    view->setWindowTitle(Title);
    view->verticalHeader()->hide();
    view->setModel(this);
    view->show();
}

void CAllObjectsTable::addRecord(CTestObject *object)
{
    if(!object)
        return;

    this->Objects.append(object);
    this->insertRow(this->Objects.size() - 1);
    this->setData(index((Objects.size() - 1), 0), object->Name, Qt::DisplayRole);

    connect(object, SIGNAL(changed(CTestObject*)), this, SLOT(updateRecordData(CTestObject*)));
}

void CAllObjectsTable::deleteRecord(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {
            this->Objects.remove(c);
            this->removeRow(c);
        }
}

void CAllObjectsTable::updateRecordData(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {
            this->setData(index(c, 1), object->CoordX, Qt::DisplayRole);
            this->setData(index(c, 2), object->CoordY, Qt::DisplayRole);
            this->setData(index(c, 3), object->Speed, Qt::DisplayRole);
            this->setData(index(c, 4), object->Zone, Qt::DisplayRole);
        }
}
//------------------------------------------------------- Table Zone
void CZoneTable::addRecord(CTestObject *object)
{
    if(!object)
        return;

    this->Objects.append(object);
    this->insertRow(Objects.size() - 1);
    this->setData(index((this->Objects.size() - 1), 0), object->Name, Qt::DisplayRole); // Name
    this->setData(index((Objects.size() - 1), 1), object->Weight, Qt::DisplayRole); // Weight

    connect(object, SIGNAL(changed(CTestObject*)), this, SLOT(updateRecordData(CTestObject*)));
}

void CZoneTable::updateRecordData(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {

            this->setData(index(c, 2), object->Speed, Qt::DisplayRole); // Speed
            this->setData(index(c, 3), object->Azimuth, Qt::DisplayRole); // Azimuth
            this->setData(index(c, 4), object->CoordX, Qt::DisplayRole); // X
            this->setData(index(c, 5), object->CoordY, Qt::DisplayRole); // Y
        }
}
//------------------------------------------------------- Table Users
void CUsersTable::addRecord(CTestObject *object)
{
    if(!object)
        return;

    this->Objects.append(object);
    this->insertRow(Objects.size() - 1);
    this->setData(index((this->Objects.size() - 1), 0), object->User, Qt::DisplayRole); // User
    this->setData(index((Objects.size() - 1), 1), object->Name, Qt::DisplayRole); // Name
    this->setData(index((Objects.size() - 1), 0), object->Color, Qt::ForegroundRole);

    connect(object, SIGNAL(changed(CTestObject*)), this, SLOT(updateRecordData(CTestObject*)));
}

void CUsersTable::updateRecordData(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {
            this->setData(index(c, 2), object->Zone, Qt::DisplayRole); // Zone
            this->setData(index(c, 3), object->CoordX, Qt::DisplayRole); // X
            this->setData(index(c, 4), object->CoordY, Qt::DisplayRole); // Y
        }
}
//------------------------------------------------------- Object
CTestObject::CTestObject(QString name, QString user) : Name(name), User(user)
{
    Weight =(std::rand() % 20000);
    Color =(std::rand() << 15 | std::rand());
    setData((std::rand() % MAP_WIDTH), (std::rand() % MAP_HEIGHT), 0, "");
    setData(std::rand(), ((double)(std::rand() - RAND_HALF) / RAND_MAX));
}

void CTestObject::setData(double x, double y, double speed, const QString &zone)
{
    this->CoordX =x;
    this->CoordY =y;
    this->Speed =speed;
    this->Zone =zone;

    emit changed(this);
}

void CTestObject::setData(double speed, double azimuth)
{
    this->Speed =std::fmod(speed, 1000);
    this->Azimuth =azimuth;

    emit changed(this);
}
//----------------------------------------------------------
QString GetZoneXY(double x, double y)
{
double ZoneWidth =(MAP_WIDTH / 3), ZoneHeight =(MAP_HEIGHT / 3);
QString Zone ="";

    if(x < ZoneWidth)
        Zone +="A";
    else
    if(x < (ZoneWidth * 2))
        Zone +="B";
    else
        Zone +="C";

    if(y < ZoneHeight)
        Zone +="0";
    else
    if(y < (ZoneHeight * 2))
        Zone +="1";
    else
        Zone +="2";

return(Zone);
}
//============================================== Update =================================
void tmrUpdateEvent()
{
    for(int c =0; c < g_Objects.size(); c++)
    {
    double s;

        s =(g_Objects[c]->Speed - (0.001 * g_Objects[c]->Weight));

        if(s > 10) // if Object moving - update Coords & Speed
        {
        double x =g_Objects[c]->CoordX, y =g_Objects[c]->CoordY, a =g_Objects[c]->Azimuth;
        QString z;

            x =std::fmod(x + (std::sin(a) * s * 0.01), MAP_WIDTH);
            y =std::fmod(y + (std::cos(a) * s * 0.01), MAP_HEIGHT);

            while(x < 0)
                x +=MAP_WIDTH;

            while(y < 0)
                y +=MAP_HEIGHT;

            z =GetZoneXY(x, y); // current zone

            // check objects for Zone table
            if(g_Objects[c]->Zone == "B1" && z != "B1")
                ZoneObjectsTable->deleteRecord(g_Objects[c]);
            else
            if(z == "B1" && g_Objects[c]->Zone != "B1")
                ZoneObjectsTable->addRecord(g_Objects[c]);

            // check objects for Users table
            if(z != "B1" && g_Objects[c]->Zone == "B1")
                UsersTable->addRecord(g_Objects[c]);
            else
            if(z == "B1" && g_Objects[c]->Zone != "B1")
                UsersTable->deleteRecord(g_Objects[c]);

            g_Objects[c]->setData(x, y, s, z);
        }
        else // new Speed & Direction
            g_Objects[c]->setData(std::rand(), ((double)(std::rand() - RAND_HALF) / RAND_MAX));
    }

    QTimer::singleShot(UPDATE_INTERVAL, [=](){tmrUpdateEvent();});
}
</code>```

答:
Thank you all. I found the answer to my question - no, this is impossible.
The problem is that setData(...) sets the data for the model by copying it. And I would like to insert a link to them and not later to catch signals about data changes. Something like this.</p>

Body:
Suppose I have a source data structure of type QString. My goal is to display this data in different tables (QTableView) presented by different models (QAbstractTableModel). I would like to see the data change in these tables when the source data changes, but without explicitly calling setData (...) for each table model.
Is it possible?

------UPD------- It took to add the code for my example. How to do it in the comments I do not know.

I do not know how to use the same model for different tables.
If you know, show me please how to do it. Here is my test example.

#TableTest.pro

    QT += widgets
    DEFINES += QT_DEPRECATED_WARNINGS

    SOURCES += \
            main.cpp

    HEADERS += \
        main.h
    # Default rules for deployment.
    qnx: target.path = /tmp/$${TARGET}/bin
    else: unix:!android: target.path = /opt/$${TARGET}/bin
    !isEmpty(target.path): INSTALLS += target

// main.h
    #include <QObject>
    #include <QTimer>
    #include <QString>
    #include <QColor>
    #include <QTableView>
    #include <QHeaderView>
    #include <QStandardItemModel>
    #include <QStringList>

    #define UPDATE_INTERVAL 200
    #define MAP_WIDTH 600
    #define MAP_HEIGHT 400
    #define RAND_HALF (RAND_MAX / 2)

    #ifndef MAIN_H
    #define MAIN_H

    class CTestObject : public QObject
    {
        Q_OBJECT

    public:

        CTestObject(QString name, QString user);
        void setData(double x, double y, double speed, const QString &zone);
        void setData(double speed, double azimuth);

        QString Name;
        QString User;
        double CoordX;
        double CoordY;
        double Speed;
        double Azimuth;
        double Weight;
        QColor Color;
        QString Zone;

    signals:
        void changed(CTestObject*);
    };
    //--------------------------------------------- All Objects Table
    class CAllObjectsTable : public QStandardItemModel
    {
        Q_OBJECT

    public:
        CAllObjectsTable(QString Title, QStringList ColumnHeaders);
        void addRecord(CTestObject *object);
        void deleteRecord(CTestObject *object);

        QTableView *view;

    public slots:
        virtual void updateRecordData(CTestObject *object);

    protected:
        QVector<CTestObject*> Objects; // local array pointers to objects (each table has its own set)
    };
    //--------------------------------------------- Table Zone
    class CZoneTable : public CAllObjectsTable
    {
        Q_OBJECT

    public:
        CZoneTable(QString Title, QStringList ColumnHeaders) : CAllObjectsTable(Title, ColumnHeaders){}
        void addRecord(CTestObject *object);

    public slots:
        virtual void updateRecordData(CTestObject *object) override;
    };
    //-------------------------------------------- Users Table
    class CUsersTable : public CAllObjectsTable
    {
        Q_OBJECT

    public:
        CUsersTable(QString Title, QStringList ColumnHeaders) : CAllObjectsTable(Title, ColumnHeaders){}
        void addRecord(CTestObject *object);

    public slots:
        virtual void updateRecordData(CTestObject *object) override;
    };

    #endif // MAIN_H

// main.cpp
#include <QApplication>
#include <QtMath>
#include <QDebug>
#include "main.h"

void tmrUpdateEvent();
QVector<CTestObject*> g_Objects; // Global source objects array
CAllObjectsTable *AllObjectsTable;
CZoneTable *ZoneObjectsTable;
CUsersTable *UsersTable;
//-----------------------------------------------------------------
int main(int argc, char *argv[])
{
QApplication app(argc, argv);

    // create objects
    g_Objects.append(new CTestObject("ObjectA", "John"));
    g_Objects.append(new CTestObject("ObjectB", "Peter"));
    g_Objects.append(new CTestObject("ObjectC", "Mike"));
    g_Objects.append(new CTestObject("ObjectD", "Alice"));
    g_Objects.append(new CTestObject("ObjectE", "Megan"));

    // create tables
    AllObjectsTable = new CAllObjectsTable("All Objects", QStringList() << "Object" << "X" << "Y" << "Speed" << "Zone");

    for(int c =0; c < g_Objects.size(); c++)
        AllObjectsTable->addRecord(g_Objects[c]);

    ZoneObjectsTable = new CZoneTable("Zone B1", QStringList() << "Object" << "Weight" << "Speed" << "Azimuth" << "X" << "Y");
    UsersTable = new CUsersTable("Users", QStringList() << "User" << "Object" << "Zone" << "X" << "Y");

    tmrUpdateEvent();

return app.exec();
}
//------------------------------------------------ Table AllObjects
CAllObjectsTable::CAllObjectsTable(QString Title, QStringList ColumnHeaders)
{
    // model
    this->setHorizontalHeaderLabels(ColumnHeaders);

    // view
    view = new QTableView;
    view->setWindowTitle(Title);
    view->verticalHeader()->hide();
    view->setModel(this);
    view->show();
}

void CAllObjectsTable::addRecord(CTestObject *object)
{
    if(!object)
        return;

    this->Objects.append(object);
    this->insertRow(this->Objects.size() - 1);
    this->setData(index((Objects.size() - 1), 0), object->Name, Qt::DisplayRole);

    connect(object, SIGNAL(changed(CTestObject*)), this, SLOT(updateRecordData(CTestObject*)));
}

void CAllObjectsTable::deleteRecord(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {
            this->Objects.remove(c);
            this->removeRow(c);
        }
}

void CAllObjectsTable::updateRecordData(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {
            this->setData(index(c, 1), object->CoordX, Qt::DisplayRole);
            this->setData(index(c, 2), object->CoordY, Qt::DisplayRole);
            this->setData(index(c, 3), object->Speed, Qt::DisplayRole);
            this->setData(index(c, 4), object->Zone, Qt::DisplayRole);
        }
}
//------------------------------------------------------- Table Zone
void CZoneTable::addRecord(CTestObject *object)
{
    if(!object)
        return;

    this->Objects.append(object);
    this->insertRow(Objects.size() - 1);
    this->setData(index((this->Objects.size() - 1), 0), object->Name, Qt::DisplayRole); // Name
    this->setData(index((Objects.size() - 1), 1), object->Weight, Qt::DisplayRole); // Weight

    connect(object, SIGNAL(changed(CTestObject*)), this, SLOT(updateRecordData(CTestObject*)));
}

void CZoneTable::updateRecordData(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {

            this->setData(index(c, 2), object->Speed, Qt::DisplayRole); // Speed
            this->setData(index(c, 3), object->Azimuth, Qt::DisplayRole); // Azimuth
            this->setData(index(c, 4), object->CoordX, Qt::DisplayRole); // X
            this->setData(index(c, 5), object->CoordY, Qt::DisplayRole); // Y
        }
}
//------------------------------------------------------- Table Users
void CUsersTable::addRecord(CTestObject *object)
{
    if(!object)
        return;

    this->Objects.append(object);
    this->insertRow(Objects.size() - 1);
    this->setData(index((this->Objects.size() - 1), 0), object->User, Qt::DisplayRole); // User
    this->setData(index((Objects.size() - 1), 1), object->Name, Qt::DisplayRole); // Name
    this->setData(index((Objects.size() - 1), 0), object->Color, Qt::ForegroundRole);

    connect(object, SIGNAL(changed(CTestObject*)), this, SLOT(updateRecordData(CTestObject*)));
}

void CUsersTable::updateRecordData(CTestObject *object)
{
    for(int c =0; c < this->Objects.size(); c++)
        if(this->Objects[c] == object)
        {
            this->setData(index(c, 2), object->Zone, Qt::DisplayRole); // Zone
            this->setData(index(c, 3), object->CoordX, Qt::DisplayRole); // X
            this->setData(index(c, 4), object->CoordY, Qt::DisplayRole); // Y
        }
}
//------------------------------------------------------- Object
CTestObject::CTestObject(QString name, QString user) : Name(name), User(user)
{
    Weight =(std::rand() % 20000);
    Color =(std::rand() << 15 | std::rand());
    setData((std::rand() % MAP_WIDTH), (std::rand() % MAP_HEIGHT), 0, "");
    setData(std::rand(), ((double)(std::rand() - RAND_HALF) / RAND_MAX));
}

void CTestObject::setData(double x, double y, double speed, const QString &zone)
{
    this->CoordX =x;
    this->CoordY =y;
    this->Speed =speed;
    this->Zone =zone;

    emit changed(this);
}

void CTestObject::setData(double speed, double azimuth)
{
    this->Speed =std::fmod(speed, 1000);
    this->Azimuth =azimuth;

    emit changed(this);
}
//----------------------------------------------------------
QString GetZoneXY(double x, double y)
{
double ZoneWidth =(MAP_WIDTH / 3), ZoneHeight =(MAP_HEIGHT / 3);
QString Zone ="";

    if(x < ZoneWidth)
        Zone +="A";
    else
    if(x < (ZoneWidth * 2))
        Zone +="B";
    else
        Zone +="C";

    if(y < ZoneHeight)
        Zone +="0";
    else
    if(y < (ZoneHeight * 2))
        Zone +="1";
    else
        Zone +="2";

return(Zone);
}
//============================================== Update =================================
void tmrUpdateEvent()
{
    for(int c =0; c < g_Objects.size(); c++)
    {
    double s;

        s =(g_Objects[c]->Speed - (0.001 * g_Objects[c]->Weight));

        if(s > 10) // if Object moving - update Coords & Speed
        {
        double x =g_Objects[c]->CoordX, y =g_Objects[c]->CoordY, a =g_Objects[c]->Azimuth;
        QString z;

            x =std::fmod(x + (std::sin(a) * s * 0.01), MAP_WIDTH);
            y =std::fmod(y + (std::cos(a) * s * 0.01), MAP_HEIGHT);

            while(x < 0)
                x +=MAP_WIDTH;

            while(y < 0)
                y +=MAP_HEIGHT;

            z =GetZoneXY(x, y); // current zone

            // check objects for Zone table
            if(g_Objects[c]->Zone == "B1" && z != "B1")
                ZoneObjectsTable->deleteRecord(g_Objects[c]);
            else
            if(z == "B1" && g_Objects[c]->Zone != "B1")
                ZoneObjectsTable->addRecord(g_Objects[c]);

            // check objects for Users table
            if(z != "B1" && g_Objects[c]->Zone == "B1")
                UsersTable->addRecord(g_Objects[c]);
            else
            if(z == "B1" && g_Objects[c]->Zone != "B1")
                UsersTable->deleteRecord(g_Objects[c]);

            g_Objects[c]->setData(x, y, s, z);
        }
        else // new Speed & Direction
            g_Objects[c]->setData(std::rand(), ((double)(std::rand() - RAND_HALF) / RAND_MAX));
    }

    QTimer::singleShot(UPDATE_INTERVAL, [=](){tmrUpdateEvent();});
}


答:
A Django form's cleaned_data attribute isn't accessible until you call is_valid() on the form.

```<code>form = PostForm(request.POST)

if form.is_valid():
    cd = form.cleaned_data
    ...
</code>```

Title: Django code only works in debug

Body:
Very confused about this one. This code in views.py works, but only when I'm debugging using Pycharm. If I just do runserver I get a 500 error.

views.py:

def add_post(request):
if request.method == 'POST':
    form = PostForm(request.POST)
    cd = form.cleaned_data
    if form.is_valid():
        print "valid"
        post = Post(nickname=cd['nickname'], body=cd['body'], category=cd['category'])
        post.save()

        return HttpResponse("success")

return HttpResponseServerError("fail")

Error as seen in Chrome Inspector

     Exception Value:

'PostForm' object has no attribute 'cleaned_data'

No attribute cleaned_data? But why...?

Body:
A Django form's cleaned_data attribute isn't accessible until you call is_valid() on the form.

form = PostForm(request.POST)

if form.is_valid():
    cd = form.cleaned_data
    ...


问:
Terms in neural networks: what is annealing temperature parameter in a softmax activation function?
I’m reading this paper about sound separation by using neural network method. It uses the term "annealing the temperature parameter in a softmax activation function". What does it mean?</p>

答:
"Annealing", in this sense, is an analogy to a chemical process in which temperature is reduced.

Here, too, the 'temperature' term in the softmax is reduced, changing it gradually from a 'soft' sigmoid function to a 'sharp' argmax

Try plotting a softmax function for yourself with different temperatures, you'll see the difference...


问:
Bootstrap modal - Issue with stopping of video with Safari and Chrome
I have added the following code to my html page to stop a modal video from playing when closing it:

```<code><head>
<script type="text/javascript">
    $(document).ready(function(){
       $('.modal').each(function(){
           var src = $(this).find('video').attr('src');

       $(this).on('click', function(){

           $(this).find('video').attr('src', '');
           $(this).find('video').attr('src', src);

        });
    });
});
</script>
</head>

<body>
<div class="modal fade" role="dialog">
    <div class="modal-dialog">
          <div class="modal-content">
               <div class="modal-header">
               <button type="button" class="close" data-dismiss="modal">×</button>
               <h4 class="modal-title">My title</h4>
               </div>
           <div class="modal-body">
               <div> <video controls width="100%"> <source src="videos/myvideo.mp4" type="video/mp4"></video> </div>
           </div>
           <div class="modal-footer">
           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
           </div>
         </div>
    </div>
 </div>
</body>
</code>```

It works fine with Firefox but not with Chrome and Safari.
On Firefox, the src link is removed when closing the modal (good).
On Chrome, when I click the playing bar of the video inside the modal, Chrome starts the video but if I click the video itself (which should just pause/play it) it removes the src link, so the video becomes black.
Safari removes the src link as soon as clicking play (so the video never starts).
My priority is to make this work on Firefox and Safari.

Does anyone have any idea how I could solve this?

(Note: I have tried other codes to make the video stop when modal is closed, to see if it could work better with Safari and Chrome (for example, here Twitter Bootstrap Modal stop Youtube video) but I could not manage to make the video stop at all. So the one I use in this example is the only one that correctly stops my video from playing when closed – at least in Firefox.)

答:
First of all, add an id="videoModal" to the modal and an id="video" to the video tag.

Then use the bootstrap show and hide event listeners for the modal, and use the play() and pause() for the video element like this:

```<code><script type="text/javascript">
 $(document).ready(function(){
    var video = document.getElementById('video');
    $('#videoModal').on('shown.bs.modal', function () {
        console.log('playing video');
        video.play();
    });
    $('#videoModal').on('hide.bs.modal', function () {
        console.log('pausing video');
        video.pause();
    });
});
</script>
</code>```

Body:
I have added the following code to my html page to stop a modal video from playing when closing it:

               <button type="button" class="close" data-dismiss="modal">×</button>

My title

 <video controls width="100%"> <source src="videos/myvideo.mp4" type="video/mp4"></video>

           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

It works fine with Firefox but not with Chrome and Safari.
On Firefox, the src link is removed when closing the modal (good).
On Chrome, when I click the playing bar of the video inside the modal, Chrome starts the video but if I click the video itself (which should just pause/play it) it removes the src link, so the video becomes black.
Safari removes the src link as soon as clicking play (so the video never starts).
My priority is to make this work on Firefox and Safari.

Does anyone have any idea how I could solve this?

(Note: I have tried other codes to make the video stop when modal is closed, to see if it could work better with Safari and Chrome (for example, here Twitter Bootstrap Modal stop Youtube video) but I could not manage to make the video stop at all. So the one I use in this example is the only one that correctly stops my video from playing when closed – at least in Firefox.)

Body:
First of all, add an id="videoModal" to the modal and an id="video" to the video tag.

Then use the bootstrap show and hide event listeners for the modal, and use the play() and pause() for the video element like this:

<script type="text/javascript">
 $(document).ready(function(){
    var video = document.getElementById('video');
    $('#videoModal').on('shown.bs.modal', function () {
        console.log('playing video');
        video.play();
    });
    $('#videoModal').on('hide.bs.modal', function () {
        console.log('pausing video');
        video.pause();
    });
});
</script>


问:
Zip function in System F
Let's define list type

```<code>list = forall 'a, 'x. ('a -> 'x -> 'x) -> 'x -> 'x
</code>```

where for instance

```<code>nil = Λ'a . Λ'x . λ(c : 'a -> 'x -> 'x) . λ(e : 'x) . e
cons = Λ'a . Λ'x . λ(head : 'a) . λ(tail : list 'a 'x) . λ(c : 'a -> 'x -> 'x) . λ(e : 'x) . c head (tail c e)
</code>```

I am trying to define function zip of type

```<code>zip : forall 'a, 'b, 'c, 'x. ('a -> 'b -> 'c) -> list 'a 'x -> list 'b 'x -> list 'c 'x
</code>```

That intuitively does

```<code>zip (+) [1,2,3] [4,5,6] = [5,7,9]
zip (λa . λb . a) [1,2] [2,3,4] = [1,2]
zip (λa . λb . a) [2,3,4] [1,2] = [2,3]
</code>```

Note that it truncates the longer list to fit the shorter.

The main problem I encounter here is that I cannot "iterate" over two lists at once. How can implement such a function in system F? Is it even possible?

答:
Okay, I managed to write solution for it. First of all let's define helper option type:

```<code>option = forall 'a, 'x. ('a -> 'x) -> 'x -> 'x
</code>```

Which has two constructors:

```<code>none = Λ'a . Λ'x . λ (onsome : 'a -> 'x) . λ (onnone : 'x) . onnone
some = Λ'a . Λ'x . λ (elem : 'a) . λ (onsome : 'a -> 'x) . λ (onnone : 'x) . onsome elem
</code>```

Next step are functions that will extract head and tail of the list. head will return option 'elemtype to handle empty list case, but tail will just return empty list on empty list (in similar manner to predecessor function on Church numerals)

```<code>head = Λ 'a . λ (l : list 'a) . l (λ (elem : 'a) . λ (p : option 'a) . some elem) none
tail = Λ 'a . λ (l : list 'a) .
    pair_first
       ( l (λ (elem : 'a) . λ (p : pair (list 'a) (list 'a)) .
               make_pair (list 'a) (list 'a)
                  (pair_second (list 'a) (list 'a) p)
                  (cons 'a elem (pair_second (list 'a) (list 'a) p)))
           (make_pair (list 'a) (list 'a) (nil 'a) (nil 'a)))
</code>```

The idea of head is that we start aggregating our list starting with none on empty list and for each new element from the left we set this element as our result wrapped by some to preserve typing.
tail on the other hand does not need option to be well defined, because in case of empty list we may just return an empty list. It looks very ugly, but uses same technique as predecessor of natural numbers. I assume pair interface is known.

Next, let's define listmatch function that will pattern match on given list

```<code>listmatch = Λ 'a . Λ 'x . λ (l : list 'a) . λ (oncons : 'a -> list 'a -> 'x) . λ (onnil : 'x) .
    (head 'a l)
      (λ (hd : 'a) . oncons hd (tail 'a l))
      onnil
</code>```

This function helps us distinguish empty list and non-empty list and perform some actions after its destruction.

Almost finally, we would like to have foldl2 function that given function f, empty case em and two lists [a,b,c] and [x,y] returns something like this: f(f(em a x) b y) (shrinks lists to the shorter one cutting off the tail).

It can be defined as

```<code>foldl2 =
  Λ 'a . Λ 'b . Λ 'c .
  λ (f : 'c -> 'a -> 'b -> 'c) . λ (em : 'c) . λ (la : list 'a) . λ (lb : list 'b) .
  pair_first 'c (list 'b)
    ((reverse 'a la)
      ( λ (el : 'a) . λ (p : pair 'c (list 'b)) .
        listmatch 'a (pair 'c (list 'b)) (pair_second 'c (list 'b) p)
          (λ (hd : 'a) . λ (tl : list 'a) .
            make_pair 'c (list 'b)
              (f (pair_first 'c (list 'b) p) el hd)
              tl)
          (make_pair 'c (list 'b) (pair_first 'c (list 'b) p) (nil 'a))
      )
      (make_pair 'c (list 'b) em lb))
</code>```

After this the zip is just in our hands:

```<code>zip =
  Λ 'a . Λ 'b . Λ 'c .
  λ (f : 'a -> 'b -> 'c) . λ (la : list 'a) . λ (lb : list 'b) .
  reverse 'c
    (foldl2 'a 'b 'c
      (λ (lt : 'c) . λ (a : 'a) . λ (b : 'b) . cons 'c (f a b) lt)
      (nil 'c) la lb)
</code>```

Title: Zip function in System F

Body:
Let's define list type

list = forall 'a, 'x. ('a -> 'x -> 'x) -> 'x -> 'x

where for instance

nil = Λ'a . Λ'x . λ(c : 'a -> 'x -> 'x) . λ(e : 'x) . e
cons = Λ'a . Λ'x . λ(head : 'a) . λ(tail : list 'a 'x) . λ(c : 'a -> 'x -> 'x) . λ(e : 'x) . c head (tail c e)

I am trying to define function zip of type

zip : forall 'a, 'b, 'c, 'x. ('a -> 'b -> 'c) -> list 'a 'x -> list 'b 'x -> list 'c 'x

That intuitively does

zip (+) [1,2,3] [4,5,6] = [5,7,9]
zip (λa . λb . a) [1,2] [2,3,4] = [1,2]
zip (λa . λb . a) [2,3,4] [1,2] = [2,3]

Note that it truncates the longer list to fit the shorter.

The main problem I encounter here is that I cannot "iterate" over two lists at once. How can implement such a function in system F? Is it even possible?

Body:
Okay, I managed to write solution for it. First of all let's define helper option type:

option = forall 'a, 'x. ('a -> 'x) -> 'x -> 'x

Which has two constructors:

none = Λ'a . Λ'x . λ (onsome : 'a -> 'x) . λ (onnone : 'x) . onnone
some = Λ'a . Λ'x . λ (elem : 'a) . λ (onsome : 'a -> 'x) . λ (onnone : 'x) . onsome elem

Next step are functions that will extract head and tail of the list. head will return option 'elemtype to handle empty list case, but tail will just return empty list on empty list (in similar manner to predecessor function on Church numerals)

head = Λ 'a . λ (l : list 'a) . l (λ (elem : 'a) . λ (p : option 'a) . some elem) none
tail = Λ 'a . λ (l : list 'a) .
    pair_first
       ( l (λ (elem : 'a) . λ (p : pair (list 'a) (list 'a)) .
               make_pair (list 'a) (list 'a)
                  (pair_second (list 'a) (list 'a) p)
                  (cons 'a elem (pair_second (list 'a) (list 'a) p)))
           (make_pair (list 'a) (list 'a) (nil 'a) (nil 'a)))

The idea of head is that we start aggregating our list starting with none on empty list and for each new element from the left we set this element as our result wrapped by some to preserve typing.
tail on the other hand does not need option to be well defined, because in case of empty list we may just return an empty list. It looks very ugly, but uses same technique as predecessor of natural numbers. I assume pair interface is known.

Next, let's define listmatch function that will pattern match on given list

listmatch = Λ 'a . Λ 'x . λ (l : list 'a) . λ (oncons : 'a -> list 'a -> 'x) . λ (onnil : 'x) .
    (head 'a l)
      (λ (hd : 'a) . oncons hd (tail 'a l))
      onnil

This function helps us distinguish empty list and non-empty list and perform some actions after its destruction.

Almost finally, we would like to have foldl2 function that given function f, empty case em and two lists [a,b,c] and [x,y] returns something like this: f(f(em a x) b y) (shrinks lists to the shorter one cutting off the tail).

It can be defined as

foldl2 =
  Λ 'a . Λ 'b . Λ 'c .
  λ (f : 'c -> 'a -> 'b -> 'c) . λ (em : 'c) . λ (la : list 'a) . λ (lb : list 'b) .
  pair_first 'c (list 'b)
    ((reverse 'a la)
      ( λ (el : 'a) . λ (p : pair 'c (list 'b)) .
        listmatch 'a (pair 'c (list 'b)) (pair_second 'c (list 'b) p)
          (λ (hd : 'a) . λ (tl : list 'a) .
            make_pair 'c (list 'b)
              (f (pair_first 'c (list 'b) p) el hd)
              tl)
          (make_pair 'c (list 'b) (pair_first 'c (list 'b) p) (nil 'a))
      )
      (make_pair 'c (list 'b) em lb))

After this the zip is just in our hands:

zip =
  Λ 'a . Λ 'b . Λ 'c .
  λ (f : 'a -> 'b -> 'c) . λ (la : list 'a) . λ (lb : list 'b) .
  reverse 'c
    (foldl2 'a 'b 'c
      (λ (lt : 'c) . λ (a : 'a) . λ (b : 'b) . cons 'c (f a b) lt)
      (nil 'c) la lb)


问:
How get days name from two days in swift
I have two dates, date1 and date2 and I want days between date1 and date 2

Example:

```<code>let date1 = 28-May-2019,
let date2 = 31-May-2019
</code>```

The expected output

[Tue, Web Thr, Fri]

答:
```<code>    let date1Str = "28-May-2019"
    let date2Str = "31-May-2019"

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    dateFormatter.locale = Locale(identifier: "en_US")

    var date1 = dateFormatter.date(from:date1Str)!
    var date2 = dateFormatter.date(from:date2Str)!

    let dayFormatter = DateFormatter()
    dayFormatter.dateFormat = "EEE"

    while date1 <= date2 {
        let dayInWeek = dayFormatter.string(from: date1)
        print(dayInWeek)
        date1 = Calendar.current.date(byAdding: .day, value: 1, to: date1)!
    }
</code>```

Body:
I have two dates, date1 and date2 and I want days between date1 and date 2

Example:

let date1 = 28-May-2019,
let date2 = 31-May-2019

The expected output

[Tue, Web Thr, Fri]