问:
JS Data filter and group not correct
I work with dictionary array, and I wanna group data by time period, I have a solution how to do it.

But now I found issues, for last hours data is not appear at the grouped array.

Code:

    // Dictionary array:
var array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];
// And I have time periods, for ex:
var time = ["05:45 - 06:00", "06:00 - 07:00",
     "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
     "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
     "13:00 - 14:00", "14:00 - 14:45"];

var formatedTime = time.map(function(val) {
    return val.split(" - ");
});

var grouped = formatedTime.reduce((groups, currentValue, cI) => {
    let min = parseInt(currentValue[0].substring(0,2));
    let max = parseInt(currentValue[1].substring(0,2));
    let filtered = array.filter(val => {
        let validDate = val.dateTime.replace(/\//g,'-').replace(' ','T').replace('19','2019');
        let date = new Date(validDate).getHours();
        let result = false;
        if(date >= min && date < max) {
            return true;
        } else {
            return false;
        }
    });

    let date = currentValue[0] + " - " + currentValue[1];
    groups.push({
        time: date,
        groupedData: filtered
    });
    return groups;

}, []);

console.log(grouped);```
</div>
</div>
</p>

<p>So as u can see at array I have data for <strong>time 14:00 - 14:45</strong> after filtering data does not appear correctly.</p>

<p>In my array i have two reccords:</p>

```{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
{ item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
```

<p>I try to found sollution, but i stuck.</p>

<p>Expected output: </p>

```{
    "time": "14:00 - 14:45",
    "groupedData": [{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
    { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }]

 }
```

答:
You could compare the time directly and find first the group and then the item in the result set.

var array = [{ item: "item", category: "category", dateTime: "19/05/23 05:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 05:21:33" }, { item: "item", category: "category", dateTime: "19/05/23 06:31:33" }, { item: "item", category: "category", dateTime: "19/05/23 06:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 07:34:33" }, { item: "item", category: "category", dateTime: "19/05/23 07:55:33" }, { item: "item", category: "category", dateTime: "19/05/23 08:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 09:16:33" }, { item: "item", category: "category", dateTime: "19/05/23 09:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 10:36:33" }, { item: "item", category: "category", dateTime: "19/05/23 11:47:33" }, { item: "item", category: "category", dateTime: "19/05/23 11:55:33" }, { item: "item", category: "category", dateTime: "19/05/23 12:37:33" }, { item: "item", category: "category", dateTime: "19/05/23 14:27:33" }, { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }],
    time = ["05:45 - 06:00", "06:00 - 07:00", "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00", "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00", "13:00 - 14:00", "14:00 - 14:45"],
    result = array.reduce((r, o) => {
        var part = o.dateTime.slice(9, 14),
            group = time.find(t => {
                var [min, max] = t.split(' - ');
                return min <= part && part < max;
            }),
            temp = r.find(({ time }) => time === group);

        if (!group) return r;
        if (!temp) {
            r.push({ time: group, groupedData: [o] });
            return r;
        }
        temp.groupedData.push(o);
        return r;
    }, []);

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

Title: JS Data filter and group not correct

Body:
I work with dictionary array, and I wanna group data by time period, I have a solution how to do it.

But now I found issues, for last hours data is not appear at the grouped array.

Code:

    // Dictionary array:
var array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];
// And I have time periods, for ex:
var time = ["05:45 - 06:00", "06:00 - 07:00",
     "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
     "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
     "13:00 - 14:00", "14:00 - 14:45"];

var formatedTime = time.map(function(val) {
    return val.split(" - ");
});

var grouped = formatedTime.reduce((groups, currentValue, cI) => {
    let min = parseInt(currentValue[0].substring(0,2));
    let max = parseInt(currentValue[1].substring(0,2));
    let filtered = array.filter(val => {
        let validDate = val.dateTime.replace(/\//g,'-').replace(' ','T').replace('19','2019');
        let date = new Date(validDate).getHours();
        let result = false;
        if(date >= min && date < max) {
            return true;
        } else {
            return false;
        }
    });

    let date = currentValue[0] + " - " + currentValue[1];
    groups.push({
        time: date,
        groupedData: filtered
    });
    return groups;

}, []);

console.log(grouped);

So as u can see at array I have data for time 14:00 - 14:45 after filtering data does not appear correctly.

In my array i have two reccords:

{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
{ item: "item", category: "category", dateTime: "19/05/23 14:37:33" },

I try to found sollution, but i stuck.

Expected output:

{
    "time": "14:00 - 14:45",
    "groupedData": [{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
    { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }]

 }

Body:
You could compare the time directly and find first the group and then the item in the result set.

var array = [{ item: "item", category: "category", dateTime: "19/05/23 05:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 05:21:33" }, { item: "item", category: "category", dateTime: "19/05/23 06:31:33" }, { item: "item", category: "category", dateTime: "19/05/23 06:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 07:34:33" }, { item: "item", category: "category", dateTime: "19/05/23 07:55:33" }, { item: "item", category: "category", dateTime: "19/05/23 08:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 09:16:33" }, { item: "item", category: "category", dateTime: "19/05/23 09:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 10:36:33" }, { item: "item", category: "category", dateTime: "19/05/23 11:47:33" }, { item: "item", category: "category", dateTime: "19/05/23 11:55:33" }, { item: "item", category: "category", dateTime: "19/05/23 12:37:33" }, { item: "item", category: "category", dateTime: "19/05/23 14:27:33" }, { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }],
    time = ["05:45 - 06:00", "06:00 - 07:00", "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00", "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00", "13:00 - 14:00", "14:00 - 14:45"],
    result = array.reduce((r, o) => {
        var part = o.dateTime.slice(9, 14),
            group = time.find(t => {
                var [min, max] = t.split(' - ');
                return min <= part && part < max;
            }),
            temp = r.find(({ time }) => time === group);

        if (!group) return r;
        if (!temp) {
            r.push({ time: group, groupedData: [o] });
            return r;
        }
        temp.groupedData.push(o);
        return r;
    }, []);

console.log(result);

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


来源: stackexchange

问:
Remove elements from Array of Array Swift
For context I'm creating my own hashmap in swift.

I've got an element and I'm storing the elements in buckets which is an array of arrays

```<code>struct Element {
    var key: Int
    var value: Int
}

class MyHashMap {
    var buckets : [[Element]] = [[]]

    init() {
        buckets = [Array(repeating: Element(key: -1, value: -1), count: 2)]
        buckets.append([Element(key: 3, value: 4)])
    }

}
</code>```

I want to remove all the buckets where the key is -1 and I'm struggling.

Flatmap does not return the right type
i.e.

```<code>hashmap.buckets.flatMap{$0}.filter{$0.key != -1}
</code>```

is incorrect.

How can I remove all of the buckets with key -1?

答:
Map the outer array to a new array of arrays, where from the inner array only the elements with key != -1 are preserved. I would make this a method of the MyHashMap class:

```<code>class MyHashMap {
    // ...

    func compactBuckets() {
        buckets = buckets.map { $0.filter { $0.key != -1 }}
    }
}
</code>```

Alternatively (and possibly more efficient), with a loop over the indices of the outer array:

```<code>    func compactBuckets() {
        for i in buckets.indices {
            buckets[i].removeAll(where: { $0.key == -1 })
        }
    }
</code>```

In either case you may additionally want to remove empty inner arrays from the outer array:

```<code>        buckets.removeAll(where: { $0.isEmpty })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For context I'm creating my own hashmap in swift.

I've got an element and I'm storing the elements in buckets which is an array of arrays

struct Element {
    var key: Int
    var value: Int
}

class MyHashMap {
    var buckets : [[Element]] = [[]]

    init() {
        buckets = [Array(repeating: Element(key: -1, value: -1), count: 2)]
        buckets.append([Element(key: 3, value: 4)])
    }

}

I want to remove all the buckets where the key is -1 and I'm struggling.

Flatmap does not return the right type
i.e.

hashmap.buckets.flatMap{$0}.filter{$0.key != -1}

is incorrect.

How can I remove all of the buckets with key -1?

Body:
Map the outer array to a new array of arrays, where from the inner array only the elements with key != -1 are preserved. I would make this a method of the MyHashMap class:

class MyHashMap {
    // ...

    func compactBuckets() {
        buckets = buckets.map { $0.filter { $0.key != -1 }}
    }
}

Alternatively (and possibly more efficient), with a loop over the indices of the outer array:

    func compactBuckets() {
        for i in buckets.indices {
            buckets[i].removeAll(where: { $0.key == -1 })
        }
    }

In either case you may additionally want to remove empty inner arrays from the outer array:

        buckets.removeAll(where: { $0.isEmpty })


问:
dependency inversion in top class (main)
i want to create an app in which i have these two classes, MainApp and Model (in reality more, but this is the base and the core of the problem). MainApp is also the starting class. I want to apply dependency inversion so mainApp doesn't have to be rebuild each time Model changes (Well, mainly because its good practice). I can't do this:

```<code>MainApp - - - > IModel
                  ^
                  |
                  |
                Model
</code>```

because i'd have to create Model in MainApp anyway because it's the start of my app, it would be redundant.

I was thinking about shifting the contents of MainApp to another class and use MainApp just as factory for MainAppContents and Model, like this:

```<code>MainApp -------------> Model
   |                     |
   |                     |
   v                     v
MainAppContents - - - > IModel
</code>```

Is this the correct approach and does this mean that any start of a well designed app is a factory?

答: If you want to achieve loosely coupling you should think about using a dependecy injection container (e.g. Unity or MEF).</p>

ContentLicense: CC BY-SA 3.0

Body:
i want to create an app in which i have these two classes, MainApp and Model (in reality more, but this is the base and the core of the problem). MainApp is also the starting class. I want to apply dependency inversion so mainApp doesn't have to be rebuild each time Model changes (Well, mainly because its good practice). I can't do this:

MainApp - - - > IModel
                  ^
                  |
                  |
                Model

because i'd have to create Model in MainApp anyway because it's the start of my app, it would be redundant.

I was thinking about shifting the contents of MainApp to another class and use MainApp just as factory for MainAppContents and Model, like this:

MainApp -------------> Model
   |                     |
   |                     |
   v                     v
MainAppContents - - - > IModel

Is this the correct approach and does this mean that any start of a well designed app is a factory?


答:
In your code, you're only comparing the hours and ignoring the minutes. This causes the issue you have with the 14:00 - 14:45 period.

Because of how the dates are formatted and how you perform the comparison, you can just get away with a string-based comparison here:

const array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];

const times = ["05:45 - 06:00", "06:00 - 07:00",
     "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
     "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
     "13:00 - 14:00", "14:00 - 14:45"];

const grouped = times.map(time => {
  const [min, max] = time.split(' - ');
  const groupedData = array.filter(({dateTime}) => {
    const ts = dateTime.substring(9, 14);

    return ts >= min && ts < max;
  });

  return {time, groupedData};
});

console.log(grouped);```

Title: JS Data filter and group not correct


问:
Express.js: Undefined request body (base64)
I'm trying to convert the .xls table to .csv row.

I found the library that helps with such operation, its name XLSX

As the first step, I encode .xls table to base64 format.

Now I'm trying to send the post request with Postman (with base64 code as the body of the request)

But when I'm trying to console.log my req.body, I'm receiving undefined. Can you tell me where I could make a mistake in my app?

my app.js:

```<code>const express = require('express');
const dataConverter = require('./inputDataConverter');
const { errorHandler } = require('./../error/error-handler');

const app = express();
const port = process.env.PORT || 5000;
const domain = process.env.DOMAIN || '0.0.0.0';

app.post('/convert', dataConverter);
app.all('*', (req, res, next) => next('Invalid request'));

app.use(errorHandler);

app.listen(port, () => {
  console.log(`Microservice runs on http://${domain}:${port}`);
});
</code>```

inputDataConverter.js:

```<code>const XLSX = require('xlsx');

module.exports = (req, res, next) => {

  console.log('First console.log ' + req.body);

  const getWorkbook = (data) => {
    let wb = null;

    if (!data.type || data.type === 'base64') {
      wb = XLSX.read(data.body, { type: 'base64' });
    }

    console.log('everything is working');
    return wb;
  };

  const requestData = req.body;
  console.log(requestData);

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

答:
As Molda said
You may need body parser
https://www.npmjs.com/package/body-parser

On new version actually body-parser is embedded to express so you can use that like:

```<code>app.use(express.json())
</code>```

I really suggest you use express-generator package to generate base Express application
https://www.npmjs.com/package/express-generator

You may find something you may not need
just strip that out

Body:
I'm trying to convert the .xls table to .csv row.

I found the library that helps with such operation, its name XLSX

As the first step, I encode .xls table to base64 format.

Now I'm trying to send the post request with Postman (with base64 code as the body of the request)

But when I'm trying to console.log my req.body, I'm receiving undefined. Can you tell me where I could make a mistake in my app?

my app.js:

const express = require('express');
const dataConverter = require('./inputDataConverter');
const { errorHandler } = require('./../error/error-handler');

const app = express();
const port = process.env.PORT || 5000;
const domain = process.env.DOMAIN || '0.0.0.0';

app.post('/convert', dataConverter);
app.all('*', (req, res, next) => next('Invalid request'));

app.use(errorHandler);

app.listen(port, () => {
  console.log(`Microservice runs on http://${domain}:${port}`);
});

inputDataConverter.js:

const XLSX = require('xlsx');

module.exports = (req, res, next) => {

  console.log('First console.log ' + req.body);

  const getWorkbook = (data) => {
    let wb = null;

    if (!data.type || data.type === 'base64') {
      wb = XLSX.read(data.body, { type: 'base64' });
    }

    console.log('everything is working');
    return wb;
  };

  const requestData = req.body;
  console.log(requestData);

  getWorkbook(requestData);
};

Body:
As Molda said
You may need body parser
https://www.npmjs.com/package/body-parser

On new version actually body-parser is embedded to express so you can use that like:

app.use(express.json())

I really suggest you use express-generator package to generate base Express application
https://www.npmjs.com/package/express-generator

You may find something you may not need
just strip that out


问:
How to extract data from a dropdown menu using python beautifulsoup
I am trying to scrape data from a website that has a multilevel drop-down menu every time an item is selected it changes the sub items for sub drop-downs.
problem is that for every loop it extracts same sub items from the drop down items. the selection happens but it do not update the items on behalf of new selection from loop
can any one help me why I am not getting the desired results.
Perhaps this is because my drop-down list is in java Script or something.

for instance like this manue in the picture below:

i have gone this far:

```<code>enter code here

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv

//#from selenium.webdriver.support import Select
import time

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

//#variables
yeart = []
make= []
model=[]
body = []
submodel = []
size = []
Yindex = Mkindex = Mdindex = Bdindex = Smindex = Sindex = 0

print ("waiting for program to set variables....")
time.sleep(20)

print ("initializing and setting variables....")

//#initializing Year
Year = Select(driver.find_element_by_id("icm-years-select"))
Year.select_by_value('2020')
yr = driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]')
time.sleep(15)

//#initializing Make
Make = Select(driver.find_element_by_id("icm-makes-select"))
Make.select_by_index(1)
mk = driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]')
time.sleep(15)

//#initializing Model
Model = Select(driver.find_element_by_id("icm-models-select"))
Model.select_by_index(1)
mdl = driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]')
time.sleep(15)

//#initializing body
Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
Body.select_by_index(1)
bdy = driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]')
time.sleep(15)

//#initializing submodel
Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
Submodel.select_by_index(1)
sbm = driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]')
time.sleep(15)

//#initializing size
Size = Select(driver.find_element_by_id("icm-sizes-select"))
Size.select_by_index(0)
siz = driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]')
time.sleep(5)

Cyr = Cmk = Cmd = Cbd = Csmd = Csz = ""

print ("fetching data from variables....")

for y in yr:
    obj1 = driver.find_element_by_id("icm-years-select")
    Year = Select(obj1)
    Year.select_by_index(++Yindex)
    obj1.click()
    #obj1.click()
    yeart.append(y.text)
    Cyr = y.text
    time.sleep(10)
    for m in mk:
        obj2 = driver.find_element_by_id("icm-makes-select")
        Make = Select(obj2)
        Make.select_by_index(++Mkindex)
        obj2.click()
        #obj2.click()
        make.append(m.text)
        Cmk = m.text
        time.sleep(10)
        for md in mdl:
            Mdindex =0
            obj3 = driver.find_element_by_id("icm-models-select")
            Model = Select(obj3)
            Model.select_by_index(++Mdindex)
            obj3.click()
            #obj3.click(clickobj)
            model.append(md.text)
            Cmd = md.text
            time.sleep(10)
            Bdindex = 0
            for bd in bdy:
                obj4 = driver.find_element_by_id("icm-drivebodies-select")
                Body = Select(obj4)
                Body.select_by_index(++Bdindex)
                obj4.click()
                #obj4.click(clickobj2)
                body.append(bd.text)
                Cbd = bd.text
                time.sleep(10)
                Smindex = 0
                for sm in sbm:
                    obj5 = driver.find_element_by_id("icm-submodels-select")
                    Submodel = Select(obj5)
                    obj5.click()
                    Submodel.select_by_index(++Smindex)
                    #obj5.click(clickobj5)
                    submodel.append(sm.text)
                    Csmd = sm.text
                    time.sleep(10)
                    Sindex = 0
                    for sz in siz:
                        Size = Select(driver.find_element_by_id("icm-sizes-select"))
                        Size.select_by_index(++Sindex)
                        size.append(sz.text)
                        Scz = sz.text
                        csvData += [Cyr, Cmk, Cmd, Cbd,Csmd, Csz]
</code>```

答:
I guess the reason you can't parse the years with beautiful soup is because the 'select' tag containing the 'option' tags with all the years is not present yet/is hidden at the moment when beautiful soup downloads the page. It is added to the DOM by executing additional JavaScript I assume. If you look at the DOM of the loaded page using the developer tools of your browser, for example F12 for Mozilla, you'll see that the tag containing the information you look for is: <select id="icm-years-select"">. If you try to parse for this tag with the object downloaded with beautiful soup, you get an empty list of tag objects:

```<code>from bs4 import BeautifulSoup
from requests import get
response = get('https://www.wheelmax.com/')
yourSoup = BeautifulSoup(response.text, "lxml")
print(len(yourSoup.select('div #vehicle-search'))) // length = 1 -> visible
print()
print(len(yourSoup.select('#icm-years-select')))    // length = 0 -> not visible
</code>```

So if you want to get the years by using Python by all means, I guess you might try to click on the respective tag and then parse again using some combination of requests/beautiful soup/ or the selenium module which will require a bit more digging :-)

Otherwise if you just quickly need the years parsed, use JavaScript:

```<code>countYears = document.getElementById('icm-years-select').length;
yearArray = [];
for (i = 0; i < countYears; i++) {yearArray.push(document.getElementById('icm-years-select')[i].value)};
</code>```

Body:
I am trying to scrape data from a website that has a multilevel drop-down menu every time an item is selected it changes the sub items for sub drop-downs.
problem is that for every loop it extracts same sub items from the drop down items. the selection happens but it do not update the items on behalf of new selection from loop
can any one help me why I am not getting the desired results.
Perhaps this is because my drop-down list is in java Script or something.

for instance like this manue in the picture below:

i have gone this far:

enter code here

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv

//#from selenium.webdriver.support import Select
import time

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

//#variables
yeart = []
make= []
model=[]
body = []
submodel = []
size = []
Yindex = Mkindex = Mdindex = Bdindex = Smindex = Sindex = 0

print ("waiting for program to set variables....")
time.sleep(20)

print ("initializing and setting variables....")

//#initializing Year
Year = Select(driver.find_element_by_id("icm-years-select"))
Year.select_by_value('2020')
yr = driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]')
time.sleep(15)

//#initializing Make
Make = Select(driver.find_element_by_id("icm-makes-select"))
Make.select_by_index(1)
mk = driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]')
time.sleep(15)

//#initializing Model
Model = Select(driver.find_element_by_id("icm-models-select"))
Model.select_by_index(1)
mdl = driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]')
time.sleep(15)

//#initializing body
Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
Body.select_by_index(1)
bdy = driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]')
time.sleep(15)

//#initializing submodel
Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
Submodel.select_by_index(1)
sbm = driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]')
time.sleep(15)

//#initializing size
Size = Select(driver.find_element_by_id("icm-sizes-select"))
Size.select_by_index(0)
siz = driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]')
time.sleep(5)

Cyr = Cmk = Cmd = Cbd = Csmd = Csz = ""

print ("fetching data from variables....")

for y in yr:
    obj1 = driver.find_element_by_id("icm-years-select")
    Year = Select(obj1)
    Year.select_by_index(++Yindex)
    obj1.click()
    #obj1.click()
    yeart.append(y.text)
    Cyr = y.text
    time.sleep(10)
    for m in mk:
        obj2 = driver.find_element_by_id("icm-makes-select")
        Make = Select(obj2)
        Make.select_by_index(++Mkindex)
        obj2.click()
        #obj2.click()
        make.append(m.text)
        Cmk = m.text
        time.sleep(10)
        for md in mdl:
            Mdindex =0
            obj3 = driver.find_element_by_id("icm-models-select")
            Model = Select(obj3)
            Model.select_by_index(++Mdindex)
            obj3.click()
            #obj3.click(clickobj)
            model.append(md.text)
            Cmd = md.text
            time.sleep(10)
            Bdindex = 0
            for bd in bdy:
                obj4 = driver.find_element_by_id("icm-drivebodies-select")
                Body = Select(obj4)
                Body.select_by_index(++Bdindex)
                obj4.click()
                #obj4.click(clickobj2)
                body.append(bd.text)
                Cbd = bd.text
                time.sleep(10)
                Smindex = 0
                for sm in sbm:
                    obj5 = driver.find_element_by_id("icm-submodels-select")
                    Submodel = Select(obj5)
                    obj5.click()
                    Submodel.select_by_index(++Smindex)
                    #obj5.click(clickobj5)
                    submodel.append(sm.text)
                    Csmd = sm.text
                    time.sleep(10)
                    Sindex = 0
                    for sz in siz:
                        Size = Select(driver.find_element_by_id("icm-sizes-select"))
                        Size.select_by_index(++Sindex)
                        size.append(sz.text)
                        Scz = sz.text
                        csvData += [Cyr, Cmk, Cmd, Cbd,Csmd, Csz]

Body:
I guess the reason you can't parse the years with beautiful soup is because the 'select' tag containing the 'option' tags with all the years is not present yet/is hidden at the moment when beautiful soup downloads the page. It is added to the DOM by executing additional JavaScript I assume. If you look at the DOM of the loaded page using the developer tools of your browser, for example F12 for Mozilla, you'll see that the tag containing the information you look for is: <select id="icm-years-select"">. If you try to parse for this tag with the object downloaded with beautiful soup, you get an empty list of tag objects:

from bs4 import BeautifulSoup
from requests import get
response = get('https://www.wheelmax.com/')
yourSoup = BeautifulSoup(response.text, "lxml")
print(len(yourSoup.select('div #vehicle-search'))) // length = 1 -> visible
print()
print(len(yourSoup.select('#icm-years-select')))    // length = 0 -> not visible

So if you want to get the years by using Python by all means, I guess you might try to click on the respective tag and then parse again using some combination of requests/beautiful soup/ or the selenium module which will require a bit more digging :-)

Otherwise if you just quickly need the years parsed, use JavaScript:

countYears = document.getElementById('icm-years-select').length;
yearArray = [];
for (i = 0; i < countYears; i++) {yearArray.push(document.getElementById('icm-years-select')[i].value)};


问:
Insert images to Entry or Editor [Xamarin.Forms]
Is there any way to add images to Entry or Editor in Xamarin Forms?

Thanks in advance!

Cheers!

答:
If you just want to insert image in Entry control, you can create custom entry, please take a look this article:

https://xamgirl.com/image-entry-in-xamarin-forms/

If you want to add emoji in Entry, and delete it, I suggest you can set Keyboard=chat for Entry:

```<code><Entry Keyboard="Chat" />
</code>```

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/entry

Body:
If you just want to insert image in Entry control, you can create custom entry, please take a look this article:

https://xamgirl.com/image-entry-in-xamarin-forms/

If you want to add emoji in Entry, and delete it, I suggest you can set Keyboard=chat for Entry:

<Entry Keyboard="Chat" />

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/entry


问:
Page load doesn`t throw error even when the page hasn`t loaded and has 'Error: 500 Server Error'
Below code is to check if page is loaded or not, it returns without any error even though page has 'Error: 500 Server Error, Application Init Error. We are unable to display the requested page.' displayed.

I haven`t tried anything other than WaitForPageLoad which have found on stackoverflow.

```<code>public static void WaitForPageLoad(IWebwebDriver webwebDriver, int WaitTime = 12)
{
    string pageStatus = string.Empty;
    OpenQA.Selenium.Support.UI.WebwebDriverWait wait = new OpenQA.Selenium.Support.UI.WebwebDriverWait(webDriver, TimeSpan.FromSeconds(WaitTime));
        wait.Until(w =>
        {
        try
        {
        pageStatus = ((IJavaScriptExecutor)webDriver).ExecuteScript(@"return document.readyState").ToString();
        }
        catch (NoSuchWindowException)
        {
        webDriver.SwitchTo().Window(webDriver.WindowHandles.Last());
        }
        return (pageStatus.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || pageStatus.Equals("loaded", StringComparison.InvariantCultureIgnoreCase));
        });
}
</code>```

I was expecting it to throw error when the page has errors or not loaded at all. There are also some cases where a part of the page isnt loaded but still returns page state as 'complete'. Kindly check and let me know if this can be handled. Am even okay to check out for third party APIs like fiddler if therere great solutions.

答:
First of all there is no document.readypageStatus, there is document.readyState  so I would recommend reconsidering your page loading completion logic.

If your application is built using AJAX technology in addition to your function (or instead of it) you could go for Explicit Wait feature like:

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(12));
IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("someid")));
</code>```

This way Selenium will wait for element with the id attribute of someid for 12 seconds and proceed as soon as it will be found. If the element will not appear within 12 seconds time frame - you will get a WebDriverTimeoutException

Body:
Below code is to check if page is loaded or not, it returns without any error even though page has 'Error: 500 Server Error, Application Init Error. We are unable to display the requested page.' displayed.

I haven`t tried anything other than WaitForPageLoad which have found on stackoverflow.

public static void WaitForPageLoad(IWebwebDriver webwebDriver, int WaitTime = 12)
{
    string pageStatus = string.Empty;
    OpenQA.Selenium.Support.UI.WebwebDriverWait wait = new OpenQA.Selenium.Support.UI.WebwebDriverWait(webDriver, TimeSpan.FromSeconds(WaitTime));
        wait.Until(w =>
        {
        try
        {
        pageStatus = ((IJavaScriptExecutor)webDriver).ExecuteScript(@"return document.readyState").ToString();
        }
        catch (NoSuchWindowException)
        {
        webDriver.SwitchTo().Window(webDriver.WindowHandles.Last());
        }
        return (pageStatus.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || pageStatus.Equals("loaded", StringComparison.InvariantCultureIgnoreCase));
        });
}

I was expecting it to throw error when the page has errors or not loaded at all. There are also some cases where a part of the page isnt loaded but still returns page state as 'complete'. Kindly check and let me know if this can be handled. Am even okay to check out for third party APIs like fiddler if therere great solutions.

Body:
First of all there is no document.readypageStatus, there is document.readyState  so I would recommend reconsidering your page loading completion logic.

If your application is built using AJAX technology in addition to your function (or instead of it) you could go for Explicit Wait feature like:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(12));
IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("someid")));

This way Selenium will wait for element with the id attribute of someid for 12 seconds and proceed as soon as it will be found. If the element will not appear within 12 seconds time frame - you will get a WebDriverTimeoutException


问:
Why isn't __bases__ accessible in the class body?
Class objects have a __bases__ (and a __base__) attribute:

```<code>>>> class Foo(object):
...     pass
...
>>> Foo.__bases__
(<class 'object'>,)
</code>```

Sadly, these attributes aren't accessible in the class body, which would be very convenient for accessing parent class attributes without having to hard-code the name:

```<code>class Foo:
    cls_attr = 3

class Bar(Foo):
    cls_attr = __base__.cls_attr + 2
    # throws NameError: name '__base__' is not defined
</code>```

Is there a reason why __bases__ and __base__ can't be accessed in the class body?

(To be clear, I'm asking if this is a conscious design decision. I'm not asking about the implementation; I know that __bases__ is a descriptor in type and that this descriptor can't be accessed until a class object has been created. I want to know why python doesn't create __bases__ as a local variable in the class body.)

答:
It's because it's simply is not yet created.

Consider the following:

```<code>>>> class baselessmeta(type):
...     def __new__(metaclass, class_name, bases, classdict):
...         return type.__new__(
...             metaclass,
...             class_name,
...             (), # I can just ignore all the base
...             {}
...         )
...
>>> class Baseless(int, metaclass=baselessmeta):
...     # imaginary print(__bases__, __base__)
...     ...
...
>>> Baseless.__bases__
(<class 'object'>,)
>>> Baseless.__base__
<class 'object'>
>>>
</code>```

What should the imaginary print result in?
Every python class is created via the type metaclass one way or another.
You have the int argument for the type() in bases argument, yet you do not know what is the return value is going to be. You may use that directly as a base in your metaclass, or you may return another base with your LOC.

Just realized your to be clear part and now my answer is useless haha. Oh welp.

Body:
Class objects have a __bases__ (and a __base__) attribute:

>>> class Foo(object):
...     pass
...
>>> Foo.__bases__
(<class 'object'>,)

Sadly, these attributes aren't accessible in the class body, which would be very convenient for accessing parent class attributes without having to hard-code the name:

class Foo:
    cls_attr = 3

class Bar(Foo):
    cls_attr = __base__.cls_attr + 2
    # throws NameError: name '__base__' is not defined

Is there a reason why __bases__ and __base__ can't be accessed in the class body?

(To be clear, I'm asking if this is a conscious design decision. I'm not asking about the implementation; I know that __bases__ is a descriptor in type and that this descriptor can't be accessed until a class object has been created. I want to know why python doesn't create __bases__ as a local variable in the class body.)

Body:
It's because it's simply is not yet created.

Consider the following:

>>> class baselessmeta(type):
...     def __new__(metaclass, class_name, bases, classdict):
...         return type.__new__(
...             metaclass,
...             class_name,
...             (), # I can just ignore all the base
...             {}
...         )
...
>>> class Baseless(int, metaclass=baselessmeta):
...     # imaginary print(__bases__, __base__)
...     ...
...
>>> Baseless.__bases__
(<class 'object'>,)
>>> Baseless.__base__
<class 'object'>
>>>

What should the imaginary print result in?
Every python class is created via the type metaclass one way or another.
You have the int argument for the type() in bases argument, yet you do not know what is the return value is going to be. You may use that directly as a base in your metaclass, or you may return another base with your LOC.

Just realized your to be clear part and now my answer is useless haha. Oh welp.


问:
Adding a Contact with the Google Contacts .NET API
I am using the following code to add a contact, but I get the following unhandled exception:
     Google.GData.Client.GDataRequestException: Execution of request failed: http://www.google.com/m8/feeds/contacts/default/full

```<code>        GDataCredentials myCred = new GDataCredentials("myusername", "mypassword");
        RequestSettings myRequestSettings = new RequestSettings("macpapa-GoogleCodeTest3-1", myCred);
        ContactsRequest myContactRequest = new ContactsRequest(myRequestSettings);

        Contact myContact = new Contact();
        myContact.Title = "Be Dazzle";
        PhoneNumber myPhoneNumber = new PhoneNumber("805-453-6688");
        myPhoneNumber.Rel = ContactsRelationships.IsGeneral;
        myPhoneNumber.Primary = true;
        myContact.Phonenumbers.Add(myPhoneNumber);

        EMail myEmail = new EMail("man@gmail.com", ContactsRelationships.IsHome);
        EMail myEmail2 = new EMail("mantest@gmail.com", ContactsRelationships.IsWork);
        myEmail.Primary = true;
        myContact.Emails.Add(myEmail);
        myContact.Emails.Add(myEmail2);

        PostalAddress postalAddress = new PostalAddress();
        postalAddress.Value = "123 somewhere lane";
        postalAddress.Primary = true;
        postalAddress.Rel = ContactsRelationships.IsHome;
        myContact.PostalAddresses.Add(postalAddress);

        Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
        Contact createdContact = myContactRequest.Insert<Contact>(feedUri, myContact);
</code>```

Any suggestions?

答: It may be related to the fact that your contact includes an email address: see this question. Does removing the myContact.Emails.Add lines help?  If not, does removing all the myContact.Xxx.Add lines help?

Body:
I am using the following code to add a contact, but I get the following unhandled exception:
     Google.GData.Client.GDataRequestException: Execution of request failed: http://www.google.com/m8/feeds/contacts/default/full

        GDataCredentials myCred = new GDataCredentials("myusername", "mypassword");
        RequestSettings myRequestSettings = new RequestSettings("macpapa-GoogleCodeTest3-1", myCred);
        ContactsRequest myContactRequest = new ContactsRequest(myRequestSettings);

        Contact myContact = new Contact();
        myContact.Title = "Be Dazzle";
        PhoneNumber myPhoneNumber = new PhoneNumber("805-453-6688");
        myPhoneNumber.Rel = ContactsRelationships.IsGeneral;
        myPhoneNumber.Primary = true;
        myContact.Phonenumbers.Add(myPhoneNumber);

        EMail myEmail = new EMail("man@gmail.com", ContactsRelationships.IsHome);
        EMail myEmail2 = new EMail("mantest@gmail.com", ContactsRelationships.IsWork);
        myEmail.Primary = true;
        myContact.Emails.Add(myEmail);
        myContact.Emails.Add(myEmail2);

        PostalAddress postalAddress = new PostalAddress();
        postalAddress.Value = "123 somewhere lane";
        postalAddress.Primary = true;
        postalAddress.Rel = ContactsRelationships.IsHome;
        myContact.PostalAddresses.Add(postalAddress);

        Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
        Contact createdContact = myContactRequest.Insert<Contact>(feedUri, myContact);

Any suggestions?


问:
Uncaught TypeError: Cannot set property 'value' of null after the page loads
I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads

```<code>var app_page_id         = 40;
var app_pattern_page_id     = 32;
var app_id;
var checksum;
var lang;

$(document).ready(function() {
    app_id = $("#pFlowId").val();
    checksum = $("#pInstance").val();

    createMyFlow();

    function createMyFlow(){
        var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc,  $v('pFlowStepId'));
        lang = jQuery.parseJSON(result.get()).lang;
        createMyArea();
        result = loadDataFromMyOra();
        if(result !== null)
            findPattern(result);
    }

    function createMyArea(){
        var textArea;
        for ( var key in lang){
            textArea = '<tr><td  align="right"><label for="P'+app_page_id+'_VALUE_'+key+'">';
            textArea += '<span class="optional">Name '+languages[key][0]+': </span></label></td>';
            textArea += '<td  align="left" valign="middle">';
            textArea += '<input type="hidden" name="p_arg_names" />';
            textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
            textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
            textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
            textArea += '</td></tr>';
        $('.formlayout').append(textArea);
        }
    }

    function findPattern(patterns)
    {
        var item = "";
        for ( var key in patterns){
            item = patterns[key]+"";
            item = item.replace(/,/g,",");
            item = item.replace(/“/g,'"')
            document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;   //error here
        }
    }
});
</code>```

答:
The function that generates the code createMyArea() uses the keys in the lang variable

```<code>for ( var key in lang){
....
textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
....
</code>```

but in the findPatterns you are checking the id of the document using keys from another variable

```<code>for ( var key in patterns){
....
document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;
....
</code>```

If the patterns variable and lang variable don't have the same key, then you will get an error.

To check that, you can

```<code>console.log ("P'+app_page_id+'_VALUE'+key+'")
</code>```

just before the document.getElementById and see what values is checked there.

Body:
I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads

var app_page_id         = 40;
var app_pattern_page_id     = 32;
var app_id;
var checksum;
var lang;

$(document).ready(function() {
    app_id = $("#pFlowId").val();
    checksum = $("#pInstance").val();

    createMyFlow();

    function createMyFlow(){
        var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc,  $v('pFlowStepId'));
        lang = jQuery.parseJSON(result.get()).lang;
        createMyArea();
        result = loadDataFromMyOra();
        if(result !== null)
            findPattern(result);
    }

    function createMyArea(){
        var textArea;
        for ( var key in lang){
            textArea = '
';
            textArea += 'Name '+languages[key][0]+': 	';
            textArea += '';
            textArea += '<input type="hidden" name="p_arg_names" />';
            textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
            textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
            textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
            textArea += '
';
        $('.formlayout').append(textArea);
        }
    }

    function findPattern(patterns)
    {
        var item = "";
        for ( var key in patterns){
            item = patterns[key]+"";
            item = item.replace(/,/g,",");
            item = item.replace(/“/g,'"')
            document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;   //error here
        }
    }
});

Body:
The function that generates the code createMyArea() uses the keys in the lang variable

for ( var key in lang){
....
textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
....

but in the findPatterns you are checking the id of the document using keys from another variable

for ( var key in patterns){
....
document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;
....

If the patterns variable and lang variable don't have the same key, then you will get an error.

To check that, you can

console.log ("P'+app_page_id+'_VALUE'+key+'")

just before the document.getElementById and see what values is checked there.


问:
Consumer and producer failing with error: "Connection to 0 was disconnected before the response was read"
I have a cluster of 3 Kafka brokers with replication factor of 3 for all topics. Since last few days I am facing this issue, suddenly(few times in a day) consumers and producers are stuck while getting response even when Kafka is running on all 3 servers which gets resolved until I check brokers logs ("Connection to 0 was disconnected before the response was read")and find out the culprit node which is 0 (1st node in this case)and restarts zookeeper and broker on that node.

As per logs it is happening due to rebalancing.

I reduces min.insync.replicas to 2, but it doesn't help.

Server logs of 0 (1st node) which caused problem in this case:

```<code>Member consumer-3-8e370c0e-4a21-4dec-8301-18ce6aaf71d9 in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Preparing to rebalance group banner in state PreparingRebalance with old generation 2570 (__consumer_offsets-5) (reason: removing member consumer-3-8e370c0e-4a21-4dec-8301-18ce6aaf71d9 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
  Member consumer-4-da57dad3-6825-4a6d-ac93-82a29f72a3dc in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-2-812b613b-3409-42e7-baf8-8b32df4e2fa4 in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-2-d03f0417-4e0f-4ab0-90c6-12b17a6354d7 in group poster has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Preparing to rebalance group poster in state PreparingRebalance with old generation 191 (__consumer_offsets-9) (reason: removing member consumer-2-d03f0417-4e0f-4ab0-90c6-12b17a6354d7 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
  Group poster with generation 192 is now empty (__consumer_offsets-9) (kafka.coordinator.group.GroupCoordinator)
  Member rdkafka-fda5cec6-e121-4ab7-9650-83d391abc82d in group notification-test has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Stabilized group notification-test generation 436 (__consumer_offsets-20) (kafka.coordinator.group.GroupCoordinator)
  Member consumer-5-eeb1b721-b52b-4b65-af70-e48a345d150f in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-4-889659e2-3c2f-4059-bf0c-45796f824443 in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-5-95a38999-6156-4a53-ac1f-1d51703956fd in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Group banner with generation 2571 is now empty (__consumer_offsets-5) (kafka.coordinator.group.GroupCoordinator)
  Failed to write empty metadata for group poster: The group is rebalancing, so a rejoin is needed. (kafka.coordinator.group.GroupCoordinator)
  Failed to write empty metadata for group banner: The group is rebalancing, so a rejoin is needed. (kafka.coordinator.group.GroupCoordinator)
  Member consumer-5-e7a6af24-1f50-40cc-a593-cf8614e9d088 in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Preparing to rebalance group redemption in state PreparingRebalance with old generation 1373 (__consumer_offsets-27) (reason: removing member consumer-5-e7a6af24-1f50-40cc-a593-cf8614e9d088 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
  Member consumer-1-d89defb1-6637-48bc-ba16-b646c32d3849 in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-4-c942542b-7c54-4656-a485-410278b936ec in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-3-adfb6536-2fbc-4b39-9368-56b665db2c75 in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
[2019-05-19 13:22
</code>```

Logs of other broker:

```<code>java.io.IOException: Connection to 0 was disconnected before the response was read
        at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:97)
        at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:97)
        at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:190)
        at kafka.server.AbstractFetcherThread.kafka$server$AbstractFetcherThread$$processFetchRequest(AbstractFetcherThread.scala:241)
        at kafka.server.AbstractFetcherThread$$anonfun$maybeFetch$1.apply(AbstractFetcherThread.scala:130)
        at kafka.server.AbstractFetcherThread$$anonfun$maybeFetch$1.apply(AbstractFetcherThread.scala:129)
        at scala.Option.foreach(Option.scala:257)
        at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:129)
        at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:111)
        at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:82)

</code>```

Logs of consumer service:

```<code>|FAIL|rdkafka#consumer-2| [thrd:m-data-kaf006.c-14cba.internal:9092/2]: m-data-kaf006.c.internal:9092/2: 3 request(s) timed out: disconnect
</code>```

Not able to find the solution for this.

Kafka version: 2.1.0

答: This is due to an issue in an older kafka version. You need to upgrade your kafka to 2.2.0, 2.1.1  Please find below the underlying jira issue - https://issues.apache.org/jira/browse/KAFKA-7697 </p>

Body:
I have a cluster of 3 Kafka brokers with replication factor of 3 for all topics. Since last few days I am facing this issue, suddenly(few times in a day) consumers and producers are stuck while getting response even when Kafka is running on all 3 servers which gets resolved until I check brokers logs ("Connection to 0 was disconnected before the response was read")and find out the culprit node which is 0 (1st node in this case)and restarts zookeeper and broker on that node.

As per logs it is happening due to rebalancing.

I reduces min.insync.replicas to 2, but it doesn't help.

Server logs of 0 (1st node) which caused problem in this case:

Member consumer-3-8e370c0e-4a21-4dec-8301-18ce6aaf71d9 in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Preparing to rebalance group banner in state PreparingRebalance with old generation 2570 (__consumer_offsets-5) (reason: removing member consumer-3-8e370c0e-4a21-4dec-8301-18ce6aaf71d9 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
  Member consumer-4-da57dad3-6825-4a6d-ac93-82a29f72a3dc in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-2-812b613b-3409-42e7-baf8-8b32df4e2fa4 in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-2-d03f0417-4e0f-4ab0-90c6-12b17a6354d7 in group poster has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Preparing to rebalance group poster in state PreparingRebalance with old generation 191 (__consumer_offsets-9) (reason: removing member consumer-2-d03f0417-4e0f-4ab0-90c6-12b17a6354d7 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
  Group poster with generation 192 is now empty (__consumer_offsets-9) (kafka.coordinator.group.GroupCoordinator)
  Member rdkafka-fda5cec6-e121-4ab7-9650-83d391abc82d in group notification-test has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Stabilized group notification-test generation 436 (__consumer_offsets-20) (kafka.coordinator.group.GroupCoordinator)
  Member consumer-5-eeb1b721-b52b-4b65-af70-e48a345d150f in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-4-889659e2-3c2f-4059-bf0c-45796f824443 in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-5-95a38999-6156-4a53-ac1f-1d51703956fd in group banner has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Group banner with generation 2571 is now empty (__consumer_offsets-5) (kafka.coordinator.group.GroupCoordinator)
  Failed to write empty metadata for group poster: The group is rebalancing, so a rejoin is needed. (kafka.coordinator.group.GroupCoordinator)
  Failed to write empty metadata for group banner: The group is rebalancing, so a rejoin is needed. (kafka.coordinator.group.GroupCoordinator)
  Member consumer-5-e7a6af24-1f50-40cc-a593-cf8614e9d088 in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Preparing to rebalance group redemption in state PreparingRebalance with old generation 1373 (__consumer_offsets-27) (reason: removing member consumer-5-e7a6af24-1f50-40cc-a593-cf8614e9d088 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)
  Member consumer-1-d89defb1-6637-48bc-ba16-b646c32d3849 in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-4-c942542b-7c54-4656-a485-410278b936ec in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
  Member consumer-3-adfb6536-2fbc-4b39-9368-56b665db2c75 in group redemption has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)
[2019-05-19 13:22

Logs of other broker:

java.io.IOException: Connection to 0 was disconnected before the response was read
        at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:97)
        at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:97)
        at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:190)
        at kafka.server.AbstractFetcherThread.kafka$server$AbstractFetcherThread$$processFetchRequest(AbstractFetcherThread.scala:241)
        at kafka.server.AbstractFetcherThread$$anonfun$maybeFetch$1.apply(AbstractFetcherThread.scala:130)
        at kafka.server.AbstractFetcherThread$$anonfun$maybeFetch$1.apply(AbstractFetcherThread.scala:129)
        at scala.Option.foreach(Option.scala:257)
        at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:129)
        at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:111)
        at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:82)

Logs of consumer service:

|FAIL|rdkafka#consumer-2| [thrd:m-data-kaf006.c-14cba.internal:9092/2]: m-data-kaf006.c.internal:9092/2: 3 request(s) timed out: disconnect

Not able to find the solution for this.

Kafka version: 2.1.0


问:
Padding dublicate in scrolling div, works in edge but not in chrome
I use padding-bottom in my project to get an aspect ratio, but the padding-bottom duplicate itself inside the overflow works in edge, but not in chrome.
What can I do to fix the problem and so it works in chrome to? :)

Link to codepen: https://codepen.io/mullermeck/pen/byKeWX

 .scroll {
    width: 50%;
    height: 0;
    padding-bottom: 300px;
    background-color: green;
    overflow-y: scroll;
    overflow-x: hidden;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scroll">
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
</div></code>```

I have done research but haven't found any answers to it...
this is also my first post on here so it may be wrong

答:
Try this I think it's useful for you to remove the padding-bottom: 300px; property and in place of height: 0; you have to use height: auto;.

 .scroll {
    width: 50%;
    height: auto;
/*     padding-bottom: 300px; */
    background-color: green;
    overflow-y: scroll;
    overflow-x: hidden;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scroll">
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
</div></code>```

Body:
I use padding-bottom in my project to get an aspect ratio, but the padding-bottom duplicate itself inside the overflow works in edge, but not in chrome.
What can I do to fix the problem and so it works in chrome to? :)

Link to codepen: https://codepen.io/mullermeck/pen/byKeWX

 .scroll {
    width: 50%;
    height: 0;
    padding-bottom: 300px;
    background-color: green;
    overflow-y: scroll;
    overflow-x: hidden;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}

I have done research but haven't found any answers to it...
this is also my first post on here so it may be wrong

Body:
Try this I think it's useful for you to remove the padding-bottom: 300px; property and in place of height: 0; you have to use height: auto;.

 .scroll {
    width: 50%;
    height: auto;
/*     padding-bottom: 300px; */
    background-color: green;
    overflow-y: scroll;
    overflow-x: hidden;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}

<div class="scroll">
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
</div>


问:
Segmentation fault when passing big integers as values in vector
Getting segmentation fault(Core Dumped) when big integers are passed. It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally, but still the same error. This function is used to perform a number of right circular rotations and return the value of the element at a given index. Here is the function:

```<code>    vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
        vector <long long int> b;
        std::vector<long long int> result(queries.size());

        b=a;
        for(long long int j=0;j<k;j++)
        {
            for(long long int i=0;i<a.size();i++)
                a[i]=b[(a.size()+i-1)%a.size()];
            b=a;
        }

        for(long long int k=0;k<queries.size();k++)
            result[k]=a[queries[k]];
        for(long long int i=0;i<result.size();i++)
                cout<<result[i]<<endl;

        return result;

    }
</code>```

The remaining code can be found here link

答:
Quality of the implementation aside (there is no need to make any copy to rotate a vector, it can be done in-place), most probably the error causing the segfault is in the code that's not shown.

To debug this further the following links might be of use:

How to debug with gdb?

Determine the line of code that causes a segmentation fault

If you need further assistance, post your entire code.

== EDIT ==

Your code isn't triggering a segfault but a "Terminated due to timeout" error on HackerRank. In other words, your solution is too slow.

That's because there is no need to rotate anything to solve Circular Array Rotation:

```<code>vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
    vector<int> res;
    res.reserve(queries.size());
    int offset = k % a.size() - a.size();
    for (int i : queries) {
        res.push_back(a[(i - offset) % a.size()]);
    }
    return res;
}
</code>```

i.e. just take the rotation into account when selecting the requested element.

Body:
Getting segmentation fault(Core Dumped) when big integers are passed. It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally, but still the same error. This function is used to perform a number of right circular rotations and return the value of the element at a given index. Here is the function:

    vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
        vector <long long int> b;
        std::vector<long long int> result(queries.size());

        b=a;
        for(long long int j=0;j<k;j++)
        {
            for(long long int i=0;i<a.size();i++)
                a[i]=b[(a.size()+i-1)%a.size()];
            b=a;
        }

        for(long long int k=0;k<queries.size();k++)
            result[k]=a[queries[k]];
        for(long long int i=0;i<result.size();i++)
                cout<<result[i]<<endl;

        return result;

    }

The remaining code can be found here link

Body:
Quality of the implementation aside (there is no need to make any copy to rotate a vector, it can be done in-place), most probably the error causing the segfault is in the code that's not shown.

To debug this further the following links might be of use:

How to debug with gdb?

Determine the line of code that causes a segmentation fault

If you need further assistance, post your entire code.

== EDIT ==

Your code isn't triggering a segfault but a "Terminated due to timeout" error on HackerRank. In other words, your solution is too slow.

That's because there is no need to rotate anything to solve Circular Array Rotation:

vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
    vector<int> res;
    res.reserve(queries.size());
    int offset = k % a.size() - a.size();
    for (int i : queries) {
        res.push_back(a[(i - offset) % a.size()]);
    }
    return res;
}

i.e. just take the rotation into account when selecting the requested element.


问:
Append values from dataframe column to list
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

```<code>empty_list = [value_1,value_2,value_3...]
</code>```

I have tried the following:

```<code>df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())
</code>```

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

答:
You could try this script if you need to append one column only:

```<code>a_list = df['iso'].tolist()
</code>```

For extending a list by appending elements from the iterable, use extend:

```<code>a_list = []
a_list.extend(df['iso'].tolist())
a_list.extend(df['country'].tolist())
print (a_list)
['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']
</code>```

Another solution is to use numpy.ravel with transpose:

```<code>a_list = df[['iso','country']].values.T.ravel().tolist()
print (a_list)
['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']
</code>```

Body:
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

empty_list = [value_1,value_2,value_3...]

I have tried the following:

df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

Body:
You could try this script if you need to append one column only:

a_list = df['iso'].tolist()

For extending a list by appending elements from the iterable, use extend:

a_list = []
a_list.extend(df['iso'].tolist())
a_list.extend(df['country'].tolist())
print (a_list)
['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']

Another solution is to use numpy.ravel with transpose:

a_list = df[['iso','country']].values.T.ravel().tolist()
print (a_list)
['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']


问:
Tkinter Missing possitional argument
I'm trying to make a GUI, that will tell me when I press numbers: 1,2,3,4, It works fine, but It throws an error message in background, when I press the button. It looks like this

```<code>    xception in Tkinter callback
    Traceback (most recent call last):
    File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
    File "/usr/lib/python3.7/tkinter/__init__.py", line 749, in callit
    func(*args)
    TypeError: shukkin() missing 1 required positional argument: 'event'
</code>```

Can someone please tell my, how to make a def shukkin(event): stop throwing that error msg? Where is a problem.

Here is the code

from tkinter import *
from tkinter import ttk
from tkinter import font
from tkinter import Button as bt
import time

def quit(*args):
    root.destroy()

def show_time():
    txt.set(time.strftime("%H:%M:%S"))
    root.after(1000, show_time)

def shukkin(event):
    txt2.set("1")
    fm3.after(100, shukkin)
def taikin(event):
    txt2.set("2")
    fm3.after(100, taikin)
def shuuchou(event):
    txt2.set("3")
    fm3.after(100, shuuchou)
def hoka(event):
    txt2.set("4")
    fm3.after(100, hoka)

root = Tk()
root.attributes("-fullscreen", True)
root.configure(background='black')
for i in range(10):
    root.bind(str(1), shukkin)
    root.bind(str(2), taikin)
    root.bind(str(3), shuuchou)
    root.bind(str(4), hoka)
root.bind("<Escape>", quit)
root.bind("x", quit)
root.after(1000, show_time)

fnt = font.Font(family='Helvetica', size=96, weight='bold')
fnt2 = font.Font(family='Helvetica', size=30)
txt = StringVar()
txt.set(time.strftime("%H:%M:%S"))
fm = Frame(root)
fm.configure(background='black')
lbl = ttk.Label(fm, textvariable=txt, font=fnt, foreground="#469aff", background="black").pack(anchor=NW,padx=40, pady=40)
fm.pack(side=LEFT, fill=BOTH)

fm2 = Frame(root)
lbl = ttk.Label(fm2, text="ボタンを押して下さい \n 1:出勤 \n 2:退勤 \n 3:出張 \n 4:その他",
                font=fnt2, foreground="#469aff", background="black").pack(side=RIGHT)
fm2.pack(side=TOP, padx=8, pady=130)

fm3 = Frame(root,  width=500, height=500)
txt2 = StringVar()
but = ttk.Label(fm3, textvariable=txt2, font=fnt, foreground="#469aff", background="black").pack()
fm3.pack(side=TOP)

root.mainloop()

```

答:
Your shukkin takes an event as arg, but there is no event generated by the after method, hence the error.

Simply make a small change to your shukkin function to make event optional:

```<code>def shukkin(event=None):
    txt2.set("1")
    fm3.after(100, shukkin)
</code>```

Title: Tkinter Missing possitional argument

Body:
I'm trying to make a GUI, that will tell me when I press numbers: 1,2,3,4, It works fine, but It throws an error message in background, when I press the button. It looks like this

    xception in Tkinter callback
    Traceback (most recent call last):
    File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
    File "/usr/lib/python3.7/tkinter/__init__.py", line 749, in callit
    func(*args)
    TypeError: shukkin() missing 1 required positional argument: 'event'

Can someone please tell my, how to make a def shukkin(event): stop throwing that error msg? Where is a problem.

Here is the code

from tkinter import *
from tkinter import ttk
from tkinter import font
from tkinter import Button as bt
import time

def quit(*args):
    root.destroy()

def show_time():
    txt.set(time.strftime("%H:%M:%S"))
    root.after(1000, show_time)

def shukkin(event):
    txt2.set("1")
    fm3.after(100, shukkin)
def taikin(event):
    txt2.set("2")
    fm3.after(100, taikin)
def shuuchou(event):
    txt2.set("3")
    fm3.after(100, shuuchou)
def hoka(event):
    txt2.set("4")
    fm3.after(100, hoka)

root = Tk()
root.attributes("-fullscreen", True)
root.configure(background='black')
for i in range(10):
    root.bind(str(1), shukkin)
    root.bind(str(2), taikin)
    root.bind(str(3), shuuchou)
    root.bind(str(4), hoka)
root.bind("<Escape>", quit)
root.bind("x", quit)
root.after(1000, show_time)

fnt = font.Font(family='Helvetica', size=96, weight='bold')
fnt2 = font.Font(family='Helvetica', size=30)
txt = StringVar()
txt.set(time.strftime("%H:%M:%S"))
fm = Frame(root)
fm.configure(background='black')
lbl = ttk.Label(fm, textvariable=txt, font=fnt, foreground="#469aff", background="black").pack(anchor=NW,padx=40, pady=40)
fm.pack(side=LEFT, fill=BOTH)

fm2 = Frame(root)
lbl = ttk.Label(fm2, text="ボタンを押して下さい \n 1:出勤 \n 2:退勤 \n 3:出張 \n 4:その他",
                font=fnt2, foreground="#469aff", background="black").pack(side=RIGHT)
fm2.pack(side=TOP, padx=8, pady=130)

fm3 = Frame(root,  width=500, height=500)
txt2 = StringVar()
but = ttk.Label(fm3, textvariable=txt2, font=fnt, foreground="#469aff", background="black").pack()
fm3.pack(side=TOP)

root.mainloop()

Body:
Your shukkin takes an event as arg, but there is no event generated by the after method, hence the error.

Simply make a small change to your shukkin function to make event optional:

def shukkin(event=None):
    txt2.set("1")
    fm3.after(100, shukkin)


问:
Customizing a modern page using SpFx
I want to transform a classic site into a modern experience and I have the following customization, done on a classic list form.

The page contains two Webparts:

XsltListViewWebPart to display the list of items

ContentEditorWebPart to fetch some summary data

Problem :

The SPFx extension used to replace the default rendering of the list works only on the allitems.aspx page (it is not working on my custom page which contains ListWebpart)

I need to know how to be able to make SPFx extension working on that ListWebpart.
Or if it is possible to add a client side webpart inside my allitems.apx page.

答:
We can't 'Edit' OOB modern list view currently.

When you add list view to a modern page, you could deploy react-script-editor to your tenant so you could add this webpart to modern page which works like script editor webpart in classic view.

Title: Customizing a modern page using SpFx


问:
How to swap a long variable present in list of a class with swap method
I have a list public List<ArticleWarehouseLocations> ArticleWarehouseLocationsList. In this list I have a property called Position.

```<code>`Swap<long>(ref ArticleWarehouseLocationsList[currentIndex].Position, ref ArticleWarehouseLocationsList[currentIndex - 1].Position);`
    public void Swap<T>(ref T lhs, ref T rhs)
     {
       T temp = lhs;
       lhs = rhs;
       rhs = temp;
      }
</code>```

I'm trying to do something like this. It's giving me an error property or index may not be passed as ref or out.

I can use a local variable and assign it the value and use it but I'm looking for a global solution.

答:
What you can do is make the property return by reference:

```<code>class Obj {
    private long pos;
    public ref long Position { get { return ref pos; } }
}

static void Main(string[] args)
{
        Obj[] arr = new Obj[2] { new Obj(), new Obj() };

        arr[0].Position = 10;
        arr[1].Position = 20;

        int index = 0;

        WriteLine($"{arr[index].Position}, {arr[index+1].Position}");
        Swap<long>(ref arr[index].Position, ref arr[index+1].Position);
        WriteLine($"{arr[index].Position}, {arr[index+1].Position}");
}
</code>```

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/ref-returns

Body:
I have a list public List<ArticleWarehouseLocations> ArticleWarehouseLocationsList. In this list I have a property called Position.

`Swap<long>(ref ArticleWarehouseLocationsList[currentIndex].Position, ref ArticleWarehouseLocationsList[currentIndex - 1].Position);`
    public void Swap<T>(ref T lhs, ref T rhs)
     {
       T temp = lhs;
       lhs = rhs;
       rhs = temp;
      }

I'm trying to do something like this. It's giving me an error property or index may not be passed as ref or out.

I can use a local variable and assign it the value and use it but I'm looking for a global solution.

Body:
What you can do is make the property return by reference:

class Obj {
    private long pos;
    public ref long Position { get { return ref pos; } }
}

static void Main(string[] args)
{
        Obj[] arr = new Obj[2] { new Obj(), new Obj() };

        arr[0].Position = 10;
        arr[1].Position = 20;

        int index = 0;

        WriteLine($"{arr[index].Position}, {arr[index+1].Position}");
        Swap<long>(ref arr[index].Position, ref arr[index+1].Position);
        WriteLine($"{arr[index].Position}, {arr[index+1].Position}");
}

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/ref-returns


问:
How can i implement an ASP.NT MVC Controller?
I am new to .NET FRAMEWORK, and am trying to come up with an ASP.NET MVC API for a real estate.
In my database, I have a table Product and Amenity. My assumption is a Product e.g Apartment can have several Amenities e.g [{ 'Gym' }, { 'Wifi' }]. Therefore, I have created another table ProductAmenity that references Product and Amenity.

I have so far come up with Product Class, Amenity class and ProductAmenity class with the corresponding ProductsController and ProductAmenitiesController. Currently when I do a get request on my ProductsController, it returns all the other values except it returns a NULL value in the Object- ProductAmenity despite their being data in the table ProductAmenity.

Here are my controllers:

namespace api_realEstate.Controllers
{
public class ProductsController : ApiController
    {
        readonly RealEstateDBEntities entities;
        public ProductsController()
        {
            entities = new RealEstateDBEntities();
        }
        private List<ProductView> PrepProducts(List<Product> dbProducts)
        {
            var productsView = new List<ProductView>();
            foreach (var product in dbProducts)
            {
                productsView.Add(
                    new ProductView
                    {
                        Id = product.ID,
                        Category = product.Category,
                        Address = product.Location,
                        Amount = product.Price,
                        Beds = product.Bathroom,
                        Baths = product.Bedroom,
                        Area = product.Area,
                        Parking = product.Parking,
                        ParkingSpot = product.ParkingSpot,
                        Description = product.Description,
                        Term = product.Term,
                        UserId = product.UserID
                    });
            }
            return productsView;
        }
        public IHttpActionResult Get()
        {
            var dbProducts = entities.Products.ToList();
            return Ok(PrepProducts(dbProducts));
        }
 }
}

namespace api_realEstate.Controllers
{
    public class AmenitiesController : ApiController
    {
        readonly RealEstateDBEntities entities;
        public AmenitiesController()
        {
            entities = new RealEstateDBEntities();
        }
        private List<AmenityView> PrepAmenities(List<Amenity> dbAmenities)
        {
            var amenitiesView = new List<AmenityView>();
            foreach (var amenity in dbAmenities)
            {
                amenitiesView.Add(
                    new AmenityView
                    {
                        Id = amenity.ID,
                        Itemname = amenity.ItemName
                    });
            }
            return amenitiesView;
        }
        public IHttpActionResult Get()
        {
            var dbAmenities = entities.Amenities.ToList();
            return Ok(PrepAmenities(dbAmenities));
        }
 }
}

namespace api_realEstate.Controllers
{
    public class ProductAmenitiesController : ApiController
    {
        readonly RealEstateDBEntities entities;
        public ProductAmenitiesController()
        {
            entities = new RealEstateDBEntities();
        }
        private List<ProductAmenityView> PrepProductAmenities(List<ProductAmenity> dbProdAmenity)
        {
            var prodamenityView = new List<ProductAmenityView>();
            foreach (var prodamenity in dbProdAmenity)
            {
                prodamenityView.Add(
                    new ProductAmenityView
                    {
                        Id = prodamenity.ID,
                        Productid = prodamenity.ProductID,
                        Amenityid = prodamenity.AmenityID
                    });
            }
            return prodamenityView;
        }
        public IHttpActionResult Get()
        {
            var dbProdAmenity = entities.ProductAmenities.ToList();
            return Ok(PrepProductAmenities(dbProdAmenity));
        }
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Here are my classes:

public partial class Product
    {
        public Product()
        {
            this.ProductAmenities = new HashSet<ProductAmenity>();
            this.ProductImages = new HashSet<ProductImage>();
        }
        public long ID { get; set; }
        public string Category { get; set; }
        public string Location { get; set; }
        public int Price { get; set; }
        public int Bedroom { get; set; }
        public int Bathroom { get; set; }
        public Nullable<int> Area { get; set; }
        public string Parking { get; set; }
        public Nullable<int> ParkingSpot { get; set; }
        public string Description { get; set; }
        public string Term { get; set; }
        public long UserID { get; set; }
        public virtual User User { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProductAmenity> ProductAmenities { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProductImage> ProductImages { get; set; }
    }

public partial class Amenity
    {
        public Amenity()
        {
            this.ProductAmenities = new HashSet<ProductAmenity>();
        }
        public long ID { get; set; }
        public string ItemName { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProductAmenity> ProductAmenities { get; set; }
    }

public partial class ProductAmenity
    {
        public long ID { get; set; }
        public long ProductID { get; set; }
        public long AmenityID { get; set; }
        public virtual Amenity Amenity { get; set; }
        public virtual Product Product { get; set; }
    } </code>```

I expect that when I do a (GET) request to my ProductsController, I should have values returned in my ProductAmenity object.
How can I apply the relationship between these tables: Product, Amenity and ProductAmenity within my Controller?

答:
In the productsView Model I just added this and it worked:

private List<ProductView> PrepProducts(List<Product> dbProducts)
        {
            var productsView = new List<ProductView>();
            foreach (var product in dbProducts)
            {
                productsView.Add(
                    new ProductView
                    {
                        Id = product.ID,
                        UserId = product.UserID,
                        Category = product.Category,
                        Address = product.Location,
                        Amount = product.Price,
                        Beds = product.Bathroom,
                        Baths = product.Bedroom,
                        Area = product.Area,
                        Parking = product.Parking,
                        ParkingSpot = product.ParkingSpot,
                        Description = product.Description,
                        Term = product.Term,

                        Amenities = product.ProductAmenities.Select(x => new Models.ProductAmenity
                        {
                            Id = x.ID,
                            Amenity = new AmenityView
                            {
                                Id = x.Amenity.ID,
                                Itemname = x.Amenity.ItemName
                            }
                        }).ToList()

            });
            return productsView;
        }```

Body:
I am new to .NET FRAMEWORK, and am trying to come up with an ASP.NET MVC API for a real estate.
In my database, I have a table Product and Amenity. My assumption is a Product e.g Apartment can have several Amenities e.g [{ 'Gym' }, { 'Wifi' }]. Therefore, I have created another table ProductAmenity that references Product and Amenity.

I have so far come up with Product Class, Amenity class and ProductAmenity class with the corresponding ProductsController and ProductAmenitiesController. Currently when I do a get request on my ProductsController, it returns all the other values except it returns a NULL value in the Object- ProductAmenity despite their being data in the table ProductAmenity.

Here are my controllers:

namespace api_realEstate.Controllers
{
public class ProductsController : ApiController
    {
        readonly RealEstateDBEntities entities;
        public ProductsController()
        {
            entities = new RealEstateDBEntities();
        }
        private List<ProductView> PrepProducts(List<Product> dbProducts)
        {
            var productsView = new List<ProductView>();
            foreach (var product in dbProducts)
            {
                productsView.Add(
                    new ProductView
                    {
                        Id = product.ID,
                        Category = product.Category,
                        Address = product.Location,
                        Amount = product.Price,
                        Beds = product.Bathroom,
                        Baths = product.Bedroom,
                        Area = product.Area,
                        Parking = product.Parking,
                        ParkingSpot = product.ParkingSpot,
                        Description = product.Description,
                        Term = product.Term,
                        UserId = product.UserID
                    });
            }
            return productsView;
        }
        public IHttpActionResult Get()
        {
            var dbProducts = entities.Products.ToList();
            return Ok(PrepProducts(dbProducts));
        }
 }
}

namespace api_realEstate.Controllers
{
    public class AmenitiesController : ApiController
    {
        readonly RealEstateDBEntities entities;
        public AmenitiesController()
        {
            entities = new RealEstateDBEntities();
        }
        private List<AmenityView> PrepAmenities(List<Amenity> dbAmenities)
        {
            var amenitiesView = new List<AmenityView>();
            foreach (var amenity in dbAmenities)
            {
                amenitiesView.Add(
                    new AmenityView
                    {
                        Id = amenity.ID,
                        Itemname = amenity.ItemName
                    });
            }
            return amenitiesView;
        }
        public IHttpActionResult Get()
        {
            var dbAmenities = entities.Amenities.ToList();
            return Ok(PrepAmenities(dbAmenities));
        }
 }
}

namespace api_realEstate.Controllers
{
    public class ProductAmenitiesController : ApiController
    {
        readonly RealEstateDBEntities entities;
        public ProductAmenitiesController()
        {
            entities = new RealEstateDBEntities();
        }
        private List<ProductAmenityView> PrepProductAmenities(List<ProductAmenity> dbProdAmenity)
        {
            var prodamenityView = new List<ProductAmenityView>();
            foreach (var prodamenity in dbProdAmenity)
            {
                prodamenityView.Add(
                    new ProductAmenityView
                    {
                        Id = prodamenity.ID,
                        Productid = prodamenity.ProductID,
                        Amenityid = prodamenity.AmenityID
                    });
            }
            return prodamenityView;
        }
        public IHttpActionResult Get()
        {
            var dbProdAmenity = entities.ProductAmenities.ToList();
            return Ok(PrepProductAmenities(dbProdAmenity));
        }
 }
}

Here are my classes:

public partial class Product
    {
        public Product()
        {
            this.ProductAmenities = new HashSet<ProductAmenity>();
            this.ProductImages = new HashSet<ProductImage>();
        }
        public long ID { get; set; }
        public string Category { get; set; }
        public string Location { get; set; }
        public int Price { get; set; }
        public int Bedroom { get; set; }
        public int Bathroom { get; set; }
        public Nullable<int> Area { get; set; }
        public string Parking { get; set; }
        public Nullable<int> ParkingSpot { get; set; }
        public string Description { get; set; }
        public string Term { get; set; }
        public long UserID { get; set; }
        public virtual User User { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProductAmenity> ProductAmenities { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProductImage> ProductImages { get; set; }
    }

public partial class Amenity
    {
        public Amenity()
        {
            this.ProductAmenities = new HashSet<ProductAmenity>();
        }
        public long ID { get; set; }
        public string ItemName { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProductAmenity> ProductAmenities { get; set; }
    }

public partial class ProductAmenity
    {
        public long ID { get; set; }
        public long ProductID { get; set; }
        public long AmenityID { get; set; }
        public virtual Amenity Amenity { get; set; }
        public virtual Product Product { get; set; }
    }

I expect that when I do a (GET) request to my ProductsController, I should have values returned in my ProductAmenity object.
How can I apply the relationship between these tables: Product, Amenity and ProductAmenity within my Controller?


问:
Identify "Start" and "End" date of a trip in SQL?
I want to get the start and end date of the trip from a table as shown below -

I have tried Min(Date) and then Max(Date) Group by Line_Number,Country
Also
LEAD function

Preferred Outcome

答:
Gaps and Islands...

Try this:

```<code>with tab (line_number, date, country) as (values
  (123456, date('2019-05-20'), 'London')
, (123456, date('2019-05-21'), 'London')
, (123456, date('2019-05-22'), 'London')
, (123456, date('2019-06-27'), 'London')
, (123456, date('2019-06-28'), 'London')
, (123456, date('2019-06-29'), 'London')
, (123456, date('2019-06-30'), 'London')
, (123456, date('2019-07-01'), 'London')
)
, a as (
select t.*
-- OLAP function sums the "flags" computed below,
-- so each group with consecutive dates has its distinct group number
, sum
(
-- The expression below
-- returns 1 if date of the current row is 1 day after the date of the previous row
-- in the corresponding group (line_number, country) ordered by date
-- and 0 otherwise
case when date = lag(date) over (partition by line_number, country order by date) + 1 day then 0 else 1 end
) over (partition by line_number, country order by date) grp_num
from tab t
)
select
  line_number
, min(date) as start_date
, max(date) as end_date
, country
--, grp_num
from a
group by line_number, country, grp_num;
</code>```

Body:
Gaps and Islands...

Try this:

with tab (line_number, date, country) as (values
  (123456, date('2019-05-20'), 'London')
, (123456, date('2019-05-21'), 'London')
, (123456, date('2019-05-22'), 'London')
, (123456, date('2019-06-27'), 'London')
, (123456, date('2019-06-28'), 'London')
, (123456, date('2019-06-29'), 'London')
, (123456, date('2019-06-30'), 'London')
, (123456, date('2019-07-01'), 'London')
)
, a as (
select t.*
-- OLAP function sums the "flags" computed below,
-- so each group with consecutive dates has its distinct group number
, sum
(
-- The expression below
-- returns 1 if date of the current row is 1 day after the date of the previous row
-- in the corresponding group (line_number, country) ordered by date
-- and 0 otherwise
case when date = lag(date) over (partition by line_number, country order by date) + 1 day then 0 else 1 end
) over (partition by line_number, country order by date) grp_num
from tab t
)
select
  line_number
, min(date) as start_date
, max(date) as end_date
, country
--, grp_num
from a
group by line_number, country, grp_num;


答:
Your problem arises from the fact that df['iso'].tolist() creates a list. The list is appended (given a place in the list at the single index), so you get a list of list. You can try:

```<code>a_list.extend(df['iso'].tolist())
</code>```

Title: Append values from dataframe column to list

Body:
Your problem arises from the fact that df['iso'].tolist() creates a list. The list is appended (given a place in the list at the single index), so you get a list of list. You can try:

a_list.extend(df['iso'].tolist())