问:
Select rows with max(id) having max(payment_date)
I've been trying to get the max(id) for the max(payment_date) of every account_id, as there are instances where there's different entries for the same max(payment_date). The ids are the payment references for the account_ids. So every account_id needs to have one entry with the max(payment_date) and the max(id) for that date. Problem is that there are entries where the max(id) for the account_id is not for the max(payment_date), or I would have just used max(id). The code below is not working because of this, since it will exclude entries where the max(id) is not for the max(payment_date). Thanks in advance.</p>

```<code>select *
from (
  select payments.*
  from (
    select account_id, max(payment_date) as last_payment, max(id) as last_payment1
    from energy.payments
    where state = 'success'
      and amount_pennies > 0
      and description not ilike '%credit%'
      group by account_id
  ) as last_payment_table
  inner join energy.payments as payments
         on payments.account_id = last_payment_table.account_id
        and payments.payment_date = last_payment_table.last_payment
        and payments.id = last_payment_table.last_payment1
) as paymentst1
</code>```

答:
It is hard to understand the question, but I think you mean this:

```<code>SELECT *
FROM payments  p
WHERE NOT EXISTS (
        SELECT *
        FROM payments  nx
        WHERE nx.account_id = p.account_id      -- same account
        AND nx.payment_date >= p.payment_date   -- same or more recent date
        AND nx.id > p.id                        -- higher ID
        );
</code>```

Or, using a window function:

```<code>select *
from (
  select *
    , row_number() OVER(PARTITION BY account_id
                        ORDER BY payment_date DESC,id DESC) as rn
    from energy.payments
    where state = 'success'
      and amount_pennies > 0
      and description not ilike '%credit%'
) x
WHERE x.rn=1
        ;
</code>```

Body:
I've been trying to get the max(id) for the max(payment_date) of every account_id, as there are instances where there's different entries for the same max(payment_date). The ids are the payment references for the account_ids. So every account_id needs to have one entry with the max(payment_date) and the max(id) for that date. Problem is that there are entries where the max(id) for the account_id is not for the max(payment_date), or I would have just used max(id). The code below is not working because of this, since it will exclude entries where the max(id) is not for the max(payment_date). Thanks in advance.

select *
from (
  select payments.*
  from (
    select account_id, max(payment_date) as last_payment, max(id) as last_payment1
    from energy.payments
    where state = 'success'
      and amount_pennies > 0
      and description not ilike '%credit%'
      group by account_id
  ) as last_payment_table
  inner join energy.payments as payments
         on payments.account_id = last_payment_table.account_id
        and payments.payment_date = last_payment_table.last_payment
        and payments.id = last_payment_table.last_payment1
) as paymentst1

Body:
It is hard to understand the question, but I think you mean this:

SELECT *
FROM payments  p
WHERE NOT EXISTS (
        SELECT *
        FROM payments  nx
        WHERE nx.account_id = p.account_id      -- same account
        AND nx.payment_date >= p.payment_date   -- same or more recent date
        AND nx.id > p.id                        -- higher ID
        );

Or, using a window function:

select *
from (
  select *
    , row_number() OVER(PARTITION BY account_id
                        ORDER BY payment_date DESC,id DESC) as rn
    from energy.payments
    where state = 'success'
      and amount_pennies > 0
      and description not ilike '%credit%'
) x
WHERE x.rn=1
        ;


来源: stackexchange

问:
Google Data studio -Default filter on last month when data is at month level
I have a report with one data source in Google Data Studio. The data is at month level inside the BigQuery table YYYYMM (for example 202001). I have a filter that is set on the year-month dimension which works ok but I would like to add a default value which changes to last month(max(year_month)) available in the table.
Is this possible? I only found the option to hard-code the default selection but this can't be updated dynamically

as in this screen shot

Jaishree's suggestion

答:
You can create an another field/column as same year-month and always keep the latest year-month value as "latest month" or any name you want. You can use logic like

```<code>when existing_column = max(year_month) then "latest month" else existing_column
</code>```

Something like this

```<code>  existing_column   new_column
  022020            latest month
  012020            012020
  122019            122019
  112019            122019
</code>```

You can pass this "latest month" value in the default selection option this option which is just below the dimension. But each time you upload new data you have to update this field like change the table suppose for next month you table should be like

```<code>  existing_column   new_column
  032020            latest month
  022020            022020
  012020            012020
  122019            122019
  112019            122019
</code>```

You can make auto update by scheduling queries as well in big query from where you are loading data to Google data studio.

ContentLicense: CC BY-SA 4.0

Body:
You can create an another field/column as same year-month and always keep the latest year-month value as "latest month" or any name you want. You can use logic like

when existing_column = max(year_month) then "latest month" else existing_column

Something like this

  existing_column   new_column
  022020            latest month
  012020            012020
  122019            122019
  112019            122019

You can pass this "latest month" value in the default selection option this option which is just below the dimension. But each time you upload new data you have to update this field like change the table suppose for next month you table should be like

  existing_column   new_column
  032020            latest month
  022020            022020
  012020            012020
  122019            122019
  112019            122019

You can make auto update by scheduling queries as well in big query from where you are loading data to Google data studio.


问:
Identifying lines ending in capital letters with AWK and using them as record separators
This is a smaller representative version of a data file that I need to parse and divide into chunks with awk based on the roman numeral of each chunk.

```<code>I
   Apple
   II
Banana

   III
   Mango
IV
Durian
Lemon

   IV
      Papaya
       V
</code>```

This seemed like an easy task with awk, so I tried
gawk -v RS="[A-Z]+$" '{print $0}' blah.txt to use lines that end with one or more capital letters (thus indicating lines with Roman Numerals) as record separators.

Surprisingly the program outputted the entire data file. Where did I go wrong?
Even more surprisingly, if I place an exit after the print statement, it still prints the entire file (indicating that the whole file is considered as one record)

I am using GNU AWK 4.1.3 on a Linux Mint machine.

NOTE: The specific use case I have in mind is to extract an arbitrary Shakespearean sonnet by number from the text file at http://www.gutenberg.org/cache/epub/1041/pg1041.txt (after removing the boilerplate header and footer data )

答:
Given the input on http://www.gutenberg.org/cache/epub/1041/pg1041.txt, it looks like you can just print the 12th, 14th, 16th, paragraph to get the output that you want. Setting the Record Separator to an empty string and printing the desired record is enough to do that.

For example, to print the first sonnet:

$ awk -v RS='' -v sonnet=1 'NR == 10 + 2 * sonnet' file
  From fairest creatures we desire increase,
  That thereby beauty's rose might never die,
  But as the riper should by time decease,
  His tender heir might bear his memory:
  But thou, contracted to thine own bright eyes,
  Feed'st thy light's flame with self-substantial fuel,
  Making a famine where abundance lies,
  Thy self thy foe, to thy sweet self too cruel:
  Thou that art now the world's fresh ornament,
  And only herald to the gaudy spring,
  Within thine own bud buriest thy content,
  And tender churl mak'st waste in niggarding:
    Pity the world, or else this glutton be,
    To eat the world's due, by the grave and thee.
```

Body:
This is a smaller representative version of a data file that I need to parse and divide into chunks with awk based on the roman numeral of each chunk.

I
   Apple
   II
Banana

   III
   Mango
IV
Durian
Lemon

   IV
      Papaya
       V

This seemed like an easy task with awk, so I tried
gawk -v RS="[A-Z]+$" '{print $0}' blah.txt to use lines that end with one or more capital letters (thus indicating lines with Roman Numerals) as record separators.

Surprisingly the program outputted the entire data file. Where did I go wrong?
Even more surprisingly, if I place an exit after the print statement, it still prints the entire file (indicating that the whole file is considered as one record)

I am using GNU AWK 4.1.3 on a Linux Mint machine.

NOTE: The specific use case I have in mind is to extract an arbitrary Shakespearean sonnet by number from the text file at http://www.gutenberg.org/cache/epub/1041/pg1041.txt (after removing the boilerplate header and footer data )


问:
Python - Return list of tuples
I am trying to return a list of tuples in the below

```<code>def lambda_handler(event, context):

    t1 = [('a', 'string', 'a', 'string'), ('b', 'string', 'b', 'string')]

    print(t1)
    return t1
</code>```

When I print the list or convert the list to str -> print, I get the below:

```<code>[('a', 'string', 'a', 'string'), ('b', 'string', 'b', 'string')]
</code>```

When I return I get

```<code>[
  [
    "a",
    "string",
    "a",
    "string"
  ],
  [
    "b",
    "string",
    "b",
    "string"
  ]
]
</code>```

My challenge is that I need to submit a list of tuples for an AWS Glue Job service:

```<code>ApplyMapping.apply(frame = datasource0, mappings = [("a", "string", "a", "string"), ("b", "string", "b", "string")], transformation_ctx = "applymapping1")
</code>```

But I pass (MY_LIST_PARAM) which is the output of the return command:

```<code>ApplyMapping.apply(frame = datasource0, mappings = MY_LIST_PARAM, transformation_ctx = "applymapping1")
</code>```

However, I then get the following error:

```<code>TypeError: Mapping must be specified as a tuple. Got [
</code>```

I can't hard code the values, as it is a single job which take the argument list and applies that in the job logic. Printing the List as a String doesn't help me (even though it looks correct) as I need a list of tuples in format [(),()] and not [[],[]].

I am using Python 3.7. Also executing in AWS Lambda (but this should not make a difference)

答:
Also executing in AWS Lambda (but this should not make a difference)

I expect it does. I'd guess the data is moved from lambda to glue (or whatever) as JSON[0], JSON doesn't have tuples so python converts tuples to JSON arrays, which become lists on the other side.

Convert the lists back to tuples on the receiver side if the API you're calling throws a fit when given lists. It's just a matter of running a list comprehension or list(map(tuple, MY_LIST_PARAM)).

[0] or some other format with similar capabilities / limitations I can't think of any serialisation format which would provide for Python's distinction between tuples and lists which is only a matter of mutability (and thus not really a concern to serialisation formats), they might have something like an "anoymous structure" or "anonymous record" but Python tuples would rarely get serialized to that, at least implicitly

Title: Python - Return list of tuples

Body:
I am trying to return a list of tuples in the below

def lambda_handler(event, context):

    t1 = [('a', 'string', 'a', 'string'), ('b', 'string', 'b', 'string')]

    print(t1)
    return t1

When I print the list or convert the list to str -> print, I get the below:

[('a', 'string', 'a', 'string'), ('b', 'string', 'b', 'string')]

When I return I get

[
  [
    "a",
    "string",
    "a",
    "string"
  ],
  [
    "b",
    "string",
    "b",
    "string"
  ]
]

My challenge is that I need to submit a list of tuples for an AWS Glue Job service:

ApplyMapping.apply(frame = datasource0, mappings = [("a", "string", "a", "string"), ("b", "string", "b", "string")], transformation_ctx = "applymapping1")

But I pass (MY_LIST_PARAM) which is the output of the return command:

ApplyMapping.apply(frame = datasource0, mappings = MY_LIST_PARAM, transformation_ctx = "applymapping1")

However, I then get the following error:

TypeError: Mapping must be specified as a tuple. Got [

I can't hard code the values, as it is a single job which take the argument list and applies that in the job logic. Printing the List as a String doesn't help me (even though it looks correct) as I need a list of tuples in format [(),()] and not [[],[]].

I am using Python 3.7. Also executing in AWS Lambda (but this should not make a difference)


问:
Debugger statement throws an error in vuejs app
I'm using a simple v-on:click="demo" method that is attached to my input. In my demo function I use debugger statement to stop JavaScript engine execution. The problem is that debugger statement throws none sense errors in es-lint module. My question is simple. How to make debugger work ?

Code

```<code>export default {
  name: "Demo",
  methods: {
    demo: function () {
      console.log('Running demo')
      debugger
    }
  }
}
</code>```

Error

```<code>Failed to compile.

./src/components/Demo.vue
Module Error (from ./node_modules/eslint-loader/index.js):

/app/src/components/Upload.vue
   2:1   warning  Insert `··`                                                                                prettier/prettier
   3:1   warning  Insert `··`                                                                                prettier/prettier
   ...
   ...
</code>```

答:
I found the problem. Apparently, ES-linter disallows debugger statement rule. To make debugger work again I had to add // eslint-disable-line comment to my debugger line. Below lines of code solved the debugger error.

```<code>debugger // eslint-disable-line
</code>```

or

```<code>/* eslint-disable no-debugger */
debugger
</code>```

Body:
I'm using a simple v-on:click="demo" method that is attached to my input. In my demo function I use debugger statement to stop JavaScript engine execution. The problem is that debugger statement throws none sense errors in es-lint module. My question is simple. How to make debugger work ?

Code

export default {
  name: "Demo",
  methods: {
    demo: function () {
      console.log('Running demo')
      debugger
    }
  }
}

Error

Failed to compile.

./src/components/Demo.vue
Module Error (from ./node_modules/eslint-loader/index.js):

/app/src/components/Upload.vue
   2:1   warning  Insert `··`                                                                                prettier/prettier
   3:1   warning  Insert `··`                                                                                prettier/prettier
   ...
   ...

Body:
I found the problem. Apparently, ES-linter disallows debugger statement rule. To make debugger work again I had to add // eslint-disable-line comment to my debugger line. Below lines of code solved the debugger error.

debugger // eslint-disable-line

or

/* eslint-disable no-debugger */
debugger


问:
How to build dependent dropdown menus in Flutter?
I have three dropdown-menus, and I want a fourth one to be displayed ONLY if certain conditions are met (Favourite Animal = Cat). I also want that fourth dropdown-menu to disappear whenever the conditions are no longer true. Right now the changes are displayed if I manually save the file and execute hot reload, so I'm guessing it has something to do with setState(), which I have not included in the filter.dart-file.

File 1 - filter.dart:

```<code>import 'package:flutter/material.dart';
import './dropdown.dart';

class Filter extends StatefulWidget {
  @override
  _FilterState createState() => _FilterState();
}

class _FilterState extends State<Filter> {
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster']),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

File 2 - dropdown.dart:

```<code>import 'package:flutter/material.dart';

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;

  Dropdown(this._key, this._values);

  @override
  _DropdownState createState() => _DropdownState();
}

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String> (
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        },
      ),
    );
  }
}

bool cat = false; //Feels wrong to have this bool out in the open
</code>```

The filter.dart-file is called from main with Filter().

Bonus question: I also want to extract the chosen values and return them to the filter.dart-file and use them in the onPressed-function in the RaisedButton, not quite sure how to do that.

答:
On your DropdownButton you have the onChanged callback:

```<code>onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        }
</code>```

This call to setState() will be made to the Dropdown widget, not
to the higher Filter widget.

One way to solve this would be to add to your custom Dropdown class a Function callback:

```<code>class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;
  final Function callback;

  Dropdown(this._key, this._values, this.callback);

  @override
  _DropdownState createState() => _DropdownState();
}
</code>```

And, in the onChanged property:

```<code>onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          callback();
        },
</code>```

This will call the callback you define on the creation of Dropdown:

```<code>children: <Widget>[
                Dropdown('Gender', ['Female', 'Male'], callbackFunc),
                Dropdown('Age', ['<15', '15-20', '>20'], callbackFunc),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], callbackFunc),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball'], callbackFunc) : Text('')
              ],

</code>```

Where callbackFunc may be as simple:

```<code>void callbackFunc(){
    setState((){});
}
</code>```

Of course, this is not the most elegant solution.
Since you are using the callback, you can undo all the global-variable you used, and just use the callback with an argument:

```<code>void callbackFunc(String value){
    if (value=='cat')
        choseCat=true;
    else
        choseCat=false;
    setState((){});
}
</code>```

Also, you don't have to check the widget key to verify which dropdown is being called. You can check if the callback is null before calling it, and only give the callback function to the appropriate ones:

```<code>children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], callbackFunc),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],

[...]

onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          if (callback)
              callback();
        },

</code>```

Don't forget to make the callback optional in this case:

```<code>Dropdown({@required this._key, @required this._values, this.callback});

</code>```

I'm sure many other optimizations may be done with this approach. And with bigger apps other State management approaches should be chosen to make your life easier.

Body:
I have three dropdown-menus, and I want a fourth one to be displayed ONLY if certain conditions are met (Favourite Animal = Cat). I also want that fourth dropdown-menu to disappear whenever the conditions are no longer true. Right now the changes are displayed if I manually save the file and execute hot reload, so I'm guessing it has something to do with setState(), which I have not included in the filter.dart-file.

File 1 - filter.dart:

import 'package:flutter/material.dart';
import './dropdown.dart';

class Filter extends StatefulWidget {
  @override
  _FilterState createState() => _FilterState();
}

class _FilterState extends State<Filter> {
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster']),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}

File 2 - dropdown.dart:

import 'package:flutter/material.dart';

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;

  Dropdown(this._key, this._values);

  @override
  _DropdownState createState() => _DropdownState();
}

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String> (
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        },
      ),
    );
  }
}

bool cat = false; //Feels wrong to have this bool out in the open

The filter.dart-file is called from main with Filter().

Bonus question: I also want to extract the chosen values and return them to the filter.dart-file and use them in the onPressed-function in the RaisedButton, not quite sure how to do that.

Body:
On your DropdownButton you have the onChanged callback:

onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        }

This call to setState() will be made to the Dropdown widget, not
to the higher Filter widget.

One way to solve this would be to add to your custom Dropdown class a Function callback:

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;
  final Function callback;

  Dropdown(this._key, this._values, this.callback);

  @override
  _DropdownState createState() => _DropdownState();
}

And, in the onChanged property:

onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          callback();
        },

This will call the callback you define on the creation of Dropdown:

children: <Widget>[
                Dropdown('Gender', ['Female', 'Male'], callbackFunc),
                Dropdown('Age', ['<15', '15-20', '>20'], callbackFunc),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], callbackFunc),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball'], callbackFunc) : Text('')
              ],

Where callbackFunc may be as simple:

void callbackFunc(){
    setState((){});
}

Of course, this is not the most elegant solution.
Since you are using the callback, you can undo all the global-variable you used, and just use the callback with an argument:

void callbackFunc(String value){
    if (value=='cat')
        choseCat=true;
    else
        choseCat=false;
    setState((){});
}

Also, you don't have to check the widget key to verify which dropdown is being called. You can check if the callback is null before calling it, and only give the callback function to the appropriate ones:

children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], callbackFunc),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],

[...]

onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          if (callback)
              callback();
        },

Don't forget to make the callback optional in this case:

Dropdown({@required this._key, @required this._values, this.callback});

I'm sure many other optimizations may be done with this approach. And with bigger apps other State management approaches should be chosen to make your life easier.


问:
phpunit - return two objects to next test case
In some places, my phpunit methods have dependency on two classes so I have decided to write a dedicate method which will create an instance of these two classes(which are related to each other) and will pass them to all phpunit methods. I want to do something like below.

```<code>public function testGetInstance()
{
    $obj1 = new Class1();
    $obj2 = new Class2();
    return $obj1, $obj2;  //can i use list  ?
}

/**
*@depends testGetInstance()
*/
public function testBothFeatures(Class1 $obj1, Class2 $obj2) //how to pass 2 instances?
{
    //Do all operation related to $obj1 and $obj2
}
</code>```

How to achieve above case? Is there a better approach for same?

答:
The short answer:

@depends only works for one argument so you have to:

```<code>return array($obj1, $obj2);

public function testBothFeatures(array $myClasses) {
    $obj1 = $myClasses[0];
    $obj2 = $myClasses[1];
}
</code>```

Longer answer:

What are you doing there? Are you using one PHPUnit Test Case to test TWO real classes?

If so thats something you should usually avoid. The only exception is that you might be doing an "integration" test that makes sure bigger parts of your code work together, but you should only do that once you have a unit test for every class.

You want to make sure your classes work independed of other parts of your application so you can easily spot what exactly you broke when you change something.

If you have a class that depends on another class then mock out the second class and use that fake object to make sure your "class under test" works correctly.

ContentLicense: CC BY-SA 3.0

Body:
In some places, my phpunit methods have dependency on two classes so I have decided to write a dedicate method which will create an instance of these two classes(which are related to each other) and will pass them to all phpunit methods. I want to do something like below.

public function testGetInstance()
{
    $obj1 = new Class1();
    $obj2 = new Class2();
    return $obj1, $obj2;  //can i use list  ?
}

/**
*@depends testGetInstance()
*/
public function testBothFeatures(Class1 $obj1, Class2 $obj2) //how to pass 2 instances?
{
    //Do all operation related to $obj1 and $obj2
}

How to achieve above case? Is there a better approach for same?

Body:
The short answer:

@depends only works for one argument so you have to:

return array($obj1, $obj2);

public function testBothFeatures(array $myClasses) {
    $obj1 = $myClasses[0];
    $obj2 = $myClasses[1];
}

Longer answer:

What are you doing there? Are you using one PHPUnit Test Case to test TWO real classes?

If so thats something you should usually avoid. The only exception is that you might be doing an "integration" test that makes sure bigger parts of your code work together, but you should only do that once you have a unit test for every class.

You want to make sure your classes work independed of other parts of your application so you can easily spot what exactly you broke when you change something.

If you have a class that depends on another class then mock out the second class and use that fake object to make sure your "class under test" works correctly.


问:
Could not find a version that satisfies the requirement tensorflow
I installed the latest version of Python (3.6.4 64-bit) and the latest version of PyCharm (2017.3.3 64-bit). Then I installed some modules in PyCharm (Numpy, Pandas, etc), but when I tried installing Tensorflow it didn't install, and I got the error message:

Could not find a version that satisfies the requirement TensorFlow (from versions: )
      No matching distribution found for TensorFlow.

Then I tried installing TensorFlow from the command prompt and I got the same error message.
I did however successfully install tflearn.

I also installed Python 2.7, but I got the same error message again. I googled the error and tried some of the things which were suggested to other people, but nothing worked (this included installing Flask).

How can I install Tensorflow? Thanks.

答:
Running this before the tensorflow installation solved it for me:

```<code>pip install "pip>=19"
</code>```

As the tensorflow's system requirements states:

pip 19.0 or later

Body:
Running this before the tensorflow installation solved it for me:

pip install "pip>=19"

As the tensorflow's system requirements states:

pip 19.0 or later


问:
Switch case won't continue to the next statement
Below is my C code, one problem is that when I try to run it, it wont continue to printf the next statement after the switch and after I put in the input. It's a lecture hall/room booking system.If you saw, there is step 3 after the if else switch statement. It wont print out the step 3.</p>

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

int main()
{
    char applicant_name[100], applicant_faculty[100], applicant_date[40], applicant_id[50], applicant_mobile_number[20];
    int number_of_students, lecture_hall_book, lecture_room;
    char lecture_hall[20],  booking_date[20];

    printf("\n=======================================================================================\n");
    printf("                                Author : Fathul Amin\n");
    printf("                                Matric ID : CB19070\n");
    printf("=======================================================================================\n\n");
    printf("                             Universiti Malaysia Pahang\n\n");
    printf("     Welcome to the Faculty of Computing (FCOM) Lecture Hall/Room Booking System\n\n");
    printf("               For your information, this system was created to support\n");
    printf("             government initiative to reduce paper usage by replacing the \n");
    printf("                   manual application form to a computerized system \n\n\n");
    printf("                      There will be 3 STEP to apply for a booking\n\n");
    printf("\t [STEP 1] Application Information\n");
    printf("\t [STEP 2] Determine Lecture Hall/Room based on Number of Students\n");
    printf("\t [STEP 3] Lecture Hall/Room Booking Date\n\n");
    printf("\t [STEP 4] Lecture Hall/Room Booking Time\n\n");
    printf("\n=======================================================================================");
    printf("\n                [STEP 1]  Below is an example of information needed");
    printf("\n=======================================================================================\n\n");
    printf("      APPLICANT INFORMATION\n\n");
    printf("       NAME   : _____________               STAFF/STUDENT ID : ______________\n\n");
    printf("      FACULTY : _____________                 MOBILE NUMBER  : ______________\n\n");
    printf("       DATE   : _____________ (xx/xx/xxxx)\n");
    printf("\n=======================================================================================\n\n");
    printf("                         Enter Your Name  : ");
    fgets(applicant_name, 100, stdin);
    printf("                      Enter Your Faculty  : ");
    fgets(applicant_faculty, 100, stdin);
    printf("                      Enter Today's Date  : ");
    fgets(applicant_date, 40, stdin);
    printf("             Enter Your Staff/Student ID  : ");
    fgets(applicant_id, 50, stdin);
    printf("                Enter Your Mobile Number  : ");
    fgets(applicant_mobile_number, 20, stdin);
    printf("\n\n=======================================================================================\n");
    printf("                             [STEP 2]  Number of Students");
    printf("\n=======================================================================================\n\n");
    printf("\t\t\t      Enter Number of Students: ");
    scanf("%i", &number_of_students);
    printf("\n=======================================================================================\n\n");
    if(number_of_students > 50 && number_of_students<101){
        printf("\t\tLecture Hall :  [1] YDK1\n");
        printf("\t\t\t\t[2] YDK2\n");
        printf("\t\t\t\t[3] YDK3\n");
        printf("\t\t\t\t[4] YDK4\n");
        printf("\t\t\t\t[5] YDK5\n\n");
        printf("     Which Lecture Hall do you want to book? (1-5): \n");
        scanf("%i", &lecture_hall_book);
        switch(lecture_hall_book){
        case 1 : printf("YDK1 Confirmed");
                 strcpy(lecture_hall, "XBK1");
                 break;
        case 2 : printf("YDK2 Confirmed");
                 strcpy(lecture_hall, "XBK2");
                 break;
        case 3 : printf("YDK3 Confirmed");
                 strcpy(lecture_hall, "XBK3");
                 break;
        case 4 : printf("YDK4 Confirmed");
                 strcpy(lecture_hall, "XBK4");
                 break;
        case 5 : printf("YDK5 Confirmed");
                 strcpy(lecture_hall, "XBK5");
                 break;
        }
    } else if(number_of_students<50) {
        printf("\t\t\tLecture Room :   [1] XBK1\n");
        printf("\t\t\t\t\t [2] XBK2\n");
        printf("\t\t\t\t\t [3] XBK3\n");
        printf("\t\t\t\t\t [4] XBK4\n");
        printf("\t\t\t\t\t [5] XBK5\n");
        printf("\t\t\t\t\t [6] XBK6\n");
        printf("\t\t\t\t\t [7] XBK7\n");
        printf("\t\t\t\t\t [8] XBK8\n");
        printf("\t\t\t\t\t [9] XBK9\n");
        printf("\t\t\t\t\t[10] XBK10\n\n");
        printf("  Which Lecture Room do you want to book? (1-10): ");
        scanf("%i", &lecture_hall_book);
        switch(lecture_hall_book){
        case 1 : printf("\n\n\t\t\t\t       XBK1 CONFIRMED");
                 strcpy(lecture_room, "XBK1");
                 break;
        case 2 : printf("\n\n\t\t\t\t       XBK2 CONFIRMED");
                 strcpy(lecture_room, "XBK2");
                 break;
        case 3 : printf("\n\n\t\t\t\t       XBK3 CONFIRMED");
                 strcpy(lecture_room, "XBK3");
                 break;
        case 4 : printf("\n\n\t\t\t\t       XBK4 CONFIRMED");
                 strcpy(lecture_room, "XBK4");
                 break;
        case 5 : printf("\n\n\t\t\t\t       XBK5 CONFIRMED");
                 strcpy(lecture_room, "XBK5");
                 break;
        case 6 : printf("\n\n\t\t\t\t       XBK6 CONFIRMED");
                 strcpy(lecture_room, "XBK6");
                 break;
        case 7 : printf("\n\n\t\t\t\t       XBK7 CONFIRMED");
                 strcpy(lecture_room, "XBK7");
                 break;
        case 8 : printf("\n\n\t\t\t\t       XBK8 CONFIRMED");
                 strcpy(lecture_room, "XBK8");
                 break;
        case 9 : printf("\n\n\t\t\t\t       XBK9 CONFIRMED");
                 strcpy(lecture_room, "XBK9");
                 break;
        case 10 : printf("\n\n\t\t\t\t      XBK10 CONFIRMED");
                  strcpy(lecture_room, "XBK10");
                  break;
        default : printf("You didnt enter anything");
        }
    } else {
        printf("            There is no Lecture Hall that can fit students more than 100\n");
        printf("         Maximum is 100 students for a lecture hall and 50 for a lecture room");
      }
    if()
    printf("\n=======================================================================================\n\n");
    printf("\n                     [STEP 3]  Lecture Hall/Room Booking Date");
    printf("\n=======================================================================================\n\n");
    printf("                           Enter Booking Date: ");
    fgets(booking_date, 20, stdin);
    printf("\n\n=======================================================================================\n");
    printf("                       [STEP 4]  Lecture Hall/Room Booking Time");
    printf("\n=======================================================================================\n\n");
    printf("\n\t\t\t\tEXAMPLE (24 Hour Format)");
    printf("\n\t\t\t\t     From : 0830");
    printf("\n\t\t\t\t       To : 1030");
    printf("\n\t\t\t\t   08 ---> Hours In");
    printf("\n\t\t\t\t   30 ---> Hours Out");
    printf("\n\t\t\t\t   10 ---> Minutes In");
    printf("\n\t\t\t\t   30 ---> Minutes Out");
    return 0;
}
</code>```

答:
The lecture_room variable is of type int.
The strcpy(...) function expects char buffer as destination. You have provided int instead, so strcpy(...) will write strings into location with memory address equal to the lecture_room value. Thus, into random memory location, leading to random effects (e.g. stackoverflow, values overwrite and so on).

Body:
Below is my C code, one problem is that when I try to run it, it wont continue to printf the next statement after the switch and after I put in the input. It's a lecture hall/room booking system.If you saw, there is step 3 after the if else switch statement. It wont print out the step 3.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char applicant_name[100], applicant_faculty[100], applicant_date[40], applicant_id[50], applicant_mobile_number[20];
    int number_of_students, lecture_hall_book, lecture_room;
    char lecture_hall[20],  booking_date[20];

    printf("\n=======================================================================================\n");
    printf("                                Author : Fathul Amin\n");
    printf("                                Matric ID : CB19070\n");
    printf("=======================================================================================\n\n");
    printf("                             Universiti Malaysia Pahang\n\n");
    printf("     Welcome to the Faculty of Computing (FCOM) Lecture Hall/Room Booking System\n\n");
    printf("               For your information, this system was created to support\n");
    printf("             government initiative to reduce paper usage by replacing the \n");
    printf("                   manual application form to a computerized system \n\n\n");
    printf("                      There will be 3 STEP to apply for a booking\n\n");
    printf("\t [STEP 1] Application Information\n");
    printf("\t [STEP 2] Determine Lecture Hall/Room based on Number of Students\n");
    printf("\t [STEP 3] Lecture Hall/Room Booking Date\n\n");
    printf("\t [STEP 4] Lecture Hall/Room Booking Time\n\n");
    printf("\n=======================================================================================");
    printf("\n                [STEP 1]  Below is an example of information needed");
    printf("\n=======================================================================================\n\n");
    printf("      APPLICANT INFORMATION\n\n");
    printf("       NAME   : _____________               STAFF/STUDENT ID : ______________\n\n");
    printf("      FACULTY : _____________                 MOBILE NUMBER  : ______________\n\n");
    printf("       DATE   : _____________ (xx/xx/xxxx)\n");
    printf("\n=======================================================================================\n\n");
    printf("                         Enter Your Name  : ");
    fgets(applicant_name, 100, stdin);
    printf("                      Enter Your Faculty  : ");
    fgets(applicant_faculty, 100, stdin);
    printf("                      Enter Today's Date  : ");
    fgets(applicant_date, 40, stdin);
    printf("             Enter Your Staff/Student ID  : ");
    fgets(applicant_id, 50, stdin);
    printf("                Enter Your Mobile Number  : ");
    fgets(applicant_mobile_number, 20, stdin);
    printf("\n\n=======================================================================================\n");
    printf("                             [STEP 2]  Number of Students");
    printf("\n=======================================================================================\n\n");
    printf("\t\t\t      Enter Number of Students: ");
    scanf("%i", &number_of_students);
    printf("\n=======================================================================================\n\n");
    if(number_of_students > 50 && number_of_students<101){
        printf("\t\tLecture Hall :  [1] YDK1\n");
        printf("\t\t\t\t[2] YDK2\n");
        printf("\t\t\t\t[3] YDK3\n");
        printf("\t\t\t\t[4] YDK4\n");
        printf("\t\t\t\t[5] YDK5\n\n");
        printf("     Which Lecture Hall do you want to book? (1-5): \n");
        scanf("%i", &lecture_hall_book);
        switch(lecture_hall_book){
        case 1 : printf("YDK1 Confirmed");
                 strcpy(lecture_hall, "XBK1");
                 break;
        case 2 : printf("YDK2 Confirmed");
                 strcpy(lecture_hall, "XBK2");
                 break;
        case 3 : printf("YDK3 Confirmed");
                 strcpy(lecture_hall, "XBK3");
                 break;
        case 4 : printf("YDK4 Confirmed");
                 strcpy(lecture_hall, "XBK4");
                 break;
        case 5 : printf("YDK5 Confirmed");
                 strcpy(lecture_hall, "XBK5");
                 break;
        }
    } else if(number_of_students<50) {
        printf("\t\t\tLecture Room :   [1] XBK1\n");
        printf("\t\t\t\t\t [2] XBK2\n");
        printf("\t\t\t\t\t [3] XBK3\n");
        printf("\t\t\t\t\t [4] XBK4\n");
        printf("\t\t\t\t\t [5] XBK5\n");
        printf("\t\t\t\t\t [6] XBK6\n");
        printf("\t\t\t\t\t [7] XBK7\n");
        printf("\t\t\t\t\t [8] XBK8\n");
        printf("\t\t\t\t\t [9] XBK9\n");
        printf("\t\t\t\t\t[10] XBK10\n\n");
        printf("  Which Lecture Room do you want to book? (1-10): ");
        scanf("%i", &lecture_hall_book);
        switch(lecture_hall_book){
        case 1 : printf("\n\n\t\t\t\t       XBK1 CONFIRMED");
                 strcpy(lecture_room, "XBK1");
                 break;
        case 2 : printf("\n\n\t\t\t\t       XBK2 CONFIRMED");
                 strcpy(lecture_room, "XBK2");
                 break;
        case 3 : printf("\n\n\t\t\t\t       XBK3 CONFIRMED");
                 strcpy(lecture_room, "XBK3");
                 break;
        case 4 : printf("\n\n\t\t\t\t       XBK4 CONFIRMED");
                 strcpy(lecture_room, "XBK4");
                 break;
        case 5 : printf("\n\n\t\t\t\t       XBK5 CONFIRMED");
                 strcpy(lecture_room, "XBK5");
                 break;
        case 6 : printf("\n\n\t\t\t\t       XBK6 CONFIRMED");
                 strcpy(lecture_room, "XBK6");
                 break;
        case 7 : printf("\n\n\t\t\t\t       XBK7 CONFIRMED");
                 strcpy(lecture_room, "XBK7");
                 break;
        case 8 : printf("\n\n\t\t\t\t       XBK8 CONFIRMED");
                 strcpy(lecture_room, "XBK8");
                 break;
        case 9 : printf("\n\n\t\t\t\t       XBK9 CONFIRMED");
                 strcpy(lecture_room, "XBK9");
                 break;
        case 10 : printf("\n\n\t\t\t\t      XBK10 CONFIRMED");
                  strcpy(lecture_room, "XBK10");
                  break;
        default : printf("You didnt enter anything");
        }
    } else {
        printf("            There is no Lecture Hall that can fit students more than 100\n");
        printf("         Maximum is 100 students for a lecture hall and 50 for a lecture room");
      }
    if()
    printf("\n=======================================================================================\n\n");
    printf("\n                     [STEP 3]  Lecture Hall/Room Booking Date");
    printf("\n=======================================================================================\n\n");
    printf("                           Enter Booking Date: ");
    fgets(booking_date, 20, stdin);
    printf("\n\n=======================================================================================\n");
    printf("                       [STEP 4]  Lecture Hall/Room Booking Time");
    printf("\n=======================================================================================\n\n");
    printf("\n\t\t\t\tEXAMPLE (24 Hour Format)");
    printf("\n\t\t\t\t     From : 0830");
    printf("\n\t\t\t\t       To : 1030");
    printf("\n\t\t\t\t   08 ---> Hours In");
    printf("\n\t\t\t\t   30 ---> Hours Out");
    printf("\n\t\t\t\t   10 ---> Minutes In");
    printf("\n\t\t\t\t   30 ---> Minutes Out");
    return 0;
}


问:
npm install global vs local installing different things
When I install a package with --global I get different results than when I install it locally.

Example
Installing https://github.com/sverweij/dependency-cruiser

```<code>$ npm install --save-dev dependency-cruiser
</code>```

I get

```<code>+ dependency-cruiser@7.2.0
added 62 packages from 63 contributors and audited 491 packages in 14.511s
</code>```

And I cannot use depcruise (a command explained in the repo doc)

However

```<code>$ npm install --global dependency-cruiser
</code>```

I get

```<code>C:\Users\me\AppData\Roaming\npm\depcruise-fmt -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\depcruise-fmt.js
C:\Users\me\AppData\Roaming\npm\dependency-cruiser -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\dependency-cruise.js
C:\Users\me\AppData\Roaming\npm\depcruise -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\dependency-cruise.js
C:\Users\me\AppData\Roaming\npm\dependency-cruise -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\dependency-cruise.js
+ dependency-cruiser@7.2.0
added 115 packages from 89 contributors in 18.422s
</code>```

And then I can use depcruise

Why is this happening?

How can I get the same results (in this case the depcruise command) when doing a local installation?

Thanks,

答:
In npm, there are two ways to install things:

globally — This drops modules in {prefix}/lib/node_modules, and puts executable files in {prefix}/bin, where {prefix} is usually something like /usr/local. It also installs man pages in {prefix}/share/man, if they’re supplied.

locally — This installs your package in the current working directory. Node modules go in ./node_modules, executables go in ./node_modules/.bin/, and man pages aren’t installed at all.

That's the reason you are seeing different package size while both installation.
Reference: Node.js Doc's

Body:
When I install a package with --global I get different results than when I install it locally.

Example
Installing https://github.com/sverweij/dependency-cruiser

$ npm install --save-dev dependency-cruiser

I get

+ dependency-cruiser@7.2.0
added 62 packages from 63 contributors and audited 491 packages in 14.511s

And I cannot use depcruise (a command explained in the repo doc)

However

$ npm install --global dependency-cruiser

I get

C:\Users\me\AppData\Roaming\npm\depcruise-fmt -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\depcruise-fmt.js
C:\Users\me\AppData\Roaming\npm\dependency-cruiser -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\dependency-cruise.js
C:\Users\me\AppData\Roaming\npm\depcruise -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\dependency-cruise.js
C:\Users\me\AppData\Roaming\npm\dependency-cruise -> C:\Users\me\AppData\Roaming\npm\node_modules\dependency-cruiser\bin\dependency-cruise.js
+ dependency-cruiser@7.2.0
added 115 packages from 89 contributors in 18.422s

And then I can use depcruise

Why is this happening?

How can I get the same results (in this case the depcruise command) when doing a local installation?

Thanks,


问:
JSON package not available in anaconda
I installed python with anaconda with my computer and I need to import the JSON library.

I learned that JSON is part of the standard library of PYthon, so I am surprised that actually it is not the case with anaconda:

see:
https://docs.anaconda.com/anaconda/packages/py3.7_win-64/

```<code>import os
import pandas as pd
import shutil
import datetime
import numpy
import xml.etree.ElementTree as ET
import JSON
</code>```

result:

```<code>----> 7 import JSON

ModuleNotFoundError: No module named 'JSON'
</code>```

I tried to install JSON with pip at no luck.
And I see that in the list of Anaconda packages ther is a "JSONschema", but I rather stick to the basics.

but what strickes me the most is that a package that is supposed to be part of the standard library it is actually NOT under Anaconda. Is that right?

How would you advise me to proceed?
Is it acually possible to install JSON in/with Anaconda, JSON not being part ot the anaconda package list?

thanks

Note the reason to stick to basic libraries is that I am working in an enterprise environement with proxis and I would like others not to have to install any pacages to use my code -we are not a software company-. thanks.

答:
You have to install json package in anaconda.</p>

```<code>conda install -c jmcmurray json
</code>```

Title: JSON package not available in anaconda

Body:
I installed python with anaconda with my computer and I need to import the JSON library.

I learned that JSON is part of the standard library of PYthon, so I am surprised that actually it is not the case with anaconda:

see:
https://docs.anaconda.com/anaconda/packages/py3.7_win-64/

import os
import pandas as pd
import shutil
import datetime
import numpy
import xml.etree.ElementTree as ET
import JSON

result:

----> 7 import JSON

ModuleNotFoundError: No module named 'JSON'

I tried to install JSON with pip at no luck.
And I see that in the list of Anaconda packages ther is a "JSONschema", but I rather stick to the basics.

but what strickes me the most is that a package that is supposed to be part of the standard library it is actually NOT under Anaconda. Is that right?

How would you advise me to proceed?
Is it acually possible to install JSON in/with Anaconda, JSON not being part ot the anaconda package list?

thanks

Note the reason to stick to basic libraries is that I am working in an enterprise environement with proxis and I would like others not to have to install any pacages to use my code -we are not a software company-. thanks.

Body:
You have to install json package in anaconda.

conda install -c jmcmurray json


问:
How to subscribe a Redis channel from a React Component
How can I subscribe a redis channel inside a React Component when it is mounted (i.e, inside the componentDidMount() ) ?

In the internet almost everywhere I see the redis implementation with nodejs but can't find any
sufficient hints how to use this in React App.

Actually I want to update my ecommerce dashboard (react app) data without refreshing the page. In the backend I used djangorest framework. When any API is fired to change any data the python code doing its work and also publishes a message in a specific Redis channel.

I want to subscribe that channel from the client (react app) so that it can consume this message and update it's content real time.

答:
A react component (client technology) should not be able to access redis (server technology) for obvious security matters.

If you use react at server side to generate responses with react using node, that's node that should make this access.

If you want to access redis from a web front end (with a web browser), you must establish the following architecture:

React accesses a server using websocket and listens for messages.

The server, in node js (using socket.io) or in aspnet core (using signalR) accesses redis and communicates changes to the client thanks to websocket technology.

If you want more details about how to do, you should describe the technology stack you use at client side.

But to make it short, for client side, the best is to use the redux observable stack. In this case, that would be an epic that would update the redux state whenever the server notifies something. If you are not comfortable with rxjs (this is very understandable!), then the easiest would be to use mobX (https://mobx.js.org/README.html)


问:
Starlette + asyncio.create_task() doesn't log error if task object is stored in instance variable
Okay, this is very weird, but here goes -

import asyncio

from starlette.applications import Starlette

class MyTasks:
    def __init__(self):
        self.task = None

    async def main(self):
        self.task = asyncio.create_task(self.hello())

    async def hello(self):
        raise ValueError

async def main():
    await MyTasks().main()

app = Starlette(on_startup=[main])
```

<hr>

```$ uvicorn test:app
INFO:     Started server process [26622]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

<p>Hmm, no <code>ValueError</code> here...</p>

<hr>

<p>Now, remove the assignment to <code>self.task</code> in <code>MyTasks.main()</code>.</p>

<pre class="lang-py prettyprint-override"><code>    async def main(self):
        asyncio.create_task(self.hello())
    ...
</code>```

```<code>$ uvicorn test:app
INFO:     Started server process [29083]
INFO:     Waiting for application startup.
ERROR:    Task exception was never retrieved
future: <Task finished name='Task-3' coro=<MyTasks.hello() done, defined at ./test.py:13> exception=ValueError()>
Traceback (most recent call last):
  File "./test.py", line 14, in hello
    raise ValueError
ValueError
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
</code>```

... And voila.

What's going on here? How does that assignment make or break the exception logging!?

答:
Sorry, this was a dupe of this other question.

A drop-in replacement to asyncio.create_task() has been posted there.

Here's the output, after using the replacement create_task()

Case 1: With await self.task

```<code>$ uvicorn test:app
INFO:     Started server process [33213]
INFO:     Waiting for application startup.
ERROR:    Traceback (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 517, in lifespan
    await self.startup()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 494, in startup
    await handler()
  File "./test.py", line 35, in main
    await MyTasks().main()
  File "./test.py", line 27, in main
    print(await self.task)
  File "./test.py", line 13, in wrapper
    return await task
  File "./test.py", line 30, in hello
    raise ValueError
ValueError

ERROR:    Application startup failed. Exiting.
</code>```

Case 2: Without await self.task

```<code>$ uvicorn test:app
INFO:     Started server process [32627]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
ERROR:    Exception in callback <function create_task.<locals>.on_done at 0x10c519550>
handle: <Handle create_task.<locals>.on_done created at /Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py:382>
source_traceback: Object created at (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/bin/uvicorn", line 8, in <module>
    sys.exit(main())
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 331, in main
    run(**kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 354, in run
    server.run()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 382, in run
    loop.run_until_complete(self.serve(sockets=sockets))
Traceback (most recent call last):
  File "uvloop/cbhandles.pyx", line 70, in uvloop.loop.Handle._run
  File "./test.py", line 9, in on_done
    fut.result()
  File "./test.py", line 30, in hello
    raise ValueError
ValueError
</code>```

Body:
Okay, this is very weird, but here goes -

import asyncio

from starlette.applications import Starlette

class MyTasks:
    def __init__(self):
        self.task = None

    async def main(self):
        self.task = asyncio.create_task(self.hello())

    async def hello(self):
        raise ValueError

async def main():
    await MyTasks().main()

app = Starlette(on_startup=[main])

$ uvicorn test:app
INFO:     Started server process [26622]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Hmm, no ValueError here...

Now, remove the assignment to self.task in MyTasks.main().

    async def main(self):
        asyncio.create_task(self.hello())
    ...

$ uvicorn test:app
INFO:     Started server process [29083]
INFO:     Waiting for application startup.
ERROR:    Task exception was never retrieved
future: <Task finished name='Task-3' coro=<MyTasks.hello() done, defined at ./test.py:13> exception=ValueError()>
Traceback (most recent call last):
  File "./test.py", line 14, in hello
    raise ValueError
ValueError
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

... And voila.

What's going on here? How does that assignment make or break the exception logging!?

Body:
Sorry, this was a dupe of this other question.

A drop-in replacement to asyncio.create_task() has been posted there.

Here's the output, after using the replacement create_task()

Case 1: With await self.task

$ uvicorn test:app
INFO:     Started server process [33213]
INFO:     Waiting for application startup.
ERROR:    Traceback (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 517, in lifespan
    await self.startup()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 494, in startup
    await handler()
  File "./test.py", line 35, in main
    await MyTasks().main()
  File "./test.py", line 27, in main
    print(await self.task)
  File "./test.py", line 13, in wrapper
    return await task
  File "./test.py", line 30, in hello
    raise ValueError
ValueError

ERROR:    Application startup failed. Exiting.

Case 2: Without await self.task

$ uvicorn test:app
INFO:     Started server process [32627]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
ERROR:    Exception in callback <function create_task.<locals>.on_done at 0x10c519550>
handle: <Handle create_task.<locals>.on_done created at /Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py:382>
source_traceback: Object created at (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/bin/uvicorn", line 8, in <module>
    sys.exit(main())
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 331, in main
    run(**kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 354, in run
    server.run()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 382, in run
    loop.run_until_complete(self.serve(sockets=sockets))
Traceback (most recent call last):
  File "uvloop/cbhandles.pyx", line 70, in uvloop.loop.Handle._run
  File "./test.py", line 9, in on_done
    fut.result()
  File "./test.py", line 30, in hello
    raise ValueError
ValueError


问:
How to plot categorical data with seaborn setting the plot-style for each data column?

Background

Let's say I have the following dataset:

import pandas as pd
import numpy as np

data = ([["Cheese", x] for x in np.random.normal(0.8, 0.03, 10)] +
        [["Meat", x] for x in np.random.normal(0.4, 0.05, 14)] +
        [["Bread", 0.8], ["Bread", 0.65]])

df = pd.DataFrame(data, columns=["Food", "Score"])

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks", color_codes=True)
sns.set_context("paper")
sns.catplot(x="Score", y="Food", kind="box", data=df)
```

which yields the following plot (or similar, depending on the generated random numbers):

The reason I am going for box-plots with my actual data is that individual dots combined with the amount of categories I want to show make the plot visually way too noisy and the boxes give a nice general overview of how the data is distributed which is what I am after. However, the issue is with categories like the "Bread" category.

Question

As you can observe, seaborn produced boxes with median, quartiles etc. for all three categories. However, since the category "Bread" does only have two data-points, using a box-plot for this category is not really an appropriate representation. I would much rather have this category only as individual dots.

But when looking at the examples on the https://seaborn.pydata.org/tutorial/categorical.html, the only suggestion for combining box-plots and simple dots is to plot both for all categories which is not what I am after.

In short: How do I plot categorical data with seaborn, selecting the appropriate representation for each category?

答:
Maybe try creating df for bread and not bread:

```<code>dfb = df[df['Food'].notnull() & (df['Food'] == 'Bread')]
dfnot_b = df[df['Food'].notnull() & (df['Food'] != 'Bread')]
</code>```

then add another axis:

```<code>fig, ax = plt.subplots()
ax2 = ax.twinx()
</code>```

try different plots:

```<code>sns.boxplot(x="Score", y="Food", data=dfnot_b, ax=ax)
sns.stripplot(x="Score", y="Food", data=dfb, ax=ax2)
</code>```

Body:
Background

Let's say I have the following dataset:

import pandas as pd
import numpy as np

data = ([["Cheese", x] for x in np.random.normal(0.8, 0.03, 10)] +
        [["Meat", x] for x in np.random.normal(0.4, 0.05, 14)] +
        [["Bread", 0.8], ["Bread", 0.65]])

df = pd.DataFrame(data, columns=["Food", "Score"])

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks", color_codes=True)
sns.set_context("paper")
sns.catplot(x="Score", y="Food", kind="box", data=df)

which yields the following plot (or similar, depending on the generated random numbers):

The reason I am going for box-plots with my actual data is that individual dots combined with the amount of categories I want to show make the plot visually way too noisy and the boxes give a nice general overview of how the data is distributed which is what I am after. However, the issue is with categories like the "Bread" category.

Question

As you can observe, seaborn produced boxes with median, quartiles etc. for all three categories. However, since the category "Bread" does only have two data-points, using a box-plot for this category is not really an appropriate representation. I would much rather have this category only as individual dots.

But when looking at the examples on the https://seaborn.pydata.org/tutorial/categorical.html, the only suggestion for combining box-plots and simple dots is to plot both for all categories which is not what I am after.

In short: How do I plot categorical data with seaborn, selecting the appropriate representation for each category?

Body:
Maybe try creating df for bread and not bread:

dfb = df[df['Food'].notnull() & (df['Food'] == 'Bread')]
dfnot_b = df[df['Food'].notnull() & (df['Food'] != 'Bread')]

then add another axis:

fig, ax = plt.subplots()
ax2 = ax.twinx()

try different plots:

sns.boxplot(x="Score", y="Food", data=dfnot_b, ax=ax)
sns.stripplot(x="Score", y="Food", data=dfb, ax=ax2)


问:
The term 'update-database' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
Im using VS 2015 Community Update 3. When I try to recreate EF-driven database with command update-database in Package Manager Console, the error is displayed:

The term 'update-database' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included,  verify that the path is correct and
  try again.

I restarted VS a few times and reboot Windows OS, but no good results. Any help?
My packages.config file is:

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Cors" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Cors" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />
</packages>
</code>```

答:
With EntityFrameworkCore I had the same problem. I found this:

Just install Microsoft.EntityFrameworkCore.Tools package from nuget:

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.1

You can also use this link to install the latest version:
Nuget package link

Copied from Nasir Jafarzadeh

Body:
Im using VS 2015 Community Update 3. When I try to recreate EF-driven database with command update-database in Package Manager Console, the error is displayed:

The term 'update-database' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included,  verify that the path is correct and
  try again.

I restarted VS a few times and reboot Windows OS, but no good results. Any help?
My packages.config file is:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Cors" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.1.2" targetFramework="net45" />
  <package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Cors" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />
</packages>


问:
Unwanted Rounding in Division
I have a 20-numbers long array; I want to find the arithmetic mean of all negative numbers in the array and then deduct this number from every single element of this array.
The problem is when I try to divide the sum of the values of the negative numbers by the number of negative numbers (to find the mean) it automatically gets rounded down to the nearest integer

Here's the code:

```<code>int main()
{
    double a1 = 0.0;
    double b2 = 0.0; // arth mean
    int arr[20] = {12, -30, 23, -43, 51, 26, 0, 88, 19, -10, 11, 2, 23, -14, 15, 6, -7, 1, -19, 120};
    for(int i = 0; i < 20; i++) {
        if(arr[i] < 0) {
            a1 += arr[i]; // sum of negative numbers
        }
    }
    b2 = a1 / 6;
    cout << b2;
     for(int i = 0; i < 20; i++) {
        arr[i] = arr[i] - b2;
    }
    for(int i = 0; i < 20; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}
</code>```

答:
You are making changes in arr which is an array of type int so every floating data type will automatically change to ignore decimal points and the remaining number is int i.e int 5 = 5.9; will be equal to 5 which is the answer of your last line. Thus convert your array arr to float or double data type.

```<code> float arr[20] = {12, -30, 23, -43, 51, 26, 0, 88, 19, -10, 11, 2, 23, -14, 15, 6, -7, 1, -19, 120};
    for(int i = 0; i < 20; i++) {
        if(arr[i] < 0) {
            a1 += arr[i]; // sum of negative numbers
        }
    }
</code>```

Title: Unwanted Rounding in Division

Body:
I have a 20-numbers long array; I want to find the arithmetic mean of all negative numbers in the array and then deduct this number from every single element of this array.
The problem is when I try to divide the sum of the values of the negative numbers by the number of negative numbers (to find the mean) it automatically gets rounded down to the nearest integer

Here's the code:

int main()
{
    double a1 = 0.0;
    double b2 = 0.0; // arth mean
    int arr[20] = {12, -30, 23, -43, 51, 26, 0, 88, 19, -10, 11, 2, 23, -14, 15, 6, -7, 1, -19, 120};
    for(int i = 0; i < 20; i++) {
        if(arr[i] < 0) {
            a1 += arr[i]; // sum of negative numbers
        }
    }
    b2 = a1 / 6;
    cout << b2;
     for(int i = 0; i < 20; i++) {
        arr[i] = arr[i] - b2;
    }
    for(int i = 0; i < 20; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Body:
You are making changes in arr which is an array of type int so every floating data type will automatically change to ignore decimal points and the remaining number is int i.e int 5 = 5.9; will be equal to 5 which is the answer of your last line. Thus convert your array arr to float or double data type.

 float arr[20] = {12, -30, 23, -43, 51, 26, 0, 88, 19, -10, 11, 2, 23, -14, 15, 6, -7, 1, -19, 120};
    for(int i = 0; i < 20; i++) {
        if(arr[i] < 0) {
            a1 += arr[i]; // sum of negative numbers
        }
    }


问:
Xml Serialization - ignore parent node
I have the following class:

```<code>    public class product
    {
        public string name { get; set; }

        [XmlElement("AreaImageCaption")]
        public List<AreaImageCaption> AreaImageCaptions { get; set; }

        [XmlElement("image")]
        public List<string> images { get; set; }
    }

    public class AreaImageCaption
    {
        public string area_image { get; set; }
        public string area_caption { get; set; }
    }
</code>```

When I serialize it, it outputs the following XML:

```<code>    <?xml version="1.0"?>
    <products>
        <product>
            <name>100</name>
            <AreaImageCaption>
                <area_image>image1</area_image>
                <area_caption>caption1</area_caption>
            </AreaImageCaption>
            <AreaImageCaption>
                <area_image>image2</area_image>
                <area_caption>caption2</area_caption>
            </AreaImageCaption>
            <image>img1.jpg</image>
            <image>img2.jpg</image>
        </product>
    </products>
</code>```

But I need it to hide the "AreaImageCaption" node, so it would look like this:

```<code>    <?xml version="1.0"?>
<products>
    <product>
        <name>100</name>

        <area_image>image1</area_image>
        <area_caption>caption1</area_caption>
        <area_image>image2</area_image>
        <area_caption>caption2</area_caption>

        <image>img1.jpg</image>
        <image>img2.jpg</image>
    </product>
</products>
</code>```

Any ideas on how to accomplish this?

Thanks

答:
Just for the sake of serialization, create two more properties like your images one:

```<code>[XmlElement("area_caption")]
public List<string> area_captions
{
    get
    {
        return (from item in AreaImageCaptions select item.area_caption).ToList();
    }
}
[XmlElement("area_image")]
public List<string> area_images
{
    get
    {
        return (from item in AreaImageCaptions select item.area_image).ToList();
    }
}
</code>```

You will also need to mark your AreaImageCaptions with an [XmlIgnore] attrbute to avoid double entries.

Title: Xml Serialization - ignore parent node

Body:
I have the following class:

    public class product
    {
        public string name { get; set; }

        [XmlElement("AreaImageCaption")]
        public List<AreaImageCaption> AreaImageCaptions { get; set; }

        [XmlElement("image")]
        public List<string> images { get; set; }
    }

    public class AreaImageCaption
    {
        public string area_image { get; set; }
        public string area_caption { get; set; }
    }

When I serialize it, it outputs the following XML:

    <?xml version="1.0"?>
    <products>
        <product>
            <name>100</name>
            <AreaImageCaption>
                <area_image>image1</area_image>
                <area_caption>caption1</area_caption>
            </AreaImageCaption>
            <AreaImageCaption>
                <area_image>image2</area_image>
                <area_caption>caption2</area_caption>
            </AreaImageCaption>
            <image>img1.jpg</image>
            <image>img2.jpg</image>
        </product>
    </products>

But I need it to hide the "AreaImageCaption" node, so it would look like this:

    <?xml version="1.0"?>
<products>
    <product>
        <name>100</name>

        <area_image>image1</area_image>
        <area_caption>caption1</area_caption>
        <area_image>image2</area_image>
        <area_caption>caption2</area_caption>

        <image>img1.jpg</image>
        <image>img2.jpg</image>
    </product>
</products>

Any ideas on how to accomplish this?

Thanks

Body:
Just for the sake of serialization, create two more properties like your images one:

[XmlElement("area_caption")]
public List<string> area_captions
{
    get
    {
        return (from item in AreaImageCaptions select item.area_caption).ToList();
    }
}
[XmlElement("area_image")]
public List<string> area_images
{
    get
    {
        return (from item in AreaImageCaptions select item.area_image).ToList();
    }
}

You will also need to mark your AreaImageCaptions with an [XmlIgnore] attrbute to avoid double entries.


问:
How to copy entire content of a local disk in python 3.6?
I want to create a .py file in Python 3.6 that will copy entire local disk partition from my PC (partition D) to external hard drive(partition E). I only managed to copy folders with distutils copytree command like this:

```<code>copy_tree(r"D:\\Myfolder", "E:\\SAVE\\Myfolder", update = True)
</code>```

But I want the program to copy the entire partition with all folders subfolders and files.

Any help?

答:
I find the answer:

```<code>import distutils
from distutils.dir_util import copy_tree
copy_tree(r"D:\\", "E:\\SAVE\\Myfolder", update = True)`
</code>```

This command will copy all folders from local disk to other location.

docs

Body:
I want to create a .py file in Python 3.6 that will copy entire local disk partition from my PC (partition D) to external hard drive(partition E). I only managed to copy folders with distutils copytree command like this:

copy_tree(r"D:\\Myfolder", "E:\\SAVE\\Myfolder", update = True)

But I want the program to copy the entire partition with all folders subfolders and files.

Any help?

Body:
I find the answer:

import distutils
from distutils.dir_util import copy_tree
copy_tree(r"D:\\", "E:\\SAVE\\Myfolder", update = True)`

This command will copy all folders from local disk to other location.

docs


问:
React Native FlatList not scrolling to end
I've got (what I thought was) a simple FlatList which renders a list of Cards (code below)

Problem: the list renders, but won't scroll to fully display the last element in the list, OR to the content below the FlatList

What I've tried: basically everything in related SO questions:

Removing ALL styling

Wrapping the FlatList in a View or a ScrollView or both

Adding style={{flex: 1}} to the FlatList or wrappers (this causes **ALL* content to disappear)

Any ideas?

```<code><FlatList
        data={props.filteredProducts}
        renderItem={({item}) => (
          <TouchableOpacity onPress={() => props.addItemToCart(item)}>
            <Card
              featuredTitle={item.key}
              image={require('../assets/icon.png')}
            />
          </TouchableOpacity>
        )}
        keyExtractor={item => item.key}
        ListHeaderComponent={
          <SearchBar />
        }
      />
...
<Other Stuff>
</code>```

答: Remove flex:1 from the FlatList and leave only the parent View.</p>

Body:
I've got (what I thought was) a simple FlatList which renders a list of Cards (code below)

Problem: the list renders, but won't scroll to fully display the last element in the list, OR to the content below the FlatList

What I've tried: basically everything in related SO questions:

Removing ALL styling

Wrapping the FlatList in a View or a ScrollView or both

Adding style={{flex: 1}} to the FlatList or wrappers (this causes **ALL* content to disappear)

Any ideas?

<FlatList
        data={props.filteredProducts}
        renderItem={({item}) => (
          <TouchableOpacity onPress={() => props.addItemToCart(item)}>
            <Card
              featuredTitle={item.key}
              image={require('../assets/icon.png')}
            />
          </TouchableOpacity>
        )}
        keyExtractor={item => item.key}
        ListHeaderComponent={
          <SearchBar />
        }
      />
...
<Other Stuff>


问:
Printing JSON object using PHP
I have a JSON file and I would like to print that object in JSON:

JSON

```<code>[{"text": "Aachen, Germany - Aachen/Merzbruck (AAH)"}, {"text": "Aachen, Germany - Railway (ZIU)"}, {"text": "Aalborg, Denmark - Aalborg (AAL)"}, {"text": "Aalesund, Norway - Vigra (AES)"}, {"text": "Aarhus, Denmark - Aarhus Airport (AAR)"}, {"text": "Aarhus Limo, Denmark - Aarhus Limo (ZBU)"}, {"text": "Aasiaat, Greenland - Aasiaat (JEG)"}, {"text": "Abadan, Iran - Abadan (ABD)"}]
</code>```

I have tried with following method,

```<code><?php
  $jsonurl='http://website.com/international.json';
  $json = file_get_contents($jsonurl,0,null,null);
  $json_output = json_decode($json);
  foreach ($json_output as $trend)
  {
   echo "{$trend->text}\n";
  }
?>
</code>```

but it didn't work:

Fatal error: Call to undefined function var_dup() in /home/dddd.com/public_html/exp.php on line 5

Can anyone help me understand what I'm doing wrong?

答:
JSON_FORCE_OBJECT in your json call eg :

$obj = json_decode($data);
```

<p>Instead write like this:</p>

<pre class="lang-php prettyprint-override"><code>$obj = json_decode($data, JSON_FORCE_OBJECT);
</code>```

Title: Printing JSON object using PHP

Body:
I have a JSON file and I would like to print that object in JSON:

JSON

[{"text": "Aachen, Germany - Aachen/Merzbruck (AAH)"}, {"text": "Aachen, Germany - Railway (ZIU)"}, {"text": "Aalborg, Denmark - Aalborg (AAL)"}, {"text": "Aalesund, Norway - Vigra (AES)"}, {"text": "Aarhus, Denmark - Aarhus Airport (AAR)"}, {"text": "Aarhus Limo, Denmark - Aarhus Limo (ZBU)"}, {"text": "Aasiaat, Greenland - Aasiaat (JEG)"}, {"text": "Abadan, Iran - Abadan (ABD)"}]

I have tried with following method,

<?php
  $jsonurl='http://website.com/international.json';
  $json = file_get_contents($jsonurl,0,null,null);
  $json_output = json_decode($json);
  foreach ($json_output as $trend)
  {
   echo "{$trend->text}\n";
  }
?>

but it didn't work:

Fatal error: Call to undefined function var_dup() in /home/dddd.com/public_html/exp.php on line 5

Can anyone help me understand what I'm doing wrong?

Body:
JSON_FORCE_OBJECT in your json call eg :

$obj = json_decode($data);

Instead write like this:

$obj = json_decode($data, JSON_FORCE_OBJECT);


问:
Migrate legacy database to cqrs/event sourcing view
We got old legacy application with complex business logic which we need to rewrite. We consider to use cqrs and event sourcing. But it's not clear how to migrate data from the old database. Probable we need migrate it to the read database only, as we can't reproduce all the events to populate event store. But we atleast need to create some initial records in event store for each aggregate, like AggregateCreated? Or we need write a scripts and to use all the commands one by one to recreate aggregates in same way we will normally with event sourcing?

答:
Using the existing database, or a transformed version of it, as a start of your read-side persistence is never a good idea. Your event-sourced system needs to have its start, so you get one of the main benefits of event sourcing - being able to create projections on-demand, using polyglot persistence.

Using commands for migration is also not a good idea for a simple reason that commands, by definition, can fail due to pre or post-condition check of invariant control. It also does not convey the meaning of migration, which is to represent the current system state as it is right now. Remember, that the current system stay is not something you can accept or deny. It is given to you and your job is to capture it.

The best practice for such a migration is to emit so-called migration events, like EntityXMigratedFromLegacy. Of course, the work might be substantial. Mainly because the legacy system model will most probably not match the new model, otherwise the reason for such a migration isn't entirely clear.

By using migration events you explicitly state the fact that a piece of state was moved from another place, as-is. You will always know how the migrated entity started its lifecycle in the new system - either by being migrated from legacy or by being initialised in the new system.


问:
Multiple Hosts for single bus in MassTransit
Just realised that with V6 of MassTransit the support for multiple hosts in a single bus was removed. Is there maybe a different solution to implement it.

Our use case is to listen to the same queues on 2 different hosts. Consume messages and respond only using RespondAsync, my understanding is that it can resolve back to the originating default response queue automatically.

Thank You,

答:
As of MassTransit v6, there is no way to configure multiple hosts for a single bus instance.

In your situation, you should create two bus instances, one for each host, and configure the same consumers on each instance.


答:
I just ran the code locally and it does spit out -20.5. The full output is this:

```<code>-20.532 -9 43 -22 71 46 20 108 39 10 31 22 43 6 35 26 13 21 1 140
</code>```

Perhaps your confusion is that you are not adding whitespace after the first number? Try

```<code>cout << b2 << " ";
</code>```

Instead and maybe it will be more clear. Note also that when doing this:

```<code>arr[i] = arr[i] - b2;
</code>```

The RHS is a float and gets truncated when stored in arr[i]. To avoid this, make arr an array of floats rather than ints.

Title: Unwanted Rounding in Division

Body:
I just ran the code locally and it does spit out -20.5. The full output is this:

-20.532 -9 43 -22 71 46 20 108 39 10 31 22 43 6 35 26 13 21 1 140

Perhaps your confusion is that you are not adding whitespace after the first number? Try

cout << b2 << " ";

Instead and maybe it will be more clear. Note also that when doing this:

arr[i] = arr[i] - b2;

The RHS is a float and gets truncated when stored in arr[i]. To avoid this, make arr an array of floats rather than ints.


问:
Python Pydantic - how to have an "optional" field but if present required to conform to not None value?
I am trying to validate an object that has "optional" fields in the sense that they may or may not be present.  But when they are present, the fields should conform to a specific type definition (not None).

In the example below, the "size" field is optional but allows None.  I want the "size" field to be optional, but if present it should be a float.

```<code>from pydantic import BaseModel

class Foo(BaseModel):
    count: int
    size: float = None  # how to make this an optional float?

 >>> Foo(count=5)
 Foo(count=5, size=None)  # GOOD - "size" is not present, value of None is OK

 >>> Foo(count=5, size=None)
 Foo(count=5, size=None) # BAD - if field "size" is present, it should be a float

 # BONUS
 >>> Foo(count=5)
 Foo(count=5)  # BEST - "size" is not present, it is not required to be present, so we don't care about about validating it all.  We are using Foo.json(exclude_unset=True) handles this for us which is fine.
</code>```

答:
It's possible to do with a validator.

from pydantic import BaseModel, ValidationError, validator

class Foo(BaseModel):
    count: int
    size: float = None

    @validator('size')
    def size_is_some(cls, v):
        if v is None:
            raise ValidationError('Cannot set size to None')
        return float(v)
```
<p>This works as intended:</p>
<pre class="lang-py prettyprint-override"><code>>>> Foo(count=5)
Foo(count=5, size=None)

>>> Foo(count=5, size=1.6)
Foo(count=5, size=1.6)

>>> Foo(count=5, size=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[venv]/lib/python3.6/site-packages/pydantic/main.py", line 283, in __init__
    raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for Foo
size
  Cannot set size to None (type=value_error)
</code>```

Body:
I am trying to validate an object that has "optional" fields in the sense that they may or may not be present.  But when they are present, the fields should conform to a specific type definition (not None).

In the example below, the "size" field is optional but allows None.  I want the "size" field to be optional, but if present it should be a float.

from pydantic import BaseModel

class Foo(BaseModel):
    count: int
    size: float = None  # how to make this an optional float?

 >>> Foo(count=5)
 Foo(count=5, size=None)  # GOOD - "size" is not present, value of None is OK

 >>> Foo(count=5, size=None)
 Foo(count=5, size=None) # BAD - if field "size" is present, it should be a float

 # BONUS
 >>> Foo(count=5)
 Foo(count=5)  # BEST - "size" is not present, it is not required to be present, so we don't care about about validating it all.  We are using Foo.json(exclude_unset=True) handles this for us which is fine.

Body:
It's possible to do with a validator.

from pydantic import BaseModel, ValidationError, validator

class Foo(BaseModel):
    count: int
    size: float = None

    @validator('size')
    def size_is_some(cls, v):
        if v is None:
            raise ValidationError('Cannot set size to None')
        return float(v)

This works as intended:

>>> Foo(count=5)
Foo(count=5, size=None)

>>> Foo(count=5, size=1.6)
Foo(count=5, size=1.6)

>>> Foo(count=5, size=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[venv]/lib/python3.6/site-packages/pydantic/main.py", line 283, in __init__
    raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for Foo
size
  Cannot set size to None (type=value_error)


问:
javax.xml.rpc.JAXRPCException: java.io.IOException at time of calling web service
Hello
i have Login web service in .Net and calling it from my
J2ME web service client.

it was working perfect and code was working
but as today i started my project and calling same

it is giving me error like

```<code>javax.xml.rpc.JAXRPCException: java.io.IOException: Error initializing HTTP tunnel connection:
HTTP/1.0 403 Forbidden
Content-type: text/html
Server: Muffin/0.9.3a

        at com.sun.j2mews.xml.rpc.OperationImpl.invoke(OperationImpl.java:283)
        at com.aa.stubs.aa_Stub.complaintList(aa_Stub.java:199)
        at com.aa.gui.form.LoginForm$LoginFormListener.getComplainList(LoginForm.java:128)
        at com.aa.gui.form.LoginForm$LoginFormListener$1.run(LoginForm.java:102)
</code>```

same code is working on different pc

i had test other web service available on web they are even giving same error.

i am using ubantu 9.04
i had test it on win xp as well as on fedora where it is working

what could be problem??

答:
i found the solution.

my net beans was set to system proxy and i check my company's server setting
where on proxy networking was not allowed.

i just set my net beans with no proxy and problem is solved.

Body:
Hello
i have Login web service in .Net and calling it from my
J2ME web service client.

it was working perfect and code was working
but as today i started my project and calling same

it is giving me error like

javax.xml.rpc.JAXRPCException: java.io.IOException: Error initializing HTTP tunnel connection:
HTTP/1.0 403 Forbidden
Content-type: text/html
Server: Muffin/0.9.3a

        at com.sun.j2mews.xml.rpc.OperationImpl.invoke(OperationImpl.java:283)
        at com.aa.stubs.aa_Stub.complaintList(aa_Stub.java:199)
        at com.aa.gui.form.LoginForm$LoginFormListener.getComplainList(LoginForm.java:128)
        at com.aa.gui.form.LoginForm$LoginFormListener$1.run(LoginForm.java:102)

same code is working on different pc

i had test other web service available on web they are even giving same error.

i am using ubantu 9.04
i had test it on win xp as well as on fedora where it is working

what could be problem??


问:
How to access files from assets folder during tests execution?
How to access files from assets folder during unit tests execution? My project is build using Gradle, I use Robolectric to run tests. It seems like gradle is being recognizing the assets:

This is how I'm struggling to read the file:

```<code>public String readFileFromAssets(String fileName) throws IOException {
    InputStream stream = getClass().getClassLoader().getResourceAsStream("assets/" + fileName);
    Preconditions.checkNotNull(stream, "Stream is null");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    return IOUtils.toString(reader);
}
</code>```

But stream is always null. I tried it many different ways, i.e. defined path to a file using different approaches.

Thank you very much in advance.

答:
If you are using Kotlin, you can have something like this:

```<code>getInstrumentation().targetContext.assets.open("news.json")
</code>```

instead of .context, you can simply use targetContext

Body:
How to access files from assets folder during unit tests execution? My project is build using Gradle, I use Robolectric to run tests. It seems like gradle is being recognizing the assets:

This is how I'm struggling to read the file:

public String readFileFromAssets(String fileName) throws IOException {
    InputStream stream = getClass().getClassLoader().getResourceAsStream("assets/" + fileName);
    Preconditions.checkNotNull(stream, "Stream is null");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    return IOUtils.toString(reader);
}

But stream is always null. I tried it many different ways, i.e. defined path to a file using different approaches.

Thank you very much in advance.

Body:
If you are using Kotlin, you can have something like this:

getInstrumentation().targetContext.assets.open("news.json")

instead of .context, you can simply use targetContext