问:
Order in Array of K8s entity
I have CRD (Custom Resource Definition) with a field with a type "array". I wonder if in this array the order is preserved , mens , if i apply yaml with:

```<code>myField:
- a
- b
- c
</code>```

And after that I get the entity using kubectl, it is promised to me that I get the order I mentions before and nor

```<code>myField:
- b
- a
- c
</code>```

答:
Yes, YAML sequences are ordered and preserve order across parsing and serialization.  From YAML 1.2 §3.2.1.1 (emphasis in original):

The content of a sequence node is an ordered series of zero or more nodes.

This is contrast to mapping nodes, which are unordered.

guaranteedToPreserveOrder: # a sequence of mappings with name: keys
  - name: a
    value: one
  - name: b
    value: two
notGuaranteedToPreserveOrder: # a simple mapping
  a: one
  b: two
```

Title: Order in Array of K8s entity

Body:
I have CRD (Custom Resource Definition) with a field with a type "array". I wonder if in this array the order is preserved , mens , if i apply yaml with:

myField:
- a
- b
- c

And after that I get the entity using kubectl, it is promised to me that I get the order I mentions before and nor

myField:
- b
- a
- c


来源: stackexchange

问:
Error 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*', when header contains "withCredentials" with request
I am sending a request from angular to my server with header withCredentials as true and on server side i have only allowed request from origin http://0.0.0.0:4200 where my angular is running. Since my request contains authorizaion header it sends preflight request and it fails with below error message.

But if you will look at my response of preflight request there is no wildcard in the value of header "Access-Control-Allow-Origin".

Preflight response:

Method in angular :

```<code>const headers = new HttpHeaders(credentials ? {
      authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
  } : {});
  headers.set("Access-Control-Allow-Origin","http://localhost:4200")
  this.http.get('http://localhost:8080/user', {headers: headers , withCredentials: true }).subscribe(response => {..}
</code>```

Can someone please explain me why i am getting this error and how to fix it?

SErver side code :-

CORSfilter.java

```<code>public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "authorization,withCredentials, content-type, xsrf-token, Cache-Control, Cookie");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
</code>```

SpringSecurityConfig class

```<code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
        http
        .httpBasic()
      .and()
        .authorizeRequests()
          .antMatchers("/").permitAll()
          .anyRequest().authenticated().and().csrf()
          .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());;
    }
}
</code>```

Controller class

```<code>@RestController
@CrossOrigin
public class SecurityController {

    @GetMapping("/hi")
    public Response method() {
        return new Response("Hi this is resposne from hi");
    }

    @GetMapping("/hi2")
    public Response method2() {
        return new Response("Hi this is resposne from hi2");
    }

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }

}
</code>```

答:
try to add this on server side near"Access-Control-Allow-Origin" setting：</p>

```<code>"Access-Control-Allow-Credentials: true"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am sending a request from angular to my server with header withCredentials as true and on server side i have only allowed request from origin http://0.0.0.0:4200 where my angular is running. Since my request contains authorizaion header it sends preflight request and it fails with below error message.

But if you will look at my response of preflight request there is no wildcard in the value of header "Access-Control-Allow-Origin".

Preflight response:

Method in angular :

const headers = new HttpHeaders(credentials ? {
      authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
  } : {});
  headers.set("Access-Control-Allow-Origin","http://localhost:4200")
  this.http.get('http://localhost:8080/user', {headers: headers , withCredentials: true }).subscribe(response => {..}

Can someone please explain me why i am getting this error and how to fix it?

SErver side code :-

CORSfilter.java

public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "authorization,withCredentials, content-type, xsrf-token, Cache-Control, Cookie");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

SpringSecurityConfig class

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
        http
        .httpBasic()
      .and()
        .authorizeRequests()
          .antMatchers("/").permitAll()
          .anyRequest().authenticated().and().csrf()
          .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());;
    }
}

Controller class

@RestController
@CrossOrigin
public class SecurityController {

    @GetMapping("/hi")
    public Response method() {
        return new Response("Hi this is resposne from hi");
    }

    @GetMapping("/hi2")
    public Response method2() {
        return new Response("Hi this is resposne from hi2");
    }

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }

}

Body:
try to add this on server side near"Access-Control-Allow-Origin" setting：

"Access-Control-Allow-Credentials: true"


问:
AWS Lambda function is returning square bracket "[ ]" result
I created a Lambda function with an API query string parameter. My Lambda function is created in NodeJS with MySQL query as shown below resulted to square bracket "[]"when invoked in the URL and Postman but the status is "Succeeded".

URL Return/Result:

```<code>[]
</code>```

Here's my Lambda function code:

```<code>var mysql = require('mysql');
var config = require('./config.json');
var pool  = mysql.createPool({
    host     : config.dbhost,
    user     : config.dbuser,
    password : config.dbpassword,
    database : config.dbname
  });

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function(err, connection) {
      // Use the connection
      connection.query('SELECT DISTINCT meta FROM item WHERE meta LIKE "+event.selected-meta"', function (error, results, fields) {
      // And done with the connection.
      connection.release();
      // Handle error after the release.
      if (error) callback(error) ;
      else callback(null, results);
    });
  });
};
</code>```

I suspect the culprit in my code is the callback method but it seems to me it is correct and could not find any other syntax to correct it.

Does anybody here familiar with AWS Lambda, NodeJS and API Gateway who could help me figure out where I was wrong?

UPDATE 1:

The above code returns "Succeeded" status but an empty array. I tried the same query in Workbench — I get the right results.

```<code>SELECT DISTINCT name FROM item WHERE meta LIKE 'tango';
</code>```

I can now confirmed that the below parameter is taken up as a variable rather than as parameter. So, I have to determine the right syntax for parameter in Lambda/NodeJS.

```<code>"+event.selected-meta"
</code>```

FINAL UPDATE

At last I got the answer! The right syntax would be as follows. The question mark (?) is the placeholder followed by an array as the second argument where we place the parameter and it solves my problem!

```<code>SELECT name FROM item WHERE meta LIKE ?', event['selected-meta']
</code>```

Hope others can learn from this!

答:
At last I got the answer! The right syntax would be as follows. The question mark (?) is the placeholder followed by an array as the second argument where we place the parameter and it solves my problem!

```<code>SELECT name FROM item WHERE meta LIKE ?', event['selected-meta']
</code>```

I am posting it here for others reference but I could not mark it as "ANSWERED". Somebody may want to check and mark it. Cheers!

Body:
I created a Lambda function with an API query string parameter. My Lambda function is created in NodeJS with MySQL query as shown below resulted to square bracket "[]"when invoked in the URL and Postman but the status is "Succeeded".

URL Return/Result:

[]

Here's my Lambda function code:

var mysql = require('mysql');
var config = require('./config.json');
var pool  = mysql.createPool({
    host     : config.dbhost,
    user     : config.dbuser,
    password : config.dbpassword,
    database : config.dbname
  });

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  pool.getConnection(function(err, connection) {
      // Use the connection
      connection.query('SELECT DISTINCT meta FROM item WHERE meta LIKE "+event.selected-meta"', function (error, results, fields) {
      // And done with the connection.
      connection.release();
      // Handle error after the release.
      if (error) callback(error) ;
      else callback(null, results);
    });
  });
};

I suspect the culprit in my code is the callback method but it seems to me it is correct and could not find any other syntax to correct it.

Does anybody here familiar with AWS Lambda, NodeJS and API Gateway who could help me figure out where I was wrong?

UPDATE 1:

The above code returns "Succeeded" status but an empty array. I tried the same query in Workbench — I get the right results.

SELECT DISTINCT name FROM item WHERE meta LIKE 'tango';

I can now confirmed that the below parameter is taken up as a variable rather than as parameter. So, I have to determine the right syntax for parameter in Lambda/NodeJS.

"+event.selected-meta"

FINAL UPDATE

At last I got the answer! The right syntax would be as follows. The question mark (?) is the placeholder followed by an array as the second argument where we place the parameter and it solves my problem!

SELECT name FROM item WHERE meta LIKE ?', event['selected-meta']

Hope others can learn from this!

Body:
At last I got the answer! The right syntax would be as follows. The question mark (?) is the placeholder followed by an array as the second argument where we place the parameter and it solves my problem!

SELECT name FROM item WHERE meta LIKE ?', event['selected-meta']

I am posting it here for others reference but I could not mark it as "ANSWERED". Somebody may want to check and mark it. Cheers!


问:
How to recursively get Excel files stored in a folder in dbfs using pyspark?
I have a path mounted in dbfs and I need to extract Excel files path from a given folder and the same folder contains Excel files or sub folder containing Excel files. Current code only gives Excel files in one folder and not in sub folders.</p>

```<code>files = dbutils.fs.ls('/raw/internal/srange/2018_11_30_00_22_11/')
for file in files:
  if file.path.endswith('xlsx'):
    path = '/dbfs' + file.path[5:]
    print(path)
</code>```

答:
This is what I recommend:</p>

```<code>for file1 in dbutils.fs.ls("dbfs:/raw/internal/srange/2018_11_30_00_22_11/"):
  if '.xlsx' in file1.name:
    print (file1.name)
  for file2 in dbutils.fs.ls("dbfs:/raw/internal/srange/2018_11_30_00_22_11/"+file1.name):
    if '.xlsx' in file2.name:
      print (file2.name)
    for file3 in dbutils.fs.ls("dbfs:/raw/internal/srange/2018_11_30_00_22_11/"+file1.name+file2.name):
      if '.xlsx' in file3.name:
        print (file3.name)
</code>```

Body:
I have a path mounted in dbfs and I need to extract Excel files path from a given folder and the same folder contains Excel files or sub folder containing Excel files. Current code only gives Excel files in one folder and not in sub folders.

files = dbutils.fs.ls('/raw/internal/srange/2018_11_30_00_22_11/')
for file in files:
  if file.path.endswith('xlsx'):
    path = '/dbfs' + file.path[5:]
    print(path)

Body:
This is what I recommend:

for file1 in dbutils.fs.ls("dbfs:/raw/internal/srange/2018_11_30_00_22_11/"):
  if '.xlsx' in file1.name:
    print (file1.name)
  for file2 in dbutils.fs.ls("dbfs:/raw/internal/srange/2018_11_30_00_22_11/"+file1.name):
    if '.xlsx' in file2.name:
      print (file2.name)
    for file3 in dbutils.fs.ls("dbfs:/raw/internal/srange/2018_11_30_00_22_11/"+file1.name+file2.name):
      if '.xlsx' in file3.name:
        print (file3.name)


问:
How to initialize the Shared Preferences values using an xml file for the first time in Android Studio
I need to initialize the Shared Preferences values using a .xml file only for the first time in Android Studio, I need these values to be read only the first time because then these values will be replaced according to the user's needs.

Here is my MainActivity:

```<code>public class MainActivity extends AppCompatActivity {

private SharedPreferences sharedpreferences;
private static final String mypreference = "mypref";
private EditText mpAddress;
private EditText mPort;
private String mconfig_IpAddress;
private String mconfig_Port;
private Button mInit;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    PreferenceManager.setDefaultValues(this, mypreference, Context.MODE_PRIVATE, R.xml.initial_setup, false);

    mpAddress = (EditText) findViewById(R.id.etx_ipaddress);
    mPort = (EditText) findViewById(R.id.etx_port);
    mInit = (Button) findViewById(R.id.bt_init);

    mInit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            leerConfigWiFiShareref();
            mpAddress.setText(mconfig_IpAddress);
            mPort.setText(mconfig_Port);
        }
    });

}

private void leerConfigWiFiShareref() {
    sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);

    if (sharedpreferences.contains("SP_ConfigIpAddress")) {
        mconfig_IpAddress = sharedpreferences.getString("SP_ConfigIpAddress", "");
    }
    if (sharedpreferences.contains("SP_ConfigPort")) {
        mconfig_Port = sharedpreferences.getString("SP_ConfigPort", "");
    }
  }
}
</code>```

And my .xml file initial_setu.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
    android:id="@+id/et1_ip_address"
    android:key="SP_ConfigIpAddress"
    android:defaultValue="192.168.4.1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="0123456789."
    android:inputType="number|numberDecimal"
    android:maxLines="1"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:textColorHighlight="#00ffffff"
    android:title="IP Address" />

<EditTextPreference
    android:id="@+id/et1_port"
    android:key="SP_ConfigPort"
    android:defaultValue="8888"
    android:maxLines="1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="0123456789."
    android:inputType="number|numberDecimal"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:textColorHighlight="#00ffffff"
    android:title="Port" />

  </PreferenceScreen>
</code>```

答:
You already put readAgain to false it means it only read the first time.

readAgain boolean: Whether to re-read the default values. If false, this method will set the default values only if this method has never been called in the past (or if the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true.

When you call this, it means you using default SharedPreference of your app.

```<code>PreferenceManager.setDefaultValues(this, R.xml.initial_setup, false);
PreferenceManager.getDefaultSharedPreferences(this) // you have to use this
</code>```

If you using the custom name you should try this

```<code>PreferenceManager.setDefaultValues(this, mypreference, Context.MODE_PRIVATE, R.xml.initial_setup, false);
</code>```

Body:
I need to initialize the Shared Preferences values using a .xml file only for the first time in Android Studio, I need these values to be read only the first time because then these values will be replaced according to the user's needs.

Here is my MainActivity:

public class MainActivity extends AppCompatActivity {

private SharedPreferences sharedpreferences;
private static final String mypreference = "mypref";
private EditText mpAddress;
private EditText mPort;
private String mconfig_IpAddress;
private String mconfig_Port;
private Button mInit;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    PreferenceManager.setDefaultValues(this, mypreference, Context.MODE_PRIVATE, R.xml.initial_setup, false);

    mpAddress = (EditText) findViewById(R.id.etx_ipaddress);
    mPort = (EditText) findViewById(R.id.etx_port);
    mInit = (Button) findViewById(R.id.bt_init);

    mInit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            leerConfigWiFiShareref();
            mpAddress.setText(mconfig_IpAddress);
            mPort.setText(mconfig_Port);
        }
    });

}

private void leerConfigWiFiShareref() {
    sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);

    if (sharedpreferences.contains("SP_ConfigIpAddress")) {
        mconfig_IpAddress = sharedpreferences.getString("SP_ConfigIpAddress", "");
    }
    if (sharedpreferences.contains("SP_ConfigPort")) {
        mconfig_Port = sharedpreferences.getString("SP_ConfigPort", "");
    }
  }
}

And my .xml file initial_setu.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
    android:id="@+id/et1_ip_address"
    android:key="SP_ConfigIpAddress"
    android:defaultValue="192.168.4.1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="0123456789."
    android:inputType="number|numberDecimal"
    android:maxLines="1"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:textColorHighlight="#00ffffff"
    android:title="IP Address" />

<EditTextPreference
    android:id="@+id/et1_port"
    android:key="SP_ConfigPort"
    android:defaultValue="8888"
    android:maxLines="1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="0123456789."
    android:inputType="number|numberDecimal"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:textColorHighlight="#00ffffff"
    android:title="Port" />

  </PreferenceScreen>

Body:
You already put readAgain to false it means it only read the first time.

readAgain boolean: Whether to re-read the default values. If false, this method will set the default values only if this method has never been called in the past (or if the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true.

When you call this, it means you using default SharedPreference of your app.

PreferenceManager.setDefaultValues(this, R.xml.initial_setup, false);
PreferenceManager.getDefaultSharedPreferences(this) // you have to use this

If you using the custom name you should try this

PreferenceManager.setDefaultValues(this, mypreference, Context.MODE_PRIVATE, R.xml.initial_setup, false);


问:
Whats possible in a for loop
So today I went to an interview and one of the questions was the following (C# context).

```<code>//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}
</code>```

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

答:
output is:
0
9
8
7
6

Almost C syntax based languages implement this functionality.

Where does this syntax stem from c.

One part, two part, three part, all may disappear.do not have any part, loop can work right.

It is a bad practice.

I do not know.

ContentLicense: CC BY-SA 3.0

Title: Whats possible in a for loop

Body:
So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?


问:
Plotting frequency distribution through time (stacked)
I am trying to plot how many people there were in a shop by date.
To do this, first I grouped by date people's names:

```<code>df.groupby(['Date', 'Name']).size()
</code>```

The result is shown below

```<code>    Date        Name

2020-01-25  John       1
2020-01-26  John       1
2020-01-27  John       1
2020-01-28  Luca       1
            John       1
                 ..
2020-03-30  John       1
2020-03-31  Martyn     2
            Christine  1
            Mary       1
            John       1
</code>```

Now, I would like to see how many people there were each day (1 on 25/01, 1 on 26/01, 1 on 27/01, 3 on 28/01, and so on), and who.
So I would need a histogram (bar plot) that can help me to visualise these results. In order to see the frequency of same people on the same day (like Martyn, that went twice), I would need to consider a stacked plot (I think).
Since the number of names is around 1000, could you please tell me if it would be possible to have a legend/labels that can be readable?

Could you please show me how to do this? Plots are my weakness (unfortunately).

答:
I like to use a combination of seaborn and maplotlib. Seaborn has very simple, out-of-the-box graphs for you to use, then you can customise them with matplotlib.</p>

```<code>import seaborn as sns
import matplotlib.pyplot as plt

#create blank figure instance using matplotlib syntax, for easier customisation
fig,ax1 = plt.subplots(figsize=(8,5))

#manipulate your data
dfg = df.groupby(['Date', 'Name']).size().reset_index()

#call the 'barplot' from seaborn, which is what you're after. You could even use
#'countplot' and skip the groupby step in your data.
sns.barplot(data=dfg,x='Date',y='Size',ax=ax1)

#customise your plot with matplotlib
ax1.set_title('Customers attending shops')
</code>```

Body:
I am trying to plot how many people there were in a shop by date.
To do this, first I grouped by date people's names:

df.groupby(['Date', 'Name']).size()

The result is shown below

    Date        Name

2020-01-25  John       1
2020-01-26  John       1
2020-01-27  John       1
2020-01-28  Luca       1
            John       1
                 ..
2020-03-30  John       1
2020-03-31  Martyn     2
            Christine  1
            Mary       1
            John       1

Now, I would like to see how many people there were each day (1 on 25/01, 1 on 26/01, 1 on 27/01, 3 on 28/01, and so on), and who.
So I would need a histogram (bar plot) that can help me to visualise these results. In order to see the frequency of same people on the same day (like Martyn, that went twice), I would need to consider a stacked plot (I think).
Since the number of names is around 1000, could you please tell me if it would be possible to have a legend/labels that can be readable?

Could you please show me how to do this? Plots are my weakness (unfortunately).

Body:
I like to use a combination of seaborn and maplotlib. Seaborn has very simple, out-of-the-box graphs for you to use, then you can customise them with matplotlib.

import seaborn as sns
import matplotlib.pyplot as plt

#create blank figure instance using matplotlib syntax, for easier customisation
fig,ax1 = plt.subplots(figsize=(8,5))

#manipulate your data
dfg = df.groupby(['Date', 'Name']).size().reset_index()

#call the 'barplot' from seaborn, which is what you're after. You could even use
#'countplot' and skip the groupby step in your data.
sns.barplot(data=dfg,x='Date',y='Size',ax=ax1)

#customise your plot with matplotlib
ax1.set_title('Customers attending shops')


问:
Is there a way to write a Spark dataframe to a .dat file?
I tried this, but it didn't work. From my understanding, Spark does not support the .dat file format. I do not want to write the file as a .csv or .json, then convert via a shell script later.

```<code>a.write.format("dat").save(outputPath)
</code>```

答:
Spark format function does not accepts "dat" as argument. You can have much more information in documentation: https://spark.apache.org/docs/latest/sql-data-sources-load-save-functions.html

I'm sorry but easiest thing you can do is creating csv and converting it to dat later.

Body:
I tried this, but it didn't work. From my understanding, Spark does not support the .dat file format. I do not want to write the file as a .csv or .json, then convert via a shell script later.

a.write.format("dat").save(outputPath)


问:
How do I make fonts of different sizes vertically centered in html spans?
I'm making a pitch controller:

```<code><div id="pitchWrapper">
  <span id="pitchButtons">-</span>
  <span id="pitchValue">0</span>
  <span id="pitchButtons">+</span>
</div>
</code>```

I want the minus, plus, and pitch value all to be vertically centered. I want the plus and minus to be a bigger font-size than the pitch value.

It works reasonably well when I set the font sizes to all be the same...

...but when I try to make the pitch buttons bigger, they align below center:

Here's my css:

```<code>#pitchWrapper {
  display: flex;
  align-items: center;
  vertical-align: middle;
}

#pitchValue {
  font-size: 200%;
}

#pitchButtons {
  font-size: 300%;
}
</code>```

How can I increase the font size of the pitch buttons while keeping everything vertically centered please?

Thank you.

答:
first, you cannot use the id selector and Select Plus and minus together. id must be unique. And why not use the Font awesome icon?

#pitchWrapper {
  display: flex;
  align-items: center;
}

.pitchValue {
  font-size: 200%;
}

.pitchButtons {
  font-size: 300%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <script src="https://kit.fontawesome.com/dc0c634418.js" crossorigin="anonymous"></script>

<div id="pitchWrapper">
  <span class="pitchButtons">
      <i class="fas fa-minus"></i>
    </span>
  <span class="pitchValue">0</span>
  <span class="pitchButtons">
      <i class="fas fa-plus"></i>
    </span>
</div></code>```

Body:
I'm making a pitch controller:

  -
  0
  +

I want the minus, plus, and pitch value all to be vertically centered. I want the plus and minus to be a bigger font-size than the pitch value.

It works reasonably well when I set the font sizes to all be the same...

...but when I try to make the pitch buttons bigger, they align below center:

Here's my css:

#pitchWrapper {
  display: flex;
  align-items: center;
  vertical-align: middle;
}

#pitchValue {
  font-size: 200%;
}

#pitchButtons {
  font-size: 300%;
}

How can I increase the font size of the pitch buttons while keeping everything vertically centered please?

Thank you.

Body:
first, you cannot use the id selector and Select Plus and minus together. id must be unique. And why not use the Font awesome icon?

#pitchWrapper {
  display: flex;
  align-items: center;
}

.pitchValue {
  font-size: 200%;
}

.pitchButtons {
  font-size: 300%;
}

  <script src="https://kit.fontawesome.com/dc0c634418.js" crossorigin="anonymous"></script>

<div id="pitchWrapper">
  <span class="pitchButtons">
      <i class="fas fa-minus"></i>
    </span>
  <span class="pitchValue">0</span>
  <span class="pitchButtons">
      <i class="fas fa-plus"></i>
    </span>
</div>


问:
Find number of close loops in Binary Edge Image
I have a binary image with the number of close loops and free curves like shown in image..

My approach so far- (python code):

Skeletonize the image to get edge of 1 pixel

Use label/bwlabel to get individual curve/edge

Applied DFS to get the edge which is not close

Apply DFS to get close edge..but not working correctly..

Expected output -

Number of close loops =6, the sum of the pixels along the loop or all (x,y) points along the edge of the close curve as highlighted in RED

Expected Output-

答:
Here is one way to do that in Python/OpenCV.

Read the input as grayscale

Threshold to binary

Get the contours and hierarchy

Loop over the contours and corresponding hierarchy and discard contours with no parent (the external ones) and save and count the contours with no children (the innermost ones)

Draw the contours on the input

Save the results

Input:

```<code>import cv2
import numpy as np

# read image as grayscale
img = cv2.imread('loops.png', cv2.IMREAD_GRAYSCALE)
hh, ww = img.shape

# blacken right columns that are white
img[0:hh, ww-3:ww] = 0

# threshold
thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)[1]

# get contours
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = contours[1] if len(contours) == 2 else contours[2]
contours = contours[0] if len(contours) == 2 else contours[1]

# get the actual inner list of hierarchy descriptions
hierarchy = hierarchy[0]

# count inner contours
count = 0
result = img.copy()
result = cv2.merge([result,result,result])
for component in zip(contours, hierarchy):
    cntr = component[0]
    hier = component[1]
    # discard outermost no parent contours and keep innermost no child contours
    # hier = indices for next, previous, child, parent
    # no parent or no child indicated by negative values
    if (hier[3] > -1) & (hier[2] < 0):
        count = count + 1
        cv2.drawContours(result, [cntr], 0, (0,0,255), 2)

# print count
print("count:",count)

# save result
cv2.imwrite("loops_result.png",result)

# show result
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Resulting contours:

Count:

```<code>count: 6
</code>```

Body:
Here is one way to do that in Python/OpenCV.

Read the input as grayscale

Threshold to binary

Get the contours and hierarchy

Loop over the contours and corresponding hierarchy and discard contours with no parent (the external ones) and save and count the contours with no children (the innermost ones)

Draw the contours on the input

Save the results

Input:

import cv2
import numpy as np

# read image as grayscale
img = cv2.imread('loops.png', cv2.IMREAD_GRAYSCALE)
hh, ww = img.shape

# blacken right columns that are white
img[0:hh, ww-3:ww] = 0

# threshold
thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)[1]

# get contours
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = contours[1] if len(contours) == 2 else contours[2]
contours = contours[0] if len(contours) == 2 else contours[1]

# get the actual inner list of hierarchy descriptions
hierarchy = hierarchy[0]

# count inner contours
count = 0
result = img.copy()
result = cv2.merge([result,result,result])
for component in zip(contours, hierarchy):
    cntr = component[0]
    hier = component[1]
    # discard outermost no parent contours and keep innermost no child contours
    # hier = indices for next, previous, child, parent
    # no parent or no child indicated by negative values
    if (hier[3] > -1) & (hier[2] < 0):
        count = count + 1
        cv2.drawContours(result, [cntr], 0, (0,0,255), 2)

# print count
print("count:",count)

# save result
cv2.imwrite("loops_result.png",result)

# show result
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Resulting contours:

Count:

count: 6


问:
Using Java Stream API, finding highest value of variable, with the stream of the changes made to the variable

Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

```<code>enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}
</code>```

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

```<code>// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0
</code>```

Bob's highest balance is 1700.

答:
A stream would not help here. Use a list and a for-loop:

```<code>List<Transaction> transactions = ...;

int balance = 0;
int max = 0;
for (Transaction transaction : transactions) {
    balance += (transaction.getAction() == TransactionAction.DEPOSIT ? 1 : -1)
                * transaction.getAmount();
    max = Math.max(max, balance);
}
</code>```

The problem is that you need to keep track of some state while processing transactions, and you wouldn't be able to do this with streams without introducing complicated or mutable data structures that would make this code bug-prone.

Body:
Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0

Bob's highest balance is 1700.

Body:
A stream would not help here. Use a list and a for-loop:

List<Transaction> transactions = ...;

int balance = 0;
int max = 0;
for (Transaction transaction : transactions) {
    balance += (transaction.getAction() == TransactionAction.DEPOSIT ? 1 : -1)
                * transaction.getAmount();
    max = Math.max(max, balance);
}

The problem is that you need to keep track of some state while processing transactions, and you wouldn't be able to do this with streams without introducing complicated or mutable data structures that would make this code bug-prone.


问:
Problem with jQuery mouseleave firing when container has select box
I have a two containers -- one is nested inside of another.  When I hover over the parent, I want the child container to appear. When I mouseout, I want the child container to fadeout. The problem I'm having is the child container has a form that contains a "select box". When the user selects the select box -- the mouseleave event is accidentally fired.

How can I stop the select box from tripping the mouseleave event?

You can see my working code here: http://jsfiddle.net/rsturim/9TZyh/3/

Here's a summary of my script:

```<code>$('#parent-container').live("mouseenter", function () {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave", function (e) {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().hide();
});
</code>```

edit: appears fine in WebKit-based browsers. Fails in Firefox and IE7-IE9.

答:
This partly solves the problem.
Unbind the mouseleave event when the select box gains focus and bind again when it loses focus.

http://jsfiddle.net/9TZyh/5/

```<code>$('#parent-container').live("mouseenter", function() {
    var $this = $(this);
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave",focusOut);
$("#select-grind-type").live("focus",function(){
    $('#parent-container').die("mouseleave");
});
$("#select-grind-type").live("focusout change",function(){
    $('#parent-container').live("mouseleave",focusOut);
});
function focusOut(e) {
    var $this = $(this),
        $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().hide();
}
</code>```

Body:
I have a two containers -- one is nested inside of another.  When I hover over the parent, I want the child container to appear. When I mouseout, I want the child container to fadeout. The problem I'm having is the child container has a form that contains a "select box". When the user selects the select box -- the mouseleave event is accidentally fired.

How can I stop the select box from tripping the mouseleave event?

You can see my working code here: http://jsfiddle.net/rsturim/9TZyh/3/

Here's a summary of my script:

$('#parent-container').live("mouseenter", function () {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave", function (e) {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().hide();
});

edit: appears fine in WebKit-based browsers. Fails in Firefox and IE7-IE9.

Body:
This partly solves the problem.
Unbind the mouseleave event when the select box gains focus and bind again when it loses focus.

http://jsfiddle.net/9TZyh/5/

$('#parent-container').live("mouseenter", function() {
    var $this = $(this);
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave",focusOut);
$("#select-grind-type").live("focus",function(){
    $('#parent-container').die("mouseleave");
});
$("#select-grind-type").live("focusout change",function(){
    $('#parent-container').live("mouseleave",focusOut);
});
function focusOut(e) {
    var $this = $(this),
        $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().hide();
}


问:
Assigning values to an array of ints through a function in C
I am making a weird unpractical program that calls four functions.

First function reads 30 integers to an array;

Second does the same but to another array;

Third should make another array with 60 elements, half being the elements of the first array, other half being the elements of the second array;

Fourth will show the entire array to the user.

I'm stuck on my third function. I am not finding anything explaining how to change the values of an array of integers through a function.

```<code>#include <stdio.h>

void array1(int *a1);
void array2(int *a2);
void mash(int *a1, int *a2, int *a);
void exhibit(int *a);

int main()
{
    int a1[30];
    array1(a1);

    int a2[30];
    array2(a2);

    int a[60];
    mash(a1, a2, a);

    exhibit(a);

    return 0;
}

void array1(int *a1)
{
    int temp[30];
    for (int i = 0; i < 30; i++)
    {
        scanf("%i", a1 + i);
    }
}

void array2(int *a2)
{
    for (int i = 0; i < 30; i++)
    {
        scanf("%i", a2 + i);
    }
}

void mash(int *a1, int *a2, int *a)
{
    for (int i = 0; i < 30; i++)
    {
        a + i = a1 + i;
    }
}

void exhibit(int *a)
{

}
</code>```

I thought I should be able to access each element by adding 1 to the pointer as I did to get input on my earlier functions.

答:
To access an element at index location of an array, you are doing:

```<code>*(array + index)
</code>```

this is equivalent to

```<code>array[index]
</code>```

this also looks more clear and easy to understand.

For getting input elements to array, you are doing

```<code>scanf("%i", a1 + i);
</code>```

you can also use &a1[i] because &a1[i] is equivalent to a1 + i -

```<code>&a1[i] --> &(*(a1 + i) --> a1 + i
</code>```

Third should make another array with 60 elements, half being the elements of the first array, other half being the elements of the second array

Your mash() should be like this:

```<code>void mash(int *a1, int *a2, int *a)
{
    for (int i = 0; i < 30; i++)
    {
        a[i] = a1[i];
        a[i + 30] = a2[i];
    }
}
</code>```

Instead of using numbers like 30 in function, better to pass size of array along with array that you want to iterate in the function.

Body:
I am making a weird unpractical program that calls four functions.

First function reads 30 integers to an array;

Second does the same but to another array;

Third should make another array with 60 elements, half being the elements of the first array, other half being the elements of the second array;

Fourth will show the entire array to the user.

I'm stuck on my third function. I am not finding anything explaining how to change the values of an array of integers through a function.

#include <stdio.h>

void array1(int *a1);
void array2(int *a2);
void mash(int *a1, int *a2, int *a);
void exhibit(int *a);

int main()
{
    int a1[30];
    array1(a1);

    int a2[30];
    array2(a2);

    int a[60];
    mash(a1, a2, a);

    exhibit(a);

    return 0;
}

void array1(int *a1)
{
    int temp[30];
    for (int i = 0; i < 30; i++)
    {
        scanf("%i", a1 + i);
    }
}

void array2(int *a2)
{
    for (int i = 0; i < 30; i++)
    {
        scanf("%i", a2 + i);
    }
}

void mash(int *a1, int *a2, int *a)
{
    for (int i = 0; i < 30; i++)
    {
        a + i = a1 + i;
    }
}

void exhibit(int *a)
{

}

I thought I should be able to access each element by adding 1 to the pointer as I did to get input on my earlier functions.

Body:
To access an element at index location of an array, you are doing:

*(array + index)

this is equivalent to

array[index]

this also looks more clear and easy to understand.

For getting input elements to array, you are doing

scanf("%i", a1 + i);

you can also use &a1[i] because &a1[i] is equivalent to a1 + i -

&a1[i] --> &(*(a1 + i) --> a1 + i

Third should make another array with 60 elements, half being the elements of the first array, other half being the elements of the second array

Your mash() should be like this:

void mash(int *a1, int *a2, int *a)
{
    for (int i = 0; i < 30; i++)
    {
        a[i] = a1[i];
        a[i + 30] = a2[i];
    }
}

Instead of using numbers like 30 in function, better to pass size of array along with array that you want to iterate in the function.


答:
```<code>void mash(int *a1, int *a2, int *a)
{
  for (int i = 0; i < 30; i++)
  {
    a[i]=a1[i];
    a[30+i]=a2[i];
  }
}
</code>```

since you already know the array a have 60 elements and a1 a2 have 30 each , you just need to insert from the start with a1 and from the middle with a2

Title: Assigning values to an array of ints through a function in C

Body:
void mash(int *a1, int *a2, int *a)
{
  for (int i = 0; i < 30; i++)
  {
    a[i]=a1[i];
    a[30+i]=a2[i];
  }
}

since you already know the array a have 60 elements and a1 a2 have 30 each , you just need to insert from the start with a1 and from the middle with a2


问:
Making a Python multiprocessing Pool awaitable
I have an application that needs to perform some processor-intensive work based on a websocket stream. I want to parallelize the CPU-intensive bits with multiprocessing, but I still need the async interface to handle the streaming parts of the application. To solve this problem I was hoping to make an awaitable version of multiprocessing.AsyncResult (the result of a multiprocessing.pool.Pool.submit_async action). However, I've run into some strange behavior.

My new awaitable pool result (which is a subclass of asyncio.Future) works fine as long as the pool result comes back before I start awaiting it. However, if I try to await the pool result before it has come back, then the program appears to stall indefinitely on the await statement.

I've checked the async iterator results with next(future.async()) and the iterator returns the future instance itself before the pool processing completes and raises a StopIterationError after, as I'd expect.

Code is below.

```<code>import multiprocessing
import multiprocessing.pool
import asyncio
import time

class Awaitable_Multiprocessing_Pool(multiprocessing.pool.Pool):
    def __init__(self, *args, **kwargs):
        multiprocessing.pool.Pool.__init__(self, *args, **kwargs)

    def apply_awaitably(self, func, args = list(), kwargs = dict()):
        return Awaitable_Multiprocessing_Pool_Result(
                self,
                func,
                args,
                kwargs)

class Awaitable_Multiprocessing_Pool_Result(asyncio.Future):
    def __init__(self, pool, func, args = list(), kwargs = dict()):
        asyncio.Future.__init__(self)
        self.pool_result = pool.apply_async(
                func,
                args,
                kwargs,
                self.set_result,
                self.set_exception)

    def result(self):
        return self.pool_result.get()

    def done(self):
        return self.pool_result.ready()

def dummy_processing_fun():
    import time
    print('start processing')
    time.sleep(4)
    print('finished processing')
    return 'result'

if __name__ == '__main__':
    async def main():
        ah = Async_Handler(1)
        pool = Awaitable_Multiprocessing_Pool(2)
        while True:
            future = pool.apply_awaitably(dummy_processing_fun, [])
            # print(next(future.__await__())) # would show same as print(future)
            # print(await future) # would stall indefinitely because pool result isn't in
            time.sleep(10) # NOTE: you may have to make this longer to account for pool startup time on the first iteration
            # print(next(future.__await__())) # would raise StopIteration
            print(await future) # prints 'result'
    asyncio.run(main())
</code>```

Am I missing something obvious here? I think I have all the essential elements of an awaitable working correctly in part because of the fact that I can await successfully in some circumstances. Anyone have any insight?

答:
I am not sure why you make it so complex... How about the following code?</p>

```<code>from concurrent.futures import ProcessPoolExecutor
import asyncio
import time

def dummy_processing_fun():
    import time
    print('start processing')
    time.sleep(4)
    print('finished processing')
    return 'result'

if __name__ == '__main__':
    async def main():
        pool = ProcessPoolExecutor(2)
        while True:
            future = pool.submit(dummy_processing_fun)
            future = asyncio.wrap_future(future)
            # print(next(future.__await__())) # would show same as print(future)
            # print(await future) # would stall indefinitely because pool result isn't in
            # time.sleep(5)
            # print(next(future.__await__())) # would raise StopIteration
            print(await future) # prints 'result'
    asyncio.run(main())
</code>```

Body:
I have an application that needs to perform some processor-intensive work based on a websocket stream. I want to parallelize the CPU-intensive bits with multiprocessing, but I still need the async interface to handle the streaming parts of the application. To solve this problem I was hoping to make an awaitable version of multiprocessing.AsyncResult (the result of a multiprocessing.pool.Pool.submit_async action). However, I've run into some strange behavior.

My new awaitable pool result (which is a subclass of asyncio.Future) works fine as long as the pool result comes back before I start awaiting it. However, if I try to await the pool result before it has come back, then the program appears to stall indefinitely on the await statement.

I've checked the async iterator results with next(future.async()) and the iterator returns the future instance itself before the pool processing completes and raises a StopIterationError after, as I'd expect.

Code is below.

import multiprocessing
import multiprocessing.pool
import asyncio
import time

class Awaitable_Multiprocessing_Pool(multiprocessing.pool.Pool):
    def __init__(self, *args, **kwargs):
        multiprocessing.pool.Pool.__init__(self, *args, **kwargs)

    def apply_awaitably(self, func, args = list(), kwargs = dict()):
        return Awaitable_Multiprocessing_Pool_Result(
                self,
                func,
                args,
                kwargs)

class Awaitable_Multiprocessing_Pool_Result(asyncio.Future):
    def __init__(self, pool, func, args = list(), kwargs = dict()):
        asyncio.Future.__init__(self)
        self.pool_result = pool.apply_async(
                func,
                args,
                kwargs,
                self.set_result,
                self.set_exception)

    def result(self):
        return self.pool_result.get()

    def done(self):
        return self.pool_result.ready()

def dummy_processing_fun():
    import time
    print('start processing')
    time.sleep(4)
    print('finished processing')
    return 'result'

if __name__ == '__main__':
    async def main():
        ah = Async_Handler(1)
        pool = Awaitable_Multiprocessing_Pool(2)
        while True:
            future = pool.apply_awaitably(dummy_processing_fun, [])
            # print(next(future.__await__())) # would show same as print(future)
            # print(await future) # would stall indefinitely because pool result isn't in
            time.sleep(10) # NOTE: you may have to make this longer to account for pool startup time on the first iteration
            # print(next(future.__await__())) # would raise StopIteration
            print(await future) # prints 'result'
    asyncio.run(main())

Am I missing something obvious here? I think I have all the essential elements of an awaitable working correctly in part because of the fact that I can await successfully in some circumstances. Anyone have any insight?

Body:
I am not sure why you make it so complex... How about the following code?

from concurrent.futures import ProcessPoolExecutor
import asyncio
import time

def dummy_processing_fun():
    import time
    print('start processing')
    time.sleep(4)
    print('finished processing')
    return 'result'

if __name__ == '__main__':
    async def main():
        pool = ProcessPoolExecutor(2)
        while True:
            future = pool.submit(dummy_processing_fun)
            future = asyncio.wrap_future(future)
            # print(next(future.__await__())) # would show same as print(future)
            # print(await future) # would stall indefinitely because pool result isn't in
            # time.sleep(5)
            # print(next(future.__await__())) # would raise StopIteration
            print(await future) # prints 'result'
    asyncio.run(main())


问:
Strange black blocks appearing in Chrome
For some reason, black boxes are displaying in random spaces in Chrome (latest build).

Some of these boxes are appearing outside of the main container, whereas some are appearing inline, covering content blocks. They appear randomly, usually after scrolling, and will often disappear when opening the inspector, hovering over elements, or scrolling down and back up.

For reference, there are some animations, box-shadows (which have been disabled with no luck), linear gradients, and position: fixed elements on the page, although this is not an issue with browsers other than Chrome.

This has been widely reported in user testing, although I have not been able to conjure up a fix. I am not sure if it is a CPU or graphics card issue, as the site is relatively lightweight and I am browsing with a new laptop with 16gb ram. My old Mac Mini, with 4gb of ram, does not produce this issue.

Any pointers would be most appreciated.

答:
I think is related to the GPU I had the same issue on my website. And it stopped happening when I turned on the Metal Rendering flag.

My website renders back bgs randomly while scrolling. It is really heavy on videos and animations and looks like chrome has so little GPU available that graphic intensive website doesn't work correctly on blink. I noticed that when chrome used webkit those issues didn't happen.

I this is a blink render issue.


问:
how to kill a Genymotion VM via command prompt?
The command

player --vm-name VM_NAME

is for launching a Genymotion VM and

What is the command for kill a Genymotion VM?

答:
If you want to DISCARD the state of VirtualBox Machine directly, you can type in terminal:

```<code>vboxmanage discardstate 'My Genymotion name machine'
</code>```

Body:
If you want to DISCARD the state of VirtualBox Machine directly, you can type in terminal:

vboxmanage discardstate 'My Genymotion name machine'


问:
JUnit testing with a call to another class
I am currently trying to create a JUnit Test with a call to another class. I have worked every which way I know how and I can't seem to get it right. The GetHistory test is the one that is causing all my headaches. Any help or tips would be great!

package medical.com.medicalApplication.model;
/**
 *
 *
 * This class represents a medical record model in the system
 *
 */
public class MedicalRecord {

    private Patient patient;
    private PatientHistory history;

    public MedicalRecord(Patient patient) {
        super();
        this.patient = patient;
        this.history = new PatientHistory();
    }

    public Patient getPatient() {
        return patient;
    }

    public PatientHistory getHistory() {
        return history;
    }
}
```

<p>And this is my current code:</p>

<pre class="lang-java prettyprint-override"><code>package medical.com.medicalApplication.model;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import medical.com.medicalApplication.model.PatientHistory;

public class MedicalRecordTest {

    @Test
    public void testGetPatient() {
        String patient = "Perez";
        Patient test = new Patient(patient, patient);
        assertTrue(test.getName().equals(patient));
    }

    @Test
    public void testGetHistory() {
        String history = "Diabetic";
        PatientHistory test = new PatientHistory();
        assertTrue(test.getHistory.equals("Diabetic"));
    }
}
</code>```

答:
You haven't given all the other classes here. Also please format your code so your classes are show correctly.

Without the actual files, my best guess is  that these should return the instance of the class.

```<code>public Patient getPatient() {
    return this.patient;
}

public PatientHistory getHistory() {
    return this.history;
}
</code>```

Additionally, you're testing wrong.

Your test should in this case should be using assertEquals:

```<code>assertEquals(patient.getFirstName(), medicalRecord.getPatient().getFirstName());
</code>```

if you use assertTrue your error message will not be helpful. It will be:

```<code>expected false was true
</code>```

if you use assertEquals your error message will be much more helpful. It will be

```<code>expected "perez" but was "abc"
</code>```

Body:
I am currently trying to create a JUnit Test with a call to another class. I have worked every which way I know how and I can't seem to get it right. The GetHistory test is the one that is causing all my headaches. Any help or tips would be great!

package medical.com.medicalApplication.model;
/**
 *
 *
 * This class represents a medical record model in the system
 *
 */
public class MedicalRecord {

    private Patient patient;
    private PatientHistory history;

    public MedicalRecord(Patient patient) {
        super();
        this.patient = patient;
        this.history = new PatientHistory();
    }

    public Patient getPatient() {
        return patient;
    }

    public PatientHistory getHistory() {
        return history;
    }
}

And this is my current code:

package medical.com.medicalApplication.model;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import medical.com.medicalApplication.model.PatientHistory;

public class MedicalRecordTest {

    @Test
    public void testGetPatient() {
        String patient = "Perez";
        Patient test = new Patient(patient, patient);
        assertTrue(test.getName().equals(patient));
    }

    @Test
    public void testGetHistory() {
        String history = "Diabetic";
        PatientHistory test = new PatientHistory();
        assertTrue(test.getHistory.equals("Diabetic"));
    }
}

Body:
You haven't given all the other classes here. Also please format your code so your classes are show correctly.

Without the actual files, my best guess is  that these should return the instance of the class.

public Patient getPatient() {
    return this.patient;
}

public PatientHistory getHistory() {
    return this.history;
}

Additionally, you're testing wrong.

Your test should in this case should be using assertEquals:

assertEquals(patient.getFirstName(), medicalRecord.getPatient().getFirstName());

if you use assertTrue your error message will not be helpful. It will be:

expected false was true

if you use assertEquals your error message will be much more helpful. It will be

expected "perez" but was "abc"


问:
How can I implement a CountedSet (NSCountedSet) in Swift?
Create a generic CountedSet struct that is constrained to Hashable elements. A counted set is an unordered collection of unique elements that may appear more than once in the collection. Use a private dictionary as your backing storage for set members and their counts.

```<code>struct CountedSet<Element> {
    private(set) var elements: [Element]

    mutating func insert(_ element: Element) {
        elements.append(element)
    }

    mutating func remove() -> Element? {
        guard elements.isEmpty == false else { return nil}
        return elements.removeFirst()

    }

    subscript(_ member: Element) -> Int {
        return 0
    }
}
</code>```

I don't understand what the real objective is here. The instructions are very confusing at least to me.

答:
1) Make your generic struct element conform to Hashable, this is necessary because the dictionary keys are required to conform to Hashable.

```<code>struct CountedSet<Element: Hashable>
</code>```

2) The backing storage you have used is an ordered array, not a dictionary and you need to initialize it with an empty one.

```<code>private(set) var elements: [Element: Int] = [:]
</code>```

3) Your subscript method you need to return the count for the counted set member or zero if it is nil.

```<code>return elements[member] ?? 0
</code>```

4) Your Insert and Remove methods need to first check the count of a member in the backing dictionary before adding or removing an element from it.

So your CountedSet should look like this:

```<code>struct CountedSet<Element: Hashable> {
    private(set) var elements: [Element: Int] = [:]
    mutating func insert(_ member: Element) {
        elements[member, default: 0] += 1
    }
    mutating func remove(_ member: Element) -> Element? {
        guard var count = elements[member], count > 0 else { return nil }
        count -= 1
        elements[member] = count == 0 ? nil : count
        return member
    }
    subscript(_ member: Element) -> Int {
        elements[member] ?? 0
    }
}
</code>```

```<code>var countedSet = CountedSet<Int>()
countedSet.insert(3)
countedSet.insert(3)
countedSet.insert(4)
countedSet.elements  // [4: 1, 3: 2]
countedSet.remove(4)
countedSet.elements  // [3: 2]
countedSet.remove(4) // nil
</code>```

Expanding on that you can also make your CountedSet conform to ExpressibleByArrayLiteral to allow you to initialize your CountedSet with an array and CustomStringConvertible to allow you to print its elements:

```<code>extension CountedSet: ExpressibleByArrayLiteral, CustomStringConvertible {

    typealias ArrayLiteralElement = Element
    init<S: Sequence>(_ sequence: S) where S.Element == Element {
        self.elements = sequence.reduce(into: [:]) { $0[$1, default: 0] += 1 }
    }
    init(arrayLiteral elements: Element...)  { self.init(elements) }
    var description: String { .init(describing: elements) }
}
</code>```

```<code>var countedSet: CountedSet = [1,2,2,3,3,3,4,4,5,5,5]
print(countedSet) // "[5: 3, 2: 2, 3: 3, 4: 2, 1: 1]\n"
</code>```

Body:
Create a generic CountedSet struct that is constrained to Hashable elements. A counted set is an unordered collection of unique elements that may appear more than once in the collection. Use a private dictionary as your backing storage for set members and their counts.

struct CountedSet<Element> {
    private(set) var elements: [Element]

    mutating func insert(_ element: Element) {
        elements.append(element)
    }

    mutating func remove() -> Element? {
        guard elements.isEmpty == false else { return nil}
        return elements.removeFirst()

    }

    subscript(_ member: Element) -> Int {
        return 0
    }
}

I don't understand what the real objective is here. The instructions are very confusing at least to me.

Body:
1) Make your generic struct element conform to Hashable, this is necessary because the dictionary keys are required to conform to Hashable.

struct CountedSet<Element: Hashable>

2) The backing storage you have used is an ordered array, not a dictionary and you need to initialize it with an empty one.

private(set) var elements: [Element: Int] = [:]

3) Your subscript method you need to return the count for the counted set member or zero if it is nil.

return elements[member] ?? 0

4) Your Insert and Remove methods need to first check the count of a member in the backing dictionary before adding or removing an element from it.

So your CountedSet should look like this:

struct CountedSet<Element: Hashable> {
    private(set) var elements: [Element: Int] = [:]
    mutating func insert(_ member: Element) {
        elements[member, default: 0] += 1
    }
    mutating func remove(_ member: Element) -> Element? {
        guard var count = elements[member], count > 0 else { return nil }
        count -= 1
        elements[member] = count == 0 ? nil : count
        return member
    }
    subscript(_ member: Element) -> Int {
        elements[member] ?? 0
    }
}

var countedSet = CountedSet<Int>()
countedSet.insert(3)
countedSet.insert(3)
countedSet.insert(4)
countedSet.elements  // [4: 1, 3: 2]
countedSet.remove(4)
countedSet.elements  // [3: 2]
countedSet.remove(4) // nil

Expanding on that you can also make your CountedSet conform to ExpressibleByArrayLiteral to allow you to initialize your CountedSet with an array and CustomStringConvertible to allow you to print its elements:

extension CountedSet: ExpressibleByArrayLiteral, CustomStringConvertible {

    typealias ArrayLiteralElement = Element
    init<S: Sequence>(_ sequence: S) where S.Element == Element {
        self.elements = sequence.reduce(into: [:]) { $0[$1, default: 0] += 1 }
    }
    init(arrayLiteral elements: Element...)  { self.init(elements) }
    var description: String { .init(describing: elements) }
}

var countedSet: CountedSet = [1,2,2,3,3,3,4,4,5,5,5]
print(countedSet) // "[5: 3, 2: 2, 3: 3, 4: 2, 1: 1]\n"


问:
pushing an object to an array in state React ERROR(objects are not valid...)
Im new to react,how can i add an object to an array in a state properly, I am receiving an error :"Error: Objects are not valid as a React child (found: object with keys {product}). If you meant to render a collection of children, use an array instead." What can i do is to push the object into list every time i click the button?

```<code>import React, { useContext, useState } from 'react'
import {SnacksContext} from './Snacks'
import AddtoCart from './AddToCart'
const SnackItem=()=>{
    const [snacks,setSnack]=useContext(SnacksContext)
    const [list,setList]=useState([])
    return(
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(200px,1fr))"}}>
            {snacks.map(i=>(
                <div>
                     <img src={i.picture}></img>
                      <h1>{i.product}</h1>
                      <h2>{i.price}</h2>
                      <button onClick={()=>setList(list=>[...list,i])}>buy</button>
                  </div>
            ))}

        </div>
    )
</code>```

答:
Objects are not valid as a React child (found: object with keys {product}).
```

<p>With the error, it is clear that <code>snacks</code> is an array of objects in which <code>product</code> is a key which is an object. You are trying to render an object - like this - <code><h1>{i.product}</h1></code>. </p>

<p>So see the property of <code>i.product</code> and render it accordingly. Eg: <code>i.product.title</code></p>

<pre class="lang-js prettyprint-override"><code>                  <div>
                     <img src={i.picture}></img>
                      <h1>{i.product.title}</h1> //<---- see here
                      <h2>{i.price}</h2>
                      <button onClick={()=>setList(list=>[...list,i])}>buy</button>
                  </div>
</code>```

Body:
Im new to react,how can i add an object to an array in a state properly, I am receiving an error :"Error: Objects are not valid as a React child (found: object with keys {product}). If you meant to render a collection of children, use an array instead." What can i do is to push the object into list every time i click the button?

import React, { useContext, useState } from 'react'
import {SnacksContext} from './Snacks'
import AddtoCart from './AddToCart'
const SnackItem=()=>{
    const [snacks,setSnack]=useContext(SnacksContext)
    const [list,setList]=useState([])
    return(

            {snacks.map(i=>(

{i.product}

{i.price}

                      <button onClick={()=>setList(list=>[...list,i])}>buy</button>

            ))}

    )

Body:
Objects are not valid as a React child (found: object with keys {product}).

With the error, it is clear that snacks is an array of objects in which product is a key which is an object. You are trying to render an object - like this - <h1>{i.product}</h1>.

So see the property of i.product and render it accordingly. Eg: i.product.title

                  <div>
                     <img src={i.picture}></img>
                      <h1>{i.product.title}</h1> //<---- see here
                      <h2>{i.price}</h2>
                      <button onClick={()=>setList(list=>[...list,i])}>buy</button>
                  </div>


问:
How can i print a page in asp.net without master page and to change color schemes of the page?
i have made a page in asp.net, i have a costing calculator which has more than 50 fields, dependent on each other, one is the result of previous two and like that, i want my page to be printed in a well manner, and the header of the page which is in master page should not be in print, also the color schemes i want to adjust, let me know the best solution for this which .net provides</p>

答:
Nothing to do with .Net and everything to do with a print stylesheet. You can create a stylesheet which will only work for when the page is printed. And you can change everything from what displays to postion to colours.

Use:

```<code><LINK rel="stylesheet" type"text/css" href="print.css" media="print">
</code>```

Note media="print" means it'll be used for printed pages.

Body:
Nothing to do with .Net and everything to do with a print stylesheet. You can create a stylesheet which will only work for when the page is printed. And you can change everything from what displays to postion to colours.

Use:

<LINK rel="stylesheet" type"text/css" href="print.css" media="print">

Note media="print" means it'll be used for printed pages.


问:
Flutter Dart Http XML rest convert to Json
I'm trying to get a album list from a server, the server uses xml and I'm trying to convert it to json but for some reason it doesn't work/comes back as null.

```<code>
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:xml2json/xml2json.dart';
import 'package:get/get.dart';
import 'package:xml/xml.dart' as xml;

class RecentlyAddedHome extends StatefulWidget {
  @override
  _RecentlyAddedHomState createState() => _RecentlyAddedHomState();
}

  Future<List<AlbumsResponse>> fetchRecentlyAddedAlbums() async{
  final aresponse = await http.get(recentAlbumsURL);
  xml2json.parse(aresponse.body);
  var jsondata = xml2json.toGData();
  var data = json.decode(jsondata);
  print(data);
  return AlbumsResponse.fromJson(data).toList();
}

class _RecentlyAddedHomState extends State<RecentlyAddedHome> {
  final Future<List<AlbumsResponse>> albumsresponse = fetchRecentlyAddedAlbums();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: FutureBuilder(
          future: fetchRecentlyAddedAlbums(),
          builder: (context, data){
            if (data.hasData){
              List<AlbumsResponse> albumsresponse = data.data;
              return ListView.builder(
              itemCount: albumsresponse.length,
              itemBuilder: (context, index){
                return ListTile(
                  title: Text(albumsresponse[index].title,style: TextStyle(fontSize: 25.0),),
                );
              },
              );
            }
          },
        )
      )
    );
  }
}

</code>```

this is my model for it

```<code>import 'package:xml/xml.dart' as xml;
import 'package:music_app_prototype/services/auth.dart';
import 'package:http/http.dart' as http;

 class AlbumsResponse {
  final String title;
  final int albumid;
  final String artist;
  final int coverart;

  AlbumsResponse({this.albumid, this.artist, this.coverart, this.title});

  factory AlbumsResponse.fromJson(Map<String, dynamic> json){
    return AlbumsResponse(
      title: json['_title'] as String,
      albumid: json['_albumid'] as int,
      artist: json['_artist'] as String,
      coverart: json['_coverart'] as int,
    );
  }
  get albumtitle => this.title;

  Future<List<AlbumsResponse>> toList() {}
}
</code>```

and this is what the server sends me when i make the request

```<code><?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.15.0">
    <albumList>
        <album id="695" parent="577" isDir="true" title="Whatever" album="Whatever" artist="Kaytranada" genre="Hip-Hop" coverArt="695" playCount="0" created="2020-04-18T02:01:55.546Z"/>
        <album id="850" parent="581" isDir="true" title="Cruel Intentions" album="Cruel Intentions" artist="Tory Lanez" genre="Hip-Hop" coverArt="850" playCount="1" created="2020-04-18T01:56:48.148Z"/>
        <album id="649" parent="574" isDir="true" title="So Far Gone" album="So Far Gone" artist="Drake" year="2009" genre="Hip-Hop/Rap" coverArt="649" playCount="0" created="2020-04-18T01:49:12.120Z"/>
        <album id="668" parent="575" isDir="true" title="Myst" album="Myst" artist="Herzeloyde" year="2020" genre="Electro" coverArt="668" playCount="1" created="2020-04-05T03:08:36.596Z"/>
        <album id="607" parent="572" isDir="true" title="Survival" album="Survival" artist="Dave East" year="2019" genre="Hip-Hop/Rap" coverArt="607" playCount="2" created="2020-03-01T02:29:48.072Z"/>
        <album id="792" parent="580" isDir="true" title="Yikes" album="Yikes" artist="Nicki Minaj" year="2020" genre="Rap/Hip Hop" coverArt="792" playCount="0" created="2020-02-17T04:47:49.067Z"/>
        <album id="790" parent="580" isDir="true" title="Sucka Free" album="Sucka Free" artist="Nicki Minaj" year="2008" genre="Hip-Hop" coverArt="790" playCount="0" created="2020-01-02T01:34:11.738Z"/>
        <album id="786" parent="580" isDir="true" title="Playtimes Over" album="Playtimes Over" artist="Nicki Minaj" year="2007" genre="Hip-Hop" coverArt="786" playCount="0" created="2020-01-02T01:34:11.716Z"/>
        <album id="715" parent="578" isDir="true" title="No Ceilings 2" album="No Ceilings 2" artist="Lil Wayne" year="2009" genre="Hip-Hop" coverArt="715" playCount="0" created="2020-01-02T01:34:04.226Z"/>
        <album id="788" parent="580" isDir="true" title="Queen" album="Queen" artist="Nicki Minaj" year="2018" genre="Hip-Hop/Rap" coverArt="788" playCount="0" created="2020-01-02T00:25:00.671Z"/>
    </albumList>
</subsonic-response>
</code>```

When i try to go to the Recently added page it says my build function returned null? I see that i get the data but it still doesn't show up. Can anyone help me, I'm not sure what I'm doing wrong, if i don't have to convert it from xml to json, how to do i work with it in xml form?
Thanks!

答:
You can copy paste run full code below

Step 1: Parse with payloadFromJson and return data.subsonicResponse.albumList.album, see full code for detail Payload class definition

```<code>Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
...
final aresponse = http.Response(xml, 200);

xml2json.parse(aresponse.body);
var jsondata = xml2json.toGData();
var data = payloadFromJson(jsondata);
var albumList = data.subsonicResponse.albumList.album;

return albumList;
</code>```

Step 2: builder need to define type AsyncSnapshot<List<AlbumsResponse>> and check connectionState

```<code> builder: (context, AsyncSnapshot<List<AlbumsResponse>> data) {
        switch (data.connectionState) {
          case ConnectionState.none:
            return Text('none');
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          case ConnectionState.active:
            return Text('');
          case ConnectionState.done:
            if (data.hasData) {
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:xml2json/xml2json.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.version,
    this.encoding,
    this.subsonicResponse,
  });

  String version;
  String encoding;
  SubsonicResponse subsonicResponse;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        version: json["version"],
        encoding: json["encoding"],
        subsonicResponse: SubsonicResponse.fromJson(json["subsonic-response"]),
      );

  Map<String, dynamic> toJson() => {
        "version": version,
        "encoding": encoding,
        "subsonic-response": subsonicResponse.toJson(),
      };
}

class SubsonicResponse {
  SubsonicResponse({
    this.status,
    this.version,
    this.xmlns,
    this.albumList,
  });

  String status;
  String version;
  String xmlns;
  AlbumList albumList;

  factory SubsonicResponse.fromJson(Map<String, dynamic> json) =>
      SubsonicResponse(
        status: json["status"],
        version: json["version"],
        xmlns: json["xmlns"],
        albumList: AlbumList.fromJson(json["albumList"]),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "version": version,
        "xmlns": xmlns,
        "albumList": albumList.toJson(),
      };
}

class AlbumList {
  AlbumList({
    this.album,
  });

  List<AlbumsResponse> album;

  factory AlbumList.fromJson(Map<String, dynamic> json) => AlbumList(
        album: List<AlbumsResponse>.from(
            json["album"].map((x) => AlbumsResponse.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "album": List<dynamic>.from(album.map((x) => x.toJson())),
      };
}

class AlbumsResponse {
  AlbumsResponse({
    this.id,
    this.parent,
    this.isDir,
    this.title,
    this.album,
    this.artist,
    this.genre,
    this.coverArt,
    this.playCount,
    this.created,
    this.year,
  });

  String id;
  String parent;
  String isDir;
  String title;
  String album;
  String artist;
  String genre;
  String coverArt;
  String playCount;
  DateTime created;
  String year;

  factory AlbumsResponse.fromJson(Map<String, dynamic> json) => AlbumsResponse(
        id: json["id"],
        parent: json["parent"],
        isDir: json["isDir"],
        title: json["title"],
        album: json["album"],
        artist: json["artist"],
        genre: json["genre"],
        coverArt: json["coverArt"],
        playCount: json["playCount"],
        created: DateTime.parse(json["created"]),
        year: json["year"] == null ? null : json["year"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "parent": parent,
        "isDir": isDir,
        "title": title,
        "album": album,
        "artist": artist,
        "genre": genre,
        "coverArt": coverArt,
        "playCount": playCount,
        "created": created.toIso8601String(),
        "year": year == null ? null : year,
      };
}

Xml2Json xml2json = Xml2Json();
Future<List<AlbumsResponse>> fetchRecentlyAddedAlbums() async {
  //final aresponse = await http.get(recentAlbumsURL);
  String xml = '''
  <?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.15.0">
    <albumList>
        <album id="695" parent="577" isDir="true" title="Whatever" album="Whatever" artist="Kaytranada" genre="Hip-Hop" coverArt="695" playCount="0" created="2020-04-18T02:01:55.546Z"/>
        <album id="850" parent="581" isDir="true" title="Cruel Intentions" album="Cruel Intentions" artist="Tory Lanez" genre="Hip-Hop" coverArt="850" playCount="1" created="2020-04-18T01:56:48.148Z"/>
        <album id="649" parent="574" isDir="true" title="So Far Gone" album="So Far Gone" artist="Drake" year="2009" genre="Hip-Hop/Rap" coverArt="649" playCount="0" created="2020-04-18T01:49:12.120Z"/>
        <album id="668" parent="575" isDir="true" title="Myst" album="Myst" artist="Herzeloyde" year="2020" genre="Electro" coverArt="668" playCount="1" created="2020-04-05T03:08:36.596Z"/>
        <album id="607" parent="572" isDir="true" title="Survival" album="Survival" artist="Dave East" year="2019" genre="Hip-Hop/Rap" coverArt="607" playCount="2" created="2020-03-01T02:29:48.072Z"/>
        <album id="792" parent="580" isDir="true" title="Yikes" album="Yikes" artist="Nicki Minaj" year="2020" genre="Rap/Hip Hop" coverArt="792" playCount="0" created="2020-02-17T04:47:49.067Z"/>
        <album id="790" parent="580" isDir="true" title="Sucka Free" album="Sucka Free" artist="Nicki Minaj" year="2008" genre="Hip-Hop" coverArt="790" playCount="0" created="2020-01-02T01:34:11.738Z"/>
        <album id="786" parent="580" isDir="true" title="Playtimes Over" album="Playtimes Over" artist="Nicki Minaj" year="2007" genre="Hip-Hop" coverArt="786" playCount="0" created="2020-01-02T01:34:11.716Z"/>
        <album id="715" parent="578" isDir="true" title="No Ceilings 2" album="No Ceilings 2" artist="Lil Wayne" year="2009" genre="Hip-Hop" coverArt="715" playCount="0" created="2020-01-02T01:34:04.226Z"/>
        <album id="788" parent="580" isDir="true" title="Queen" album="Queen" artist="Nicki Minaj" year="2018" genre="Hip-Hop/Rap" coverArt="788" playCount="0" created="2020-01-02T00:25:00.671Z"/>
    </albumList>
</subsonic-response>
''';

  final aresponse = http.Response(xml, 200);

  xml2json.parse(aresponse.body);
  var jsondata = xml2json.toGData();
  var data = payloadFromJson(jsondata);
  var albumList = data.subsonicResponse.albumList.album;
  //print(albumList.toString());
  return albumList;
}

class RecentlyAddedHome extends StatefulWidget {
  @override
  _RecentlyAddedHomState createState() => _RecentlyAddedHomState();
}

class _RecentlyAddedHomState extends State<RecentlyAddedHome> {
  final Future<List<AlbumsResponse>> albumsresponse =
      fetchRecentlyAddedAlbums();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            child: FutureBuilder(
      future: fetchRecentlyAddedAlbums(),
      builder: (context, AsyncSnapshot<List<AlbumsResponse>> data) {
        switch (data.connectionState) {
          case ConnectionState.none:
            return Text('none');
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          case ConnectionState.active:
            return Text('');
          case ConnectionState.done:
            if (data.hasData) {
              List<AlbumsResponse> albumsresponse = data.data;
              return ListView.builder(
                itemCount: albumsresponse.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(
                      albumsresponse[index].title,
                      style: TextStyle(fontSize: 25.0),
                    ),
                  );
                },
              );
            }
        }
      },
    )));
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: RecentlyAddedHome(),
    );
  }
}
</code>```

Body:
I'm trying to get a album list from a server, the server uses xml and I'm trying to convert it to json but for some reason it doesn't work/comes back as null.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:xml2json/xml2json.dart';
import 'package:get/get.dart';
import 'package:xml/xml.dart' as xml;

class RecentlyAddedHome extends StatefulWidget {
  @override
  _RecentlyAddedHomState createState() => _RecentlyAddedHomState();
}

  Future<List<AlbumsResponse>> fetchRecentlyAddedAlbums() async{
  final aresponse = await http.get(recentAlbumsURL);
  xml2json.parse(aresponse.body);
  var jsondata = xml2json.toGData();
  var data = json.decode(jsondata);
  print(data);
  return AlbumsResponse.fromJson(data).toList();
}

class _RecentlyAddedHomState extends State<RecentlyAddedHome> {
  final Future<List<AlbumsResponse>> albumsresponse = fetchRecentlyAddedAlbums();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: FutureBuilder(
          future: fetchRecentlyAddedAlbums(),
          builder: (context, data){
            if (data.hasData){
              List<AlbumsResponse> albumsresponse = data.data;
              return ListView.builder(
              itemCount: albumsresponse.length,
              itemBuilder: (context, index){
                return ListTile(
                  title: Text(albumsresponse[index].title,style: TextStyle(fontSize: 25.0),),
                );
              },
              );
            }
          },
        )
      )
    );
  }
}

this is my model for it

import 'package:xml/xml.dart' as xml;
import 'package:music_app_prototype/services/auth.dart';
import 'package:http/http.dart' as http;

 class AlbumsResponse {
  final String title;
  final int albumid;
  final String artist;
  final int coverart;

  AlbumsResponse({this.albumid, this.artist, this.coverart, this.title});

  factory AlbumsResponse.fromJson(Map<String, dynamic> json){
    return AlbumsResponse(
      title: json['_title'] as String,
      albumid: json['_albumid'] as int,
      artist: json['_artist'] as String,
      coverart: json['_coverart'] as int,
    );
  }
  get albumtitle => this.title;

  Future<List<AlbumsResponse>> toList() {}
}

and this is what the server sends me when i make the request

<?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.15.0">
    <albumList>
        <album id="695" parent="577" isDir="true" title="Whatever" album="Whatever" artist="Kaytranada" genre="Hip-Hop" coverArt="695" playCount="0" created="2020-04-18T02:01:55.546Z"/>
        <album id="850" parent="581" isDir="true" title="Cruel Intentions" album="Cruel Intentions" artist="Tory Lanez" genre="Hip-Hop" coverArt="850" playCount="1" created="2020-04-18T01:56:48.148Z"/>
        <album id="649" parent="574" isDir="true" title="So Far Gone" album="So Far Gone" artist="Drake" year="2009" genre="Hip-Hop/Rap" coverArt="649" playCount="0" created="2020-04-18T01:49:12.120Z"/>
        <album id="668" parent="575" isDir="true" title="Myst" album="Myst" artist="Herzeloyde" year="2020" genre="Electro" coverArt="668" playCount="1" created="2020-04-05T03:08:36.596Z"/>
        <album id="607" parent="572" isDir="true" title="Survival" album="Survival" artist="Dave East" year="2019" genre="Hip-Hop/Rap" coverArt="607" playCount="2" created="2020-03-01T02:29:48.072Z"/>
        <album id="792" parent="580" isDir="true" title="Yikes" album="Yikes" artist="Nicki Minaj" year="2020" genre="Rap/Hip Hop" coverArt="792" playCount="0" created="2020-02-17T04:47:49.067Z"/>
        <album id="790" parent="580" isDir="true" title="Sucka Free" album="Sucka Free" artist="Nicki Minaj" year="2008" genre="Hip-Hop" coverArt="790" playCount="0" created="2020-01-02T01:34:11.738Z"/>
        <album id="786" parent="580" isDir="true" title="Playtimes Over" album="Playtimes Over" artist="Nicki Minaj" year="2007" genre="Hip-Hop" coverArt="786" playCount="0" created="2020-01-02T01:34:11.716Z"/>
        <album id="715" parent="578" isDir="true" title="No Ceilings 2" album="No Ceilings 2" artist="Lil Wayne" year="2009" genre="Hip-Hop" coverArt="715" playCount="0" created="2020-01-02T01:34:04.226Z"/>
        <album id="788" parent="580" isDir="true" title="Queen" album="Queen" artist="Nicki Minaj" year="2018" genre="Hip-Hop/Rap" coverArt="788" playCount="0" created="2020-01-02T00:25:00.671Z"/>
    </albumList>
</subsonic-response>

When i try to go to the Recently added page it says my build function returned null? I see that i get the data but it still doesn't show up. Can anyone help me, I'm not sure what I'm doing wrong, if i don't have to convert it from xml to json, how to do i work with it in xml form?
Thanks!

Body:
You can copy paste run full code below

Step 1: Parse with payloadFromJson and return data.subsonicResponse.albumList.album, see full code for detail Payload class definition

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
...
final aresponse = http.Response(xml, 200);

xml2json.parse(aresponse.body);
var jsondata = xml2json.toGData();
var data = payloadFromJson(jsondata);
var albumList = data.subsonicResponse.albumList.album;

return albumList;

Step 2: builder need to define type AsyncSnapshot<List<AlbumsResponse>> and check connectionState

 builder: (context, AsyncSnapshot<List<AlbumsResponse>> data) {
        switch (data.connectionState) {
          case ConnectionState.none:
            return Text('none');
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          case ConnectionState.active:
            return Text('');
          case ConnectionState.done:
            if (data.hasData) {

working demo

full code

import 'package:flutter/material.dart';
import 'package:xml2json/xml2json.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.version,
    this.encoding,
    this.subsonicResponse,
  });

  String version;
  String encoding;
  SubsonicResponse subsonicResponse;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        version: json["version"],
        encoding: json["encoding"],
        subsonicResponse: SubsonicResponse.fromJson(json["subsonic-response"]),
      );

  Map<String, dynamic> toJson() => {
        "version": version,
        "encoding": encoding,
        "subsonic-response": subsonicResponse.toJson(),
      };
}

class SubsonicResponse {
  SubsonicResponse({
    this.status,
    this.version,
    this.xmlns,
    this.albumList,
  });

  String status;
  String version;
  String xmlns;
  AlbumList albumList;

  factory SubsonicResponse.fromJson(Map<String, dynamic> json) =>
      SubsonicResponse(
        status: json["status"],
        version: json["version"],
        xmlns: json["xmlns"],
        albumList: AlbumList.fromJson(json["albumList"]),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "version": version,
        "xmlns": xmlns,
        "albumList": albumList.toJson(),
      };
}

class AlbumList {
  AlbumList({
    this.album,
  });

  List<AlbumsResponse> album;

  factory AlbumList.fromJson(Map<String, dynamic> json) => AlbumList(
        album: List<AlbumsResponse>.from(
            json["album"].map((x) => AlbumsResponse.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "album": List<dynamic>.from(album.map((x) => x.toJson())),
      };
}

class AlbumsResponse {
  AlbumsResponse({
    this.id,
    this.parent,
    this.isDir,
    this.title,
    this.album,
    this.artist,
    this.genre,
    this.coverArt,
    this.playCount,
    this.created,
    this.year,
  });

  String id;
  String parent;
  String isDir;
  String title;
  String album;
  String artist;
  String genre;
  String coverArt;
  String playCount;
  DateTime created;
  String year;

  factory AlbumsResponse.fromJson(Map<String, dynamic> json) => AlbumsResponse(
        id: json["id"],
        parent: json["parent"],
        isDir: json["isDir"],
        title: json["title"],
        album: json["album"],
        artist: json["artist"],
        genre: json["genre"],
        coverArt: json["coverArt"],
        playCount: json["playCount"],
        created: DateTime.parse(json["created"]),
        year: json["year"] == null ? null : json["year"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "parent": parent,
        "isDir": isDir,
        "title": title,
        "album": album,
        "artist": artist,
        "genre": genre,
        "coverArt": coverArt,
        "playCount": playCount,
        "created": created.toIso8601String(),
        "year": year == null ? null : year,
      };
}

Xml2Json xml2json = Xml2Json();
Future<List<AlbumsResponse>> fetchRecentlyAddedAlbums() async {
  //final aresponse = await http.get(recentAlbumsURL);
  String xml = '''
  <?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.15.0">
    <albumList>
        <album id="695" parent="577" isDir="true" title="Whatever" album="Whatever" artist="Kaytranada" genre="Hip-Hop" coverArt="695" playCount="0" created="2020-04-18T02:01:55.546Z"/>
        <album id="850" parent="581" isDir="true" title="Cruel Intentions" album="Cruel Intentions" artist="Tory Lanez" genre="Hip-Hop" coverArt="850" playCount="1" created="2020-04-18T01:56:48.148Z"/>
        <album id="649" parent="574" isDir="true" title="So Far Gone" album="So Far Gone" artist="Drake" year="2009" genre="Hip-Hop/Rap" coverArt="649" playCount="0" created="2020-04-18T01:49:12.120Z"/>
        <album id="668" parent="575" isDir="true" title="Myst" album="Myst" artist="Herzeloyde" year="2020" genre="Electro" coverArt="668" playCount="1" created="2020-04-05T03:08:36.596Z"/>
        <album id="607" parent="572" isDir="true" title="Survival" album="Survival" artist="Dave East" year="2019" genre="Hip-Hop/Rap" coverArt="607" playCount="2" created="2020-03-01T02:29:48.072Z"/>
        <album id="792" parent="580" isDir="true" title="Yikes" album="Yikes" artist="Nicki Minaj" year="2020" genre="Rap/Hip Hop" coverArt="792" playCount="0" created="2020-02-17T04:47:49.067Z"/>
        <album id="790" parent="580" isDir="true" title="Sucka Free" album="Sucka Free" artist="Nicki Minaj" year="2008" genre="Hip-Hop" coverArt="790" playCount="0" created="2020-01-02T01:34:11.738Z"/>
        <album id="786" parent="580" isDir="true" title="Playtimes Over" album="Playtimes Over" artist="Nicki Minaj" year="2007" genre="Hip-Hop" coverArt="786" playCount="0" created="2020-01-02T01:34:11.716Z"/>
        <album id="715" parent="578" isDir="true" title="No Ceilings 2" album="No Ceilings 2" artist="Lil Wayne" year="2009" genre="Hip-Hop" coverArt="715" playCount="0" created="2020-01-02T01:34:04.226Z"/>
        <album id="788" parent="580" isDir="true" title="Queen" album="Queen" artist="Nicki Minaj" year="2018" genre="Hip-Hop/Rap" coverArt="788" playCount="0" created="2020-01-02T00:25:00.671Z"/>
    </albumList>
</subsonic-response>
''';

  final aresponse = http.Response(xml, 200);

  xml2json.parse(aresponse.body);
  var jsondata = xml2json.toGData();
  var data = payloadFromJson(jsondata);
  var albumList = data.subsonicResponse.albumList.album;
  //print(albumList.toString());
  return albumList;
}

class RecentlyAddedHome extends StatefulWidget {
  @override
  _RecentlyAddedHomState createState() => _RecentlyAddedHomState();
}

class _RecentlyAddedHomState extends State<RecentlyAddedHome> {
  final Future<List<AlbumsResponse>> albumsresponse =
      fetchRecentlyAddedAlbums();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            child: FutureBuilder(
      future: fetchRecentlyAddedAlbums(),
      builder: (context, AsyncSnapshot<List<AlbumsResponse>> data) {
        switch (data.connectionState) {
          case ConnectionState.none:
            return Text('none');
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          case ConnectionState.active:
            return Text('');
          case ConnectionState.done:
            if (data.hasData) {
              List<AlbumsResponse> albumsresponse = data.data;
              return ListView.builder(
                itemCount: albumsresponse.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(
                      albumsresponse[index].title,
                      style: TextStyle(fontSize: 25.0),
                    ),
                  );
                },
              );
            }
        }
      },
    )));
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: RecentlyAddedHome(),
    );
  }
}