问:
How to change the datetime format in Pandas
My dataframe has a DOB column (example format 1/1/2016) which by default gets converted to Pandas dtype 'object'.

Converting this to date format with df['DOB'] = pd.to_datetime(df['DOB']), the date gets converted to: 2016-01-26 and its dtype is: datetime64[ns].

Now I want to convert this date format to 01/26/2016 or any other general date format. How do I do it?

(Whatever the method I try, it always shows the date in 2016-01-26 format.)

答:
There is a difference between

the content of a dataframe cell (a binary value) and

its presentation (displaying it) for us, humans.

So the question is: How to reach the appropriate presentation of my data without changing the data / data types themselves?

Here is the answer:

If you use the Jupyter notebook for displaying your dataframe, or

if you want to reach a presentation in the form of an HTML file (even with many prepared superfluous id and class attributes for further CSS styling — you may or you may not use them),

use styling. Styling don't change data / data types of columns of your dataframe.

Now I show you how to reach it in the Jupyter notebook — for a presentation in the form of HTML file see the note near the end of this answer.

I will suppose that your column DOB already has the datetime64 type (you have shown that you know how to reach it). I prepared a simple dataframe (with only one column) to show you some basic styling:

Not styled:

```<code>df
</code>```

```<code>          DOB
0  2019-07-03
1  2019-08-03
2  2019-09-03
3  2019-10-03
</code>```

Styling it as mm/dd/yyyy:

```<code>df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
</code>```

```<code>          DOB
0  07/03/2019
1  08/03/2019
2  09/03/2019
3  10/03/2019
</code>```

Styling it as dd-mm-yyyy:

```<code>df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")})
</code>```

```<code>          DOB
0  03-07-2019
1  03-08-2019
2  03-09-2019
3  03-10-2019
</code>```

Be careful!

The returning object is NOT a dataframe — it is an object of the class Styler, so don't assign it back to df:

Don't do this:

```<code>df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})    # Don't do this!
</code>```

(Every dataframe has its Styler object accessible by its .style property, and we changed this df.style object, not the dataframe itself.)

Questions and Answers:

Q: Why your Styler object (or an expression returning it) used as the last command in a Jupyter notebook cell displays your (styled) table, and not the Styler object itself?

A: Because every Styler object has a callback method ._repr_html_() which returns an HTML code for rendering your dataframe (as a nice HTML table).

Jupyter Notebook IDE calls this method automatically to render objects which have it.

Note:

You don't need the Jupyter notebook for styling (i.e., for nice outputting a dataframe without changing its data / data types).

A Styler object has a method render(), too, if you want to obtain a string with the HTML code (e.g., for publishing your formatted dataframe on the Web, or simply present your table in the HTML format):

```<code>df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()
</code>```

Body:
There is a difference between

the content of a dataframe cell (a binary value) and

its presentation (displaying it) for us, humans.

So the question is: How to reach the appropriate presentation of my data without changing the data / data types themselves?

Here is the answer:

If you use the Jupyter notebook for displaying your dataframe, or

if you want to reach a presentation in the form of an HTML file (even with many prepared superfluous id and class attributes for further CSS styling — you may or you may not use them),

use styling. Styling don't change data / data types of columns of your dataframe.

Now I show you how to reach it in the Jupyter notebook — for a presentation in the form of HTML file see the note near the end of this answer.

I will suppose that your column DOB already has the datetime64 type (you have shown that you know how to reach it). I prepared a simple dataframe (with only one column) to show you some basic styling:

Not styled:

df

          DOB
0  2019-07-03
1  2019-08-03
2  2019-09-03
3  2019-10-03

Styling it as mm/dd/yyyy:

df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})

          DOB
0  07/03/2019
1  08/03/2019
2  09/03/2019
3  10/03/2019

Styling it as dd-mm-yyyy:

df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")})

          DOB
0  03-07-2019
1  03-08-2019
2  03-09-2019
3  03-10-2019

Be careful!

The returning object is NOT a dataframe — it is an object of the class Styler, so don't assign it back to df:

Don't do this:

df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})    # Don't do this!

(Every dataframe has its Styler object accessible by its .style property, and we changed this df.style object, not the dataframe itself.)

Questions and Answers:

Q: Why your Styler object (or an expression returning it) used as the last command in a Jupyter notebook cell displays your (styled) table, and not the Styler object itself?

A: Because every Styler object has a callback method ._repr_html_() which returns an HTML code for rendering your dataframe (as a nice HTML table).

Jupyter Notebook IDE calls this method automatically to render objects which have it.

Note:

You don't need the Jupyter notebook for styling (i.e., for nice outputting a dataframe without changing its data / data types).

A Styler object has a method render(), too, if you want to obtain a string with the HTML code (e.g., for publishing your formatted dataframe on the Web, or simply present your table in the HTML format):

df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()


来源: stackexchange

问:
awk convert number to date format to select line bigger than specific mmyy
INPUT:

```<code>test,1120,1
test,1219,2
</code>```

Expected Output

```<code>test,1120,1
</code>```

Goal: trying to print line where $2 which is mmyy format is bigger than 1020 as example.

I've tried with the following:

awk -F, '{ if ( $2 > 1020 ) { print $0 }}' file that's will not give the expected output because it's still number etc.. 1219 is bigger than 1020.

答:
EDIT: Since OP mentioned that now if dates require lesser than provided input in that case one could try following.

```<code>awk -v val="1020" '
BEGIN{
  FS=OFS=","
  user_year=substr(val,3)
  user_month=substr(val,1,2)
}
{
  year=substr($2,3)
  month=substr($2,1,2)
  if(year==user_year){
   if(month<user_month){
     print
   }
  }
  else if(year<user_year){
     print
  }
}
' Input_file
</code>```

Could you please try following. I have create a variable named val here which will have value which user needs to compare to all the lines of Input_file. In this case it is set to 1020

```<code>awk -v val="1020" '
BEGIN{
  FS=OFS=","
  user_year=substr(val,3)
  user_month=substr(val,1,2)
}
{
  year=substr($2,3)
  month=substr($2,1,2)
  if(year==user_year){
    if(month>user_month){
      print
    }
  }
  if(year>user_year){
      print
  }
}
' Input_file
</code>```

ContentLicense: CC BY-SA 4.0

Body:
INPUT:

test,1120,1
test,1219,2

Expected Output

test,1120,1

Goal: trying to print line where $2 which is mmyy format is bigger than 1020 as example.

I've tried with the following:

awk -F, '{ if ( $2 > 1020 ) { print $0 }}' file that's will not give the expected output because it's still number etc.. 1219 is bigger than 1020.

Body:
EDIT: Since OP mentioned that now if dates require lesser than provided input in that case one could try following.

awk -v val="1020" '
BEGIN{
  FS=OFS=","
  user_year=substr(val,3)
  user_month=substr(val,1,2)
}
{
  year=substr($2,3)
  month=substr($2,1,2)
  if(year==user_year){
   if(month<user_month){
     print
   }
  }
  else if(year<user_year){
     print
  }
}
' Input_file

Could you please try following. I have create a variable named val here which will have value which user needs to compare to all the lines of Input_file. In this case it is set to 1020

awk -v val="1020" '
BEGIN{
  FS=OFS=","
  user_year=substr(val,3)
  user_month=substr(val,1,2)
}
{
  year=substr($2,3)
  month=substr($2,1,2)
  if(year==user_year){
    if(month>user_month){
      print
    }
  }
  if(year>user_year){
      print
  }
}
' Input_file


问:
Round to nearest multiple of a number
Is there an idiomatic way to round to the nearest multiple of a number, short of rounding both up and down and seeing which one is closest?

Assume only integers:

```<code>number   multiple   result
12       5          10
13       5          15
149      10         150
</code>```

答:
I've answered this before on Rounding off a number to the next nearest multiple of 5

With using cmath::abs

```<code>int rounded = n + abs((n % denom) - denom);
</code>```

You can change denom with any denomination you want

ContentLicense: CC BY-SA 3.0

Title: Round to nearest multiple of a number

Body:
Is there an idiomatic way to round to the nearest multiple of a number, short of rounding both up and down and seeing which one is closest?

Assume only integers:

number   multiple   result
12       5          10
13       5          15
149      10         150

Body:
I've answered this before on Rounding off a number to the next nearest multiple of 5

With using cmath::abs

int rounded = n + abs((n % denom) - denom);

You can change denom with any denomination you want


问:
Why do some CPUs have different instructions to do signed and unsigned operations?
Let's assume we have the following binary numbers with their representation:

```<code>| bin | unsigned | signed   |
|:---:|----------|----------|
| 110 | 6        | -2       |
| 111 | 7        | -1       |
</code>```

Now regardless if signed or unsigned, 111 + 110 = 1101,
Now I can interpret the result 1101 as signed or unsigned which is:

```<code>| bin  | unsigned | signed   |
|:----:|----------|----------|
| 1101 | 13       | -3       |
</code>```

Which matches the decimal operation:

```<code>6+7 = 13
-1-2 = -3
</code>```

There was no difference between doing a signed addition or unsigned addition. So why would CPUs have different circuits/instructions for such operation?

答:
It depends on the binary representation. This is a major point of 2s-complement representation -- when using 2s complement, signed and unsigned addition, subtraction, and mulitplication of fixed-width operands and same width results are identical, so you can use the same hardware instructions for both.

If you use 1s complement or sign magnitude, you need slight differences between signed and unsigned operations.

Division is different here, as are widening operations.

Body:
Let's assume we have the following binary numbers with their representation:

| bin | unsigned | signed   |
|:---:|----------|----------|
| 110 | 6        | -2       |
| 111 | 7        | -1       |

Now regardless if signed or unsigned, 111 + 110 = 1101,
Now I can interpret the result 1101 as signed or unsigned which is:

| bin  | unsigned | signed   |
|:----:|----------|----------|
| 1101 | 13       | -3       |

Which matches the decimal operation:

6+7 = 13
-1-2 = -3

There was no difference between doing a signed addition or unsigned addition. So why would CPUs have different circuits/instructions for such operation?


问:
I am trying to insert records into a an object list but nothing gets inserted when I call the method. What am I doing wrong?
I'm attempting to insert data into a list using a method but nothing I attempt to insert shows up after I call the method. Can someone tell me what I'm doing wrong? I'm calling InsertMedicationOrder.

```<code>    private List<Medication> Meds;

    private List<MedOrder> MedOrder_;

    public FakeMedicationAccessor()
    {
        MedOrder_ = new List<MedOrder>()
        {
            new MedOrder(){}
        };
    }

    public int InsertMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
    {
        MedOrder_.Add(GetMedicationOrder(orderID, employeeID, itemID, itemName, quantity));

        return 0;
    }

    public MedOrder GetMedicationOrder(int orderID, int employeeID, int itemID,string itemName, int quantity)
    {
        return new MedOrder
        {
            outgoingOrderID = orderID,
            employeeID = employeeID,
            itemID = itemID,
            itemName = itemName,
            quantityOrdered = quantity,
            itemCategoryID = "Medication"
        };
    }
</code>```

The method is passed into here-

```<code>public bool CreateMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
{
    bool result = false;
    try
    {
        result = (1 == _activityAccessor.InsertMedicationOrder(orderID, employeeID, itemID, itemName, quantity));
    }
    catch (System.ApplicationException ex)
    {
        throw new ApplicationException("Meds not ordered", ex);
    }
    return result;
}
</code>```

And called here

```<code>public void OrderMedications()
{
    _medicationManager = new MedicationManager();
    int orderID = 1;
    int employeeID = 66;
    int itemID = 1;
    string itemName = "Med_A";

    _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
}
</code>```

Instantiation of FakeMedicationAccessor

```<code>  private IMedicationAccessor _activityAccessor;

    public MedicationManager()
    {
        _activityAccessor = new FakeMedicationAccessor();

    }

    public MedicationManager(IMedicationAccessor MedicationManager)
    {
        _activityAccessor = MedicationManager;

    }
</code>```

答:
You returns 0 from InsertMedicationOrder and you compare it with 1

```<code>1 == _activityAccessor.InsertMedicationOrder(orderID, employeeID, itemID, itemName, quantity));
</code>```

1 == 0 will always be false.

Return 1 or

```<code>var before = MedOrder_.Count
MedOrder_.Add(...);
return MedOrder_.Count - before;
</code>```

to check if an element is added to your list.

Edit:

Here is what happens in your code

Whenever you call InsertMedication(), an element is added to your
list. This is a fact.

Whenever you call CreateMedicationOrder(), it returns false, but your
list has grown. This is a fact.

You could check it after the line _medicationManager.CreateMedicationOrder() and will see by yourself, like:

var currentSize = _medicationManager.MedOrder_.Count;
which wouldn't compile, because MedOrder_ is private which is a good practice if you don't just keep calling OrderMedications() because:

Whenever you call OrderMedications(), this list is gone because of you
tell _medicationManager to point to a completely new object by the code:

_medicationManager = new MedicationManager();

So assuming you are not doing this completely crazy thing to call OrderMedications() you indeed have a lot of items in your list! (by calling InsertMedication() multiple times) BUT I don't see any code, that checks that list for emptyness or for elements within or even code to check the count. So I propose you should look at the list to see what it contains For example, use foreach. Create a new function inside FakeMedicationAccessor class:

```<code>void ReadMedicationOrders()
{
    foreach(var item in MedOrder_)
        Console.WriteLine(item.itemName);  //if it is a console application
}
</code>```

In case

you do only calling OrderMedications() (let say from you Main), then you need to initialize _medicationManager only once in your other class. So write this to the top of your class:

```<code>MedicationManager _medicationManager = new MedicationManager();
</code>```

and get rid of re-initialization within your function. Delete the line I commented out:

```<code>public void OrderMedications()
{
    //_medicationManager = new MedicationManager();
    int orderID = 1;
    int employeeID = 66;
    int itemID = 1;
    string itemName = "Med_A";

    _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
}
</code>```

You may also need to change MedOrder_ inside FakeMedicationAccessor class to internal or public, or create a new function (inside FakeMedicationAccessor), like:

```<code>void PrintMedicationOrders()
{
    //do your logic here similar to ReadMedicationOrders()
}
</code>```

Body:
I'm attempting to insert data into a list using a method but nothing I attempt to insert shows up after I call the method. Can someone tell me what I'm doing wrong? I'm calling InsertMedicationOrder.

    private List<Medication> Meds;

    private List<MedOrder> MedOrder_;

    public FakeMedicationAccessor()
    {
        MedOrder_ = new List<MedOrder>()
        {
            new MedOrder(){}
        };
    }

    public int InsertMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
    {
        MedOrder_.Add(GetMedicationOrder(orderID, employeeID, itemID, itemName, quantity));

        return 0;
    }

    public MedOrder GetMedicationOrder(int orderID, int employeeID, int itemID,string itemName, int quantity)
    {
        return new MedOrder
        {
            outgoingOrderID = orderID,
            employeeID = employeeID,
            itemID = itemID,
            itemName = itemName,
            quantityOrdered = quantity,
            itemCategoryID = "Medication"
        };
    }

The method is passed into here-

public bool CreateMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
{
    bool result = false;
    try
    {
        result = (1 == _activityAccessor.InsertMedicationOrder(orderID, employeeID, itemID, itemName, quantity));
    }
    catch (System.ApplicationException ex)
    {
        throw new ApplicationException("Meds not ordered", ex);
    }
    return result;
}

And called here

public void OrderMedications()
{
    _medicationManager = new MedicationManager();
    int orderID = 1;
    int employeeID = 66;
    int itemID = 1;
    string itemName = "Med_A";

    _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
}

Instantiation of FakeMedicationAccessor

  private IMedicationAccessor _activityAccessor;

    public MedicationManager()
    {
        _activityAccessor = new FakeMedicationAccessor();

    }

    public MedicationManager(IMedicationAccessor MedicationManager)
    {
        _activityAccessor = MedicationManager;

    }

Body:
You returns 0 from InsertMedicationOrder and you compare it with 1

1 == _activityAccessor.InsertMedicationOrder(orderID, employeeID, itemID, itemName, quantity));

1 == 0 will always be false.

Return 1 or

var before = MedOrder_.Count
MedOrder_.Add(...);
return MedOrder_.Count - before;

to check if an element is added to your list.

Edit:

Here is what happens in your code

Whenever you call InsertMedication(), an element is added to your
list. This is a fact.

Whenever you call CreateMedicationOrder(), it returns false, but your
list has grown. This is a fact.

You could check it after the line _medicationManager.CreateMedicationOrder() and will see by yourself, like:

var currentSize = _medicationManager.MedOrder_.Count;
which wouldn't compile, because MedOrder_ is private which is a good practice if you don't just keep calling OrderMedications() because:

Whenever you call OrderMedications(), this list is gone because of you
tell _medicationManager to point to a completely new object by the code:

_medicationManager = new MedicationManager();

So assuming you are not doing this completely crazy thing to call OrderMedications() you indeed have a lot of items in your list! (by calling InsertMedication() multiple times) BUT I don't see any code, that checks that list for emptyness or for elements within or even code to check the count. So I propose you should look at the list to see what it contains For example, use foreach. Create a new function inside FakeMedicationAccessor class:

void ReadMedicationOrders()
{
    foreach(var item in MedOrder_)
        Console.WriteLine(item.itemName);  //if it is a console application
}

In case

you do only calling OrderMedications() (let say from you Main), then you need to initialize _medicationManager only once in your other class. So write this to the top of your class:

MedicationManager _medicationManager = new MedicationManager();

and get rid of re-initialization within your function. Delete the line I commented out:

public void OrderMedications()
{
    //_medicationManager = new MedicationManager();
    int orderID = 1;
    int employeeID = 66;
    int itemID = 1;
    string itemName = "Med_A";

    _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
}

You may also need to change MedOrder_ inside FakeMedicationAccessor class to internal or public, or create a new function (inside FakeMedicationAccessor), like:

void PrintMedicationOrders()
{
    //do your logic here similar to ReadMedicationOrders()
}


问:
Background color to Navbar links
I have already defined my Navbar and it works perfectly fine, except I want to give a full page background to the Navbar links as well. Currently when I want to open the page on a mobile device, the links background doesn't cover the whole page horizontally, but instead it looks like a highlighted line. For more detail see the screenshots. I would appreciate if someone can help me with this. Thanks!

  <button class="navbar-toggler ml-auto custom-toggler" type="button" data-toggle="collapse" data-target="#collapsingNavbar4">

      </button>

         Portfolio

        About

        Contact

        Resume

        &nbsp&nbsp&nbsp

        &nbsp&nbsp&nbsp

        &nbsp&nbsp&nbsp

[![enter image description here][1]][1]
```

答:
You could try this:</p>

```<code><nav class="navbar navbar-expand-sm navbar-light fixed-top p-0">
</code>```

Title: Background color to Navbar links

Body:
You could try this:

<nav class="navbar navbar-expand-sm navbar-light fixed-top p-0">


问:
How to resolve an async function from within a settimeout
How do I write this code using async, await only:</p>

```<code>new Promise((resolve, reject) => {
 setTimeout(() => {
   resolve(‘done’)
 }, 1000)
}
</code>```

答:
You can't. What async and await do is they can replace .thens, eg:

```<code>function foo(someProm) {
  return someProm.then(() => {
    console.log('someProm done');
  });
}
</code>```

can turn into

```<code>async function foo(someProm) {
  await someProm;
  console.log('someProm done');
}
</code>```

They can also automatically wrap their return value in a Promise if the return value is synchronous - eg

```<code>async function foo() {
  return '2';
}
</code>```

will return a Promise which resolves to 2.

But async and await cannot replace the generic Promise constructor. If you have a callback-based API, and you want a Promise that resolves when the callback finishes, you can't use async and await for that task - you must use new Promise as you're doing here.

There's one exception which is barely worth mentioning, and should not be used. In the particular case of setTimeout, when nothing else needs to be done between the time the Promise is created and when it resolves, it's theoretically possible to create an async function which blocks for however many seconds you need, and then resolves:

console.log('start');

// Putting this in a setTimeout so that "start" logs above
// before the below code starts blocking
setTimeout(() => {
  const theProm = (async () => {
    const t0 = performance.now();
    while (performance.now() - t0 < 1000);
  })();

  theProm.then(() => {
    console.log('done');
  });
}, 100);```

(For informational purposes only. Do not use that code)

Body:
How do I write this code using async, await only:

new Promise((resolve, reject) => {
 setTimeout(() => {
   resolve(‘done’)
 }, 1000)
}

Body:
You can't. What async and await do is they can replace .thens, eg:

function foo(someProm) {
  return someProm.then(() => {
    console.log('someProm done');
  });
}

can turn into

async function foo(someProm) {
  await someProm;
  console.log('someProm done');
}

They can also automatically wrap their return value in a Promise if the return value is synchronous - eg

async function foo() {
  return '2';
}

will return a Promise which resolves to 2.

But async and await cannot replace the generic Promise constructor. If you have a callback-based API, and you want a Promise that resolves when the callback finishes, you can't use async and await for that task - you must use new Promise as you're doing here.

There's one exception which is barely worth mentioning, and should not be used. In the particular case of setTimeout, when nothing else needs to be done between the time the Promise is created and when it resolves, it's theoretically possible to create an async function which blocks for however many seconds you need, and then resolves:

console.log('start');

// Putting this in a setTimeout so that "start" logs above
// before the below code starts blocking
setTimeout(() => {
  const theProm = (async () => {
    const t0 = performance.now();
    while (performance.now() - t0 < 1000);
  })();

  theProm.then(() => {
    console.log('done');
  });
}, 100);

(For informational purposes only. Do not use that code)


问:
Getting URL hash location, and using it in jQuery
I'd like to get the value after a hash in the URL of the current page and then be able to apply this in a new function... eg.

The URL could be

```<code>www.example.com/index.html#foo
</code>```

And I would like to use this in conjunction with the following piece of code

```<code>$('ul#foo:first').show();
</code>```

I'm kinda assuming/hoping there is some way of grabbing this, and turning it into a variable that I can then use in the second piece of code.

答:
I'm using this to address the security implications noted in @CMS's answer.</p>

```<code>// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});
</code>```

Body:
I'd like to get the value after a hash in the URL of the current page and then be able to apply this in a new function... eg.

The URL could be

www.example.com/index.html#foo

And I would like to use this in conjunction with the following piece of code

$('ul#foo:first').show();

I'm kinda assuming/hoping there is some way of grabbing this, and turning it into a variable that I can then use in the second piece of code.

Body:
I'm using this to address the security implications noted in @CMS's answer.

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});


问:
How to check if all items in a list are of the same type?
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Edit:

I've now tried combining a couple of the answers into a section of the code:

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

答:
The best way  is to actually cast the value into the type you want in a "try/catch".

So if you want to check for integer you would do it like this:

try:
    val = int(Value1)
 except ValueError:
    print("This is not a number... Please write a real value")

You can do the same for float etc as well.

Also you could use isdigit()

```<code>if(Value1.isdigit()):
   print("Finally, it's a number!")
else:
   print("Type a real number please!")
</code>```

Body:
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Edit:

I've now tried combining a couple of the answers into a section of the code:

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

Body:
The best way  is to actually cast the value into the type you want in a "try/catch".

So if you want to check for integer you would do it like this:

try:
    val = int(Value1)
 except ValueError:
    print("This is not a number... Please write a real value")

You can do the same for float etc as well.

Also you could use isdigit()

if(Value1.isdigit()):
   print("Finally, it's a number!")
else:
   print("Type a real number please!")


问:
maxlength ignored for input type="number" in Chrome
The maxlength attribute is not working with <input type="number">. This happens only in Chrome.

```<code><input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>
</code>```

答:
<input type="number"> is just that... a number input (albeit, unconverted from a string to float via Javascript).

My guess, it doesn't restrict characters on key input by maxLength or else your user could be stuck in a "key trap" if they forgot a decimal at the beginning (Try putting a . at index 1 when an <input type"text"> "maxLength" attr has already been reached). It will however validate on form submit if you set a max attribute.

If you're trying to restrict/validate a phone number, use the type="tel" attr/value. It obeys the maxLength attr and brings up the mobile number keyboard only (in modern browsers) and you can restrict input to a pattern (i.e. pattern="[0-9]{10}").

Body:
The maxlength attribute is not working with <input type="number">. This happens only in Chrome.

<input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>


问:
Docker (node:8.15-alpine) + Chromium + Karma unit tests not working
I'm trying to run my frontend tests on Docker (node:8.15-alpine) using Chromium and Karma, however I'm getting lots of ChromeHeadless related errors.

These tests used to work but recently they suddenly stopped, so I'm guessing it's either related to a third-party dependency (apk?), or the local Docker install.

I've created a branch on the repo with an easy to run command which reproduces the issue. README.md here:
https://github.com/olivercaine/react-redux-starter-kit-extended/tree/bug/cant-run-unit-tests-in-docker

Any help with this would be masively appreciated!

Thanks.

Expected Outcome:

```<code>[output of passed tests...]
Finished in 0.026 secs / 0.031 secs @ 19:53:44 GMT+1100 (AEDT)
SUMMARY:
✔ 46 tests completed
</code>```

Actual Outcome:

13 02 2020 09:10:45.314:ERROR [launcher]: Cannot start ChromeHeadless

13 02 2020 09:10:45.316:ERROR [launcher]: ChromeHeadless stdout:
13 02 2020 09:10:45.317:ERROR [launcher]: ChromeHeadless stderr:
13 02 2020 09:10:45.772:ERROR [launcher]: Cannot start ChromeHeadless

13 02 2020 09:10:45.772:ERROR [launcher]: ChromeHeadless stdout:
13 02 2020 09:10:45.773:ERROR [launcher]: ChromeHeadless stderr:
13 02 2020 09:10:45.939:ERROR [launcher]: Cannot start ChromeHeadless

13 02 2020 09:10:45.939:ERROR [launcher]: ChromeHeadless stdout:
13 02 2020 09:10:45.939:ERROR [launcher]: ChromeHeadless stderr:
13 02 2020 09:10:46.424:ERROR [launcher]: ChromeHeadless failed 2 times (cannot start). Giving up.

Finished in 0 secs / 0 secs @ 09:10:46 GMT+0000 (UTC)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react-redux-starter-kit@3.0.1 test: `cross-env NODE_ENV=test karma start build/karma.config`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react-redux-starter-kit@3.0.1 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-02-13T09_10_46_935Z-debug.log
```

Update:

The above URL has been removed, however the full (now working) repo can be found here:

https://github.com/olivercaine/react-redux-starter-kit-extended/tree/modpack/latest

答:
Thanks Baptiste, your answer helped me verify the fix was working.
Basically what I ended up doing was using a different URL for alpinelinux.org.

In the end I changed the Dockerfile to:

```<code>FROM node:8.15-alpine

WORKDIR /project

# Install Chrome
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories \
    && echo http://dl-cdn.alpinelinux.org/alpine/edge/main >> /etc/apk/repositories \
    && echo http://dl-cdn.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories \
    && apk --no-cache update && apk --no-cache upgrade \
    && apk add --no-cache chromium \
    && rm -rf /var/cache/apk/* /tmp/*

ENV CHROME_BIN /usr/bin/chromium-browser
</code>```

which seemed to set the CHROME_BIN env variable properly, allowing me to run my tests in the Alpine container. Also meant I didn't need to update the karma.config.js file either. Previously I was using nl.alpinelinux.org/alpine/v3.8/ instead of edge.

Cheers for your help!

Body:
I'm trying to run my frontend tests on Docker (node:8.15-alpine) using Chromium and Karma, however I'm getting lots of ChromeHeadless related errors.

These tests used to work but recently they suddenly stopped, so I'm guessing it's either related to a third-party dependency (apk?), or the local Docker install.

I've created a branch on the repo with an easy to run command which reproduces the issue. README.md here:
https://github.com/olivercaine/react-redux-starter-kit-extended/tree/bug/cant-run-unit-tests-in-docker

Any help with this would be masively appreciated!

Thanks.

Expected Outcome:

[output of passed tests...]
Finished in 0.026 secs / 0.031 secs @ 19:53:44 GMT+1100 (AEDT)
SUMMARY:
✔ 46 tests completed

Actual Outcome:

13 02 2020 09:10:45.314:ERROR [launcher]: Cannot start ChromeHeadless

13 02 2020 09:10:45.316:ERROR [launcher]: ChromeHeadless stdout:
13 02 2020 09:10:45.317:ERROR [launcher]: ChromeHeadless stderr:
13 02 2020 09:10:45.772:ERROR [launcher]: Cannot start ChromeHeadless

13 02 2020 09:10:45.772:ERROR [launcher]: ChromeHeadless stdout:
13 02 2020 09:10:45.773:ERROR [launcher]: ChromeHeadless stderr:
13 02 2020 09:10:45.939:ERROR [launcher]: Cannot start ChromeHeadless

13 02 2020 09:10:45.939:ERROR [launcher]: ChromeHeadless stdout:
13 02 2020 09:10:45.939:ERROR [launcher]: ChromeHeadless stderr:
13 02 2020 09:10:46.424:ERROR [launcher]: ChromeHeadless failed 2 times (cannot start). Giving up.

Finished in 0 secs / 0 secs @ 09:10:46 GMT+0000 (UTC)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react-redux-starter-kit@3.0.1 test: `cross-env NODE_ENV=test karma start build/karma.config`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react-redux-starter-kit@3.0.1 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-02-13T09_10_46_935Z-debug.log

Update:

The above URL has been removed, however the full (now working) repo can be found here:

https://github.com/olivercaine/react-redux-starter-kit-extended/tree/modpack/latest

Body:
Thanks Baptiste, your answer helped me verify the fix was working.
Basically what I ended up doing was using a different URL for alpinelinux.org.

In the end I changed the Dockerfile to:

FROM node:8.15-alpine

WORKDIR /project

# Install Chrome
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories \
    && echo http://dl-cdn.alpinelinux.org/alpine/edge/main >> /etc/apk/repositories \
    && echo http://dl-cdn.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories \
    && apk --no-cache update && apk --no-cache upgrade \
    && apk add --no-cache chromium \
    && rm -rf /var/cache/apk/* /tmp/*

ENV CHROME_BIN /usr/bin/chromium-browser

which seemed to set the CHROME_BIN env variable properly, allowing me to run my tests in the Alpine container. Also meant I didn't need to update the karma.config.js file either. Previously I was using nl.alpinelinux.org/alpine/v3.8/ instead of edge.

Cheers for your help!


问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答:
If you are going to head the "don't throw an exception route" (which I am not necessarily reccomending), you could follow the TryParse approach MS uses.

Something like:

```<code>private string FillDataTable(out DataTable results)
{

  try
{
  results = new DataTable(); //something like this;
  return String.Empty;
}
catch (Exception ex)
{
  results = null;
 return ex.Message;

}
</code>```

}

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

Body:
If you are going to head the "don't throw an exception route" (which I am not necessarily reccomending), you could follow the TryParse approach MS uses.

Something like:

private string FillDataTable(out DataTable results)
{

  try
{
  results = new DataTable(); //something like this;
  return String.Empty;
}
catch (Exception ex)
{
  results = null;
 return ex.Message;

}

}

OwnerDisplayName: Kevin


问:
How to create multilines legend in Data Studio
In Data Studio my 10 points pie chart is like below:

As you can see there is a navigation arrow in the legend at the top of the pie.

I wonder how can I avoid the navigation by creating the multiline legend? How can I wrap the current single line legend?

答:
Three ways to display all items in the legend; located in the Style Tab of the Pie Chart (added a GIF to elaborate):

Increasing the max lines;

Increasing the width of the Pie Chart;

Reducing the font size of the legend.

EDIT: Multi line Legend (Workaround using a Bar Chart)

How about using the legend from a Bar Chart? Added a GIF to elaborate as well as a few points:

Bar Chart: Use a Dimension and Breakdown Dimension that's the same as the one on the Pie Chart and enable the legend (Top) as well as using 2 lines (no legend for the Pie Chart)

Shape: Add a Shape over the Bar Chart (one that blends in with the background)

Order: Right click on components and select Order from the drop down to change the order of the components (Bar Chart: Send to back; Shape: Send Backwards (behind the Pie Chart); Pie Chart: Bring to Front)

Fine Tuning: Use Shift + Movement for precision placement (to get the shape exactly where you want it)


问:
Eclipse won't compile SWT file properly after SFTP transfer
I was coding earlier today using Textastic 9 on my iPhone today using files I had downloaded over SFTP. I sent them back to my computer (the whole project transferred to my phone), and now three of the four work. They compile correctly, and the colour coding works perfectly. The last one, however, only colour codes specific keywords and strings. It won't accept variable names and anything from a separate library/file, say org.eclipse.swt.SWT.

Here's a screenshot of that file:

Here's another file that also went through SFTP that's working perfectly:

I'm also getting the error Syntax error on tokens, SimpleName expected on a return; statement. I've also tried pasting the code in Notepad, deleting the file, and pasting it into a new file. That doesn't work.

Thanks to @Ros5292

It turns out the display() method had parameters with incorrect capitalisation. I fixed this, clicked on the Design tab, selected the root method, and it compiles. It still doesn't allow me to use other files, color code, etc.

答:
Thanks to @Ros5292

It turns out the display() method had parameters with incorrect capitalisation. I fixed this, clicked on the Design tab, selected the root method, and it works. The colour coding and stuff were messed up due to a few errors because the file was technically new, and it hadn't compiled properly for the first time ever.


问:
Install opencv with conda
This question is different from "How do I install Python OpenCV through Conda?" because that question was asked more than 5 years ago, when all packages had different versions.  I tried ALL answers to that question, and neither worked.  See the text of question for details.

How to install opencv with conda now, in July 2019?  On a freshly installed anaconda, I did conda update conda (succesfully) then tried the following:

```<code>(base) C:\Users\mlearning>python
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv'

(base) C:\Users\mlearning>conda install -c menpo opencv3
Collecting package metadata (repodata.json): done
Solving environment: (goes into infinite loop, after 10 minutes I pressed ^C)

(base) C:\Users\mlearning>conda install opencv
Collecting package metadata (repodata.json): done
Solving environment: failed
Initial quick solve with frozen env failed.  Unfreezing env and trying again.
Solving environment: failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Package zipp conflicts for:
importlib_metadata -> zipp[version='>=0.3.2']
path.py -> importlib_metadata[version='>=0.5'] -> zipp[version='>=0.3.2']
anaconda==2019.03=py37_0 -> importlib_metadata==0.8=py37_0 -> zipp[version='>=0.3.2']
zipp
Package importlib_metadata conflicts for:
anaconda==2019.03=py37_0 -> importlib_metadata==0.8=py37_0
path.py -> importlib_metadata[version='>=0.5']
Package hdf5 conflicts for:
anaconda==2019.03=py37_0 -> h5py==2.9.0=py37h5e291fa_0 -> hdf5[version='>=1.10.4,<1.10.5.0a0']
hdf5
opencv -> hdf5[version='>=1.10.2,<1.10.3.0a0,>=1.8.18,<1.8.19.0a0,>=1.8.20,<1.9.0a0']
h5py -> hdf5[version='>=1.10.1,<1.10.2.0a0,>=1.10.2,<1.10.3.0a0,>=1.10.4,<1.10.5.0a0,>=1.8.18,<1.9.0a0']
pytables -> hdf5[version='>=1.10.1,<1.10.2.0a0,>=1.8.18,<1.8.19.0a0,>=1.8.18,<1.9.0a0']
Package mkl-service conflicts for:
mkl-service
anaconda==2019.03=py37_0 -> mkl-service==1.1.2=py37hb782905_5

(base) C:\Users\mlearning>conda install -c conda-forge opencv
Collecting package metadata (repodata.json): done
Solving environment: failed
Initial quick solve with frozen env failed.  Unfreezing env and trying again.
Solving environment: failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Package hdf5 conflicts for:
anaconda==2019.03=py37_0 -> hdf5==1.10.4=h7ebc959_0
h5py -> hdf5[version='1.10.1,1.8.17|1.8.17.*,1.8.18|1.8.18.*,>=1.10.2,<1.10.3.0a0,>=1.10.3,<1.10.4.0a0,>=1.8.20,<1.9.0a0']
pytables -> hdf5[version='1.8.18|1.8.18.*,>=1.10.4,<1.10.5.0a0,>=1.8.18,<1.8.19.0a0,>=1.8.18,<1.9.0a0']
hdf5
Package mkl-service conflicts for:
mkl-service
Package importlib_metadata conflicts for:
importlib_metadata
path.py -> importlib_metadata[version='>=0.5']
</code>```

答:
I faced a similar issue. Installed it with the following and it is working for me:

```<code>pip install opencv-python
</code>```

The pypi for the above is at https://pypi.org/project/opencv-python/

Title: Install opencv with conda

Body:
This question is different from "How do I install Python OpenCV through Conda?" because that question was asked more than 5 years ago, when all packages had different versions.  I tried ALL answers to that question, and neither worked.  See the text of question for details.

How to install opencv with conda now, in July 2019?  On a freshly installed anaconda, I did conda update conda (succesfully) then tried the following:

(base) C:\Users\mlearning>python
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv'

(base) C:\Users\mlearning>conda install -c menpo opencv3
Collecting package metadata (repodata.json): done
Solving environment: (goes into infinite loop, after 10 minutes I pressed ^C)

(base) C:\Users\mlearning>conda install opencv
Collecting package metadata (repodata.json): done
Solving environment: failed
Initial quick solve with frozen env failed.  Unfreezing env and trying again.
Solving environment: failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Package zipp conflicts for:
importlib_metadata -> zipp[version='>=0.3.2']
path.py -> importlib_metadata[version='>=0.5'] -> zipp[version='>=0.3.2']
anaconda==2019.03=py37_0 -> importlib_metadata==0.8=py37_0 -> zipp[version='>=0.3.2']
zipp
Package importlib_metadata conflicts for:
anaconda==2019.03=py37_0 -> importlib_metadata==0.8=py37_0
path.py -> importlib_metadata[version='>=0.5']
Package hdf5 conflicts for:
anaconda==2019.03=py37_0 -> h5py==2.9.0=py37h5e291fa_0 -> hdf5[version='>=1.10.4,<1.10.5.0a0']
hdf5
opencv -> hdf5[version='>=1.10.2,<1.10.3.0a0,>=1.8.18,<1.8.19.0a0,>=1.8.20,<1.9.0a0']
h5py -> hdf5[version='>=1.10.1,<1.10.2.0a0,>=1.10.2,<1.10.3.0a0,>=1.10.4,<1.10.5.0a0,>=1.8.18,<1.9.0a0']
pytables -> hdf5[version='>=1.10.1,<1.10.2.0a0,>=1.8.18,<1.8.19.0a0,>=1.8.18,<1.9.0a0']
Package mkl-service conflicts for:
mkl-service
anaconda==2019.03=py37_0 -> mkl-service==1.1.2=py37hb782905_5

(base) C:\Users\mlearning>conda install -c conda-forge opencv
Collecting package metadata (repodata.json): done
Solving environment: failed
Initial quick solve with frozen env failed.  Unfreezing env and trying again.
Solving environment: failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Package hdf5 conflicts for:
anaconda==2019.03=py37_0 -> hdf5==1.10.4=h7ebc959_0
h5py -> hdf5[version='1.10.1,1.8.17|1.8.17.*,1.8.18|1.8.18.*,>=1.10.2,<1.10.3.0a0,>=1.10.3,<1.10.4.0a0,>=1.8.20,<1.9.0a0']
pytables -> hdf5[version='1.8.18|1.8.18.*,>=1.10.4,<1.10.5.0a0,>=1.8.18,<1.8.19.0a0,>=1.8.18,<1.9.0a0']
hdf5
Package mkl-service conflicts for:
mkl-service
Package importlib_metadata conflicts for:
importlib_metadata
path.py -> importlib_metadata[version='>=0.5']

Body:
I faced a similar issue. Installed it with the following and it is working for me:

pip install opencv-python

The pypi for the above is at https://pypi.org/project/opencv-python/


问:
react handler array from axios
How I handle the value array from Axios and fill the card
get the value from the array and show data

```<code>import React, { Component, Suspense } from "react";
import axios from "axios";

import {Card} from "reactstrap";

import { PHP } from "../../constants";

//api url adress server
const api = PHP;
const reqtoken = "Bearer " + localStorage.getItem("token");

class Property extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  load() {
    axios
      .get(api + "api/property", {
        headers: {
          "Content-type": "application/json",
          Authorization: reqtoken
        }
      })
</code>```

insert the data array on the state

```<code>      .then(json => {

</code>```

console.log show the data on console terminal

```<code>        console.log(json.data.data.data);
        this.setState({
          data: json.data.data.data
        });
      })
      .catch(erros => {
        console.log(erros);
      });
  }
  componentDidMount() {
    this.load();
  }

  render() {
    return (
      <div>
</code>```

map the array to handle the result................

```<code>        {this.state.data.map(i => (
          <Card>
            <li>{i.address}</li>
          </Card>
        ))}
      </div>
    );
  }
}
export default Property;

</code>```

didn't make me a wrong error console

答:
I don't know how the response data comes in, but I found a problem with the code. You should pass keys.

{this.state.data.map(item => (
  <Card key={item.id}>

{item.address}

  </Card>
))}
```

https://reactjs.org/docs/lists-and-keys.html#keys

Title: react handler array from axios

Body:
How I handle the value array from Axios and fill the card
get the value from the array and show data

import React, { Component, Suspense } from "react";
import axios from "axios";

import {Card} from "reactstrap";

import { PHP } from "../../constants";

//api url adress server
const api = PHP;
const reqtoken = "Bearer " + localStorage.getItem("token");

class Property extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  load() {
    axios
      .get(api + "api/property", {
        headers: {
          "Content-type": "application/json",
          Authorization: reqtoken
        }
      })

insert the data array on the state

      .then(json => {

console.log show the data on console terminal

        console.log(json.data.data.data);
        this.setState({
          data: json.data.data.data
        });
      })
      .catch(erros => {
        console.log(erros);
      });
  }
  componentDidMount() {
    this.load();
  }

  render() {
    return (

map the array to handle the result................

        {this.state.data.map(i => (
          <Card>

{i.address}

          </Card>
        ))}

    );
  }
}
export default Property;

didn't make me a wrong error console

Body:
I don't know how the response data comes in, but I found a problem with the code. You should pass keys.

{this.state.data.map(item => (
  <Card key={item.id}>
    <li>{item.address}</li>
  </Card>
))}

https://reactjs.org/docs/lists-and-keys.html#keys


问:
Is there a built-in Python function or module that will sum digits multiplied by their integer weight?
What I need to do is take a 10-digit ISBN number and check if it's valid, according to this rule:

According to the 2001 edition of the International ISBN Agency's official user manual,[47] the ISBN-10 check digit (which is the last digit of the 10-digit ISBN) must range from 0 to 10 (the symbol 'X' is used for 10), and must be such that the sum of the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.

In other words, if the number is 0-306-40615-2, I need to calculate:

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1) mod 11

While suggestions or hints on how to write such a function are welcome, my main question is simply whether Python already has a way of doing this, perhaps in the math module.

This is my attempt, but the for loops don't work because the inner one keeps starting over. Plus it just seems messy!

```<code>    checksum = 0
    for digit in isbn:
        for weight in range(10, 0, -1):
            if digit == 'X':
                checksum += 10 * weight
                break
            checksum += int(digit) * weight
            break
    return checksum % 11```
```

答:
If the number is 0-306-40615-2, and you need to calculate if

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1)

is a multiple of 11, then you can just write a simple function.

```<code>def check_isbn(isbn): #isbn should be type str
    isbn = "".join(isbn.split("-"))
    sum = (int(isbn[0]) * 10) + (int(isbn[1]) * 9) + (int(isbn[2]) * 8) + (int(isbn[3]) * 7) + (int(isbn[4]) * 6) + (int(isbn[5]) * 5) + (int(isbn[6]) * 4) + (int(isbn[7]) * 3) + (int(isbn[8]) * 2) + (int(isbn[9]) * 1)
    return sum % 11 == 0

check_isbn("1416406110")
# False

check_isbn("0-306-40615-2")
# True
</code>```

Body:
What I need to do is take a 10-digit ISBN number and check if it's valid, according to this rule:

According to the 2001 edition of the International ISBN Agency's official user manual,[47] the ISBN-10 check digit (which is the last digit of the 10-digit ISBN) must range from 0 to 10 (the symbol 'X' is used for 10), and must be such that the sum of the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.

In other words, if the number is 0-306-40615-2, I need to calculate:

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1) mod 11

While suggestions or hints on how to write such a function are welcome, my main question is simply whether Python already has a way of doing this, perhaps in the math module.

This is my attempt, but the for loops don't work because the inner one keeps starting over. Plus it just seems messy!

    checksum = 0
    for digit in isbn:
        for weight in range(10, 0, -1):
            if digit == 'X':
                checksum += 10 * weight
                break
            checksum += int(digit) * weight
            break
    return checksum % 11```

Body:
If the number is 0-306-40615-2, and you need to calculate if

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1)

is a multiple of 11, then you can just write a simple function.

def check_isbn(isbn): #isbn should be type str
    isbn = "".join(isbn.split("-"))
    sum = (int(isbn[0]) * 10) + (int(isbn[1]) * 9) + (int(isbn[2]) * 8) + (int(isbn[3]) * 7) + (int(isbn[4]) * 6) + (int(isbn[5]) * 5) + (int(isbn[6]) * 4) + (int(isbn[7]) * 3) + (int(isbn[8]) * 2) + (int(isbn[9]) * 1)
    return sum % 11 == 0

check_isbn("1416406110")
# False

check_isbn("0-306-40615-2")
# True


问:
Xamarin Drag and drop with a drop zone
I am trying to implement drag and drop to create a grammatical exercise in which you have to complete the sentence with the right word, dragging the right answer in the right spot (as shown in figure below).

I tried to achieve that by using custom renderer, creating some extended native views that override the methods to implement their dragging and dropping (like OnTouchEvent for Android, and TouchesBegan, TouchesMoved, TouchesEnded for iOS). In both platform I am able to drag the custom native views, but only in iOS I am able to drop them into the specific destination view that I want. In Android it seems to be a conflict with Xamarin Forms view coordinates and the native Android coordinates used in the android custom renderer. Even if I try to "adjust" them, (by manually inserting the coordinates that I want the view to be dropped in) it seems like that the check if(destinationRect.Contains(myTouchX, myTouchY) doesn't work proper.

Git repository example here: Git example

Does anyone know how to solve that?
Or does anyone know how to implement drag and drop (with a proper dropzone to check) in any other easiest way?

答:
In Android, it provide the View.StartDrag(ClipData, View+DragShadowBuilder, Object, Int32) Method method to start a drag and drop operation.

You could check the MS document.

View.StartDrag(ClipData, View+DragShadowBuilder, Object, Int32) Method:
https://learn.microsoft.com/en-us/dotnet/api/android.views.view.startdrag?view=xamarin-android-sdk-9

View.StartDragAndDrop(ClipData, View+DragShadowBuilder, Object, Int32) Method:
https://learn.microsoft.com/en-us/dotnet/api/android.views.view.startdraganddrop?view=xamarin-android-sdk-9

Based on my search, this blog would be helpful for this method.
https://pumpingco.de/blog/adding-drag-and-drop-to-your-android-application-with-xamarin/

You could download the source file from the GitHub.
https://github.com/Pumpingcode/Xamarin-DragAndDropDemo

Title: Xamarin Drag and drop with a drop zone


问:
How can I read a header from an http request in golang?
If I receive a request of type http.Request, how can I read the value of a specific header? In this case I want to pull the value of a jwt token out of the request header.

答:
Note: The accepted answer is missing some information.

A Header represents the key-value pairs in an HTTP header.
It's defined as a map where key is of string type and value is an array of string type.

```<code>type Header map[string][]string
</code>```

Actually, r.Header.Get gets the first value associated with the given key i.e. it just gets the first string from index 0.

This is okay if your header just have one value but if it has multiple values, you may miss out on some information.

Eg. User-Agent header has multiple values against the same key.

```<code>user-agent: ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)",  "AppleWebKit/537.36 (KHTML, like Gecko)", "Chrome/80.0.3987.106 Safari/537.36",]
</code>```

So if you use r.Header.get("User-Agent") , it'll return Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) only and not the rest of the values.

If you want to get all the values you can use this:

```<code>req.Header["User-Agent"]
</code>```

Body:
Note: The accepted answer is missing some information.

A Header represents the key-value pairs in an HTTP header.
It's defined as a map where key is of string type and value is an array of string type.

type Header map[string][]string

Actually, r.Header.Get gets the first value associated with the given key i.e. it just gets the first string from index 0.

This is okay if your header just have one value but if it has multiple values, you may miss out on some information.

Eg. User-Agent header has multiple values against the same key.

user-agent: ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)",  "AppleWebKit/537.36 (KHTML, like Gecko)", "Chrome/80.0.3987.106 Safari/537.36",]

So if you use r.Header.get("User-Agent") , it'll return Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) only and not the rest of the values.

If you want to get all the values you can use this:

req.Header["User-Agent"]


问:
How do you check current view controller class in Swift?
As far as I know, this would work in Objective-C:

```<code>self.window.rootViewController.class == myViewController
</code>```

How can I check if the current view controller is a specific one?

答:
Swift 4, Swift 5</p>

```<code>let viewController = UIApplication.shared.keyWindow?.rootViewController
if viewController is MyViewController {

}
</code>```

Body:
As far as I know, this would work in Objective-C:

self.window.rootViewController.class == myViewController

How can I check if the current view controller is a specific one?

Body:
Swift 4, Swift 5

let viewController = UIApplication.shared.keyWindow?.rootViewController
if viewController is MyViewController {

}


问:
SwiftUI Edit Item From List Using CoreData
I am working on a list app and would like the ability to edit the list item details.  I am using CoreData for the data model.  Right now I am stuck on how to pass the data item from the DetailView to the EditItemView. I updated to the code to the current state I am at.  I am currently getting an error in the DetailView taged to the DetailView(myItem: item) line the preview. Am I setting the @State correctly for name and passing the @Binding correctly?  I think my error lies in the way I am passing the name in EditItemView(name: self.$name) to the edit view.  Thoughts?

Detail View:

```<code>import CoreData
import SwiftUI

struct DetailView: View {
    @Environment(\.managedObjectContext) var moc
    @ObservedObject var myItem: Item

    @State private var name: String
    @State private var showingEditScreen = false

    var body: some View {
        NavigationView {
            VStack {
                Text(self.myItem.name ?? "Unknown Item")
                Text(self.myItem.attribute ?? "Unknown attribute")
            }
        }
        .navigationBarTitle(Text(myItem.name ?? "Unknown Item"), displayMode: .inline)
        .navigationBarItems(trailing:
            Button(action: {
                self.showingEditScreen.toggle()
            }) {
                Image(systemName: "square.and.pencil")
            }
        )
        .sheet(isPresented: $showingEditScreen) {
            EditItemView(name: self.$name).environment(\.managedObjectContext, self.moc)
        }
    }
}

struct DetailView_Previews: PreviewProvider {
    static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

    static var previews: some View {
        let item = Item(context: moc)
        item.name = "Test item"
        item.attribute = "Test attribute"

        return NavigationView {
            DetailView(myItem: item)
        }
    }
}
</code>```

Edit Item View:

```<code>import CoreData
import SwiftUI

struct EditItemView: View {
    @Binding var name: String

    var body: some View {
        TextField("Enter Item Name", text: self.$name)
    }
}

struct EditItemView_Previews: PreviewProvider {
    static var previews: some View {
        EditItemView(name: .constant("ItemX"))
    }
}
</code>```

答:
I would say the Item or a NSManagedObject is an ObservableObject.

so you can directly use an item in a View:

```<code> struct EditItemView: View  {

     @ObservedObject var myItem : Item

      var body: some View {
       ...}

 }
</code>```

Body:
I am working on a list app and would like the ability to edit the list item details.  I am using CoreData for the data model.  Right now I am stuck on how to pass the data item from the DetailView to the EditItemView. I updated to the code to the current state I am at.  I am currently getting an error in the DetailView taged to the DetailView(myItem: item) line the preview. Am I setting the @State correctly for name and passing the @Binding correctly?  I think my error lies in the way I am passing the name in EditItemView(name: self.$name) to the edit view.  Thoughts?

Detail View:

import CoreData
import SwiftUI

struct DetailView: View {
    @Environment(\.managedObjectContext) var moc
    @ObservedObject var myItem: Item

    @State private var name: String
    @State private var showingEditScreen = false

    var body: some View {
        NavigationView {
            VStack {
                Text(self.myItem.name ?? "Unknown Item")
                Text(self.myItem.attribute ?? "Unknown attribute")
            }
        }
        .navigationBarTitle(Text(myItem.name ?? "Unknown Item"), displayMode: .inline)
        .navigationBarItems(trailing:
            Button(action: {
                self.showingEditScreen.toggle()
            }) {
                Image(systemName: "square.and.pencil")
            }
        )
        .sheet(isPresented: $showingEditScreen) {
            EditItemView(name: self.$name).environment(\.managedObjectContext, self.moc)
        }
    }
}

struct DetailView_Previews: PreviewProvider {
    static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

    static var previews: some View {
        let item = Item(context: moc)
        item.name = "Test item"
        item.attribute = "Test attribute"

        return NavigationView {
            DetailView(myItem: item)
        }
    }
}

Edit Item View:

import CoreData
import SwiftUI

struct EditItemView: View {
    @Binding var name: String

    var body: some View {
        TextField("Enter Item Name", text: self.$name)
    }
}

struct EditItemView_Previews: PreviewProvider {
    static var previews: some View {
        EditItemView(name: .constant("ItemX"))
    }
}

Body:
I would say the Item or a NSManagedObject is an ObservableObject.

so you can directly use an item in a View:

 struct EditItemView: View  {

     @ObservedObject var myItem : Item

      var body: some View {
       ...}

 }


问:
Missing Claims via JWT Web Token
I have the following code that creates a JWT token in a webapi core application.

```<code>var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

                var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username!=null?userInfo.Username:string.Empty),
                    new Claim(JwtRegisteredClaimNames.Email, userInfo.Email!=null?userInfo.Email:string.Empty),
                    new Claim(JwtRegisteredClaimNames.Jti, userInfo.AccountId!=null?userInfo.AccountId.ToString():Guid.Empty.ToString()),
                    new Claim(JwtRegisteredClaimNames.NameId, userInfo.UserId!=null?userInfo.UserId.ToString():Guid.Empty.ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, userInfo.ClientId!=null?userInfo.ClientId.ToString():Guid.Empty.ToString())
                };

                var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                  _config["Jwt:Issuer"],
                  claims,
                  null,
                  expires: DateTime.Now.AddMinutes(20),
                  signingCredentials: credentials);

                return new JwtSecurityTokenHandler().WriteToken(token);
</code>```

However when I try to get the claims back after the client has called a webapi end point, I only have the following claims. As you can see the "JTI" claim is fine, but the "UniqueName" claim is missing.

```<code>[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: }
    [1]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: }
    [2]: {jti: f7c5af77-d0c4-4026-9b33-2fe9fbf5ee28}
    [3]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: 00000000-0000-0000-0000-000000000000}
    [4]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: b34a1b42-df24-42a3-93d7-68e88523602f}
    [5]: {exp: 1581973428}
    [6]: {iss: Test.com}
    [7]: {aud: Test.com}
</code>```

What do I need to do to get the claim to appear?

Just to note that the claim that I set as JwtRegisteredClaimNames.UniqueName does appear in the claims but not under that name. Its value is set under the item

```<code>[4]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: b34a1b42-df24-42a3-93d7-68e88523602f}
</code>```

However this is not brought back when use the following as it is null

```<code>identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;
</code>```

答:
However this is not brought back when use the following as it is null

identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;

To fix the above issue, you can try to clear the inbound claim type map using following code snippet in Startup.cs

```<code>System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
</code>```

Test Result

Set testing value for JwtRegisteredClaimNames.UniqueName

```<code>//just for testing purpose

new Claim(JwtRegisteredClaimNames.UniqueName, "b34a1b42-df24-42a3-93d7-68e88523602f")
</code>```

Can get expected value using identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value

Title: Missing Claims via JWT Web Token

Body:
I have the following code that creates a JWT token in a webapi core application.

var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

                var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username!=null?userInfo.Username:string.Empty),
                    new Claim(JwtRegisteredClaimNames.Email, userInfo.Email!=null?userInfo.Email:string.Empty),
                    new Claim(JwtRegisteredClaimNames.Jti, userInfo.AccountId!=null?userInfo.AccountId.ToString():Guid.Empty.ToString()),
                    new Claim(JwtRegisteredClaimNames.NameId, userInfo.UserId!=null?userInfo.UserId.ToString():Guid.Empty.ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, userInfo.ClientId!=null?userInfo.ClientId.ToString():Guid.Empty.ToString())
                };

                var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                  _config["Jwt:Issuer"],
                  claims,
                  null,
                  expires: DateTime.Now.AddMinutes(20),
                  signingCredentials: credentials);

                return new JwtSecurityTokenHandler().WriteToken(token);

However when I try to get the claims back after the client has called a webapi end point, I only have the following claims. As you can see the "JTI" claim is fine, but the "UniqueName" claim is missing.

[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: }
    [1]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: }
    [2]: {jti: f7c5af77-d0c4-4026-9b33-2fe9fbf5ee28}
    [3]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: 00000000-0000-0000-0000-000000000000}
    [4]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: b34a1b42-df24-42a3-93d7-68e88523602f}
    [5]: {exp: 1581973428}
    [6]: {iss: Test.com}
    [7]: {aud: Test.com}

What do I need to do to get the claim to appear?

Just to note that the claim that I set as JwtRegisteredClaimNames.UniqueName does appear in the claims but not under that name. Its value is set under the item

[4]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: b34a1b42-df24-42a3-93d7-68e88523602f}

However this is not brought back when use the following as it is null

identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;

Body:
However this is not brought back when use the following as it is null

identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;

To fix the above issue, you can try to clear the inbound claim type map using following code snippet in Startup.cs

System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

Test Result

Set testing value for JwtRegisteredClaimNames.UniqueName

//just for testing purpose

new Claim(JwtRegisteredClaimNames.UniqueName, "b34a1b42-df24-42a3-93d7-68e88523602f")

Can get expected value using identity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value


问:
Data not showing up in sharepoint list as well as in drop downs
hi
i have a problem at my production site, client reported that he is not seeing data in lists of sharepoint, as well drop downs which have years in pages of site appear empty with one user A on machin X having with windows 7. but data and comes up and drop downs are now populated when accessed from machine Y with same user A.

i dont knw wht really the problem is. As to development site this issue is not produced,
plz help,

thnks in advance

答: Windows 7 or xp has nothing to do over here probably it has to do with the browser which he is using to browse the site ask him to chk the internet explorer settings and verify that he has enabled execution of javascript and other related things</p>


问:
Is there a better way to WaitForSeconds?
I'm new to c# programming, but I followed the documentation to insert a wait in my code. The problem is, it doesn't seem to work. Here's the code:

```<code>void Start()
{
    StartCoroutine(Fixed());
}

IEnumerator Fixed()
{
    print("fixed clone");
    yield return new WaitForSeconds(5);

    Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);
    Rigidbody clone = Instantiate(original, originalPosition, transform.rotation);
    clone.velocity = rb.velocity * speed;
}
</code>```

(This is just a snippet of the code.) In Unity, when I play the clones come rocketing out, and with each clone comes the "fixed clone" message in my console, so I know it's coming from here.

If you need the whole code to figure the problem, I can insert that as well.

答:
Looking at your code you simply want to spawn an object after a delay. You don't really need a Coroutine to do this. Coroutines are good for manipulating objects over a number of frames, or frame by frame.

To simply run a function after a delay try the Invoke method:

```<code>void Start()
{
    Invoke("SpawnClone", 5.0f); //Call SpawnClone 5 seconds after start
}

void SpawnClone()
{
    print("fixed clone");

    Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);

    Rigidbody clone;
    clone = Instantiate(original, originalPosition, transform.rotation);
    clone.velocity = rb.velocity * speed;
}
</code>```

OR Try this to trigger as Coroutine

```<code>private IEnumerator coroutine;
void Start()
{
    coroutine = SpawnClone(5.0f);
    StartCoroutine(coroutine); //Trigger SpawnClone coroutine and pass in the delay of 5 seconds
    print("Triggered Coroutine SpawnClone");
}

private IEnumerator SpawnClone(float delay)
{
    print("Coroutine tick");
    yield return new WaitForSeconds(delay);

    print("Coroutine logic stared: " + Time.time + " seconds");

    Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);
    Rigidbody clone;
    clone = Instantiate(original, originalPosition, transform.rotation);
    clone.velocity = rb.velocity * speed;

    print("Coroutine ended: " + Time.time + " seconds");
}
</code>```

Body:
I'm new to c# programming, but I followed the documentation to insert a wait in my code. The problem is, it doesn't seem to work. Here's the code:

void Start()
{
    StartCoroutine(Fixed());
}

IEnumerator Fixed()
{
    print("fixed clone");
    yield return new WaitForSeconds(5);

    Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);
    Rigidbody clone = Instantiate(original, originalPosition, transform.rotation);
    clone.velocity = rb.velocity * speed;
}

(This is just a snippet of the code.) In Unity, when I play the clones come rocketing out, and with each clone comes the "fixed clone" message in my console, so I know it's coming from here.

If you need the whole code to figure the problem, I can insert that as well.

Body:
Looking at your code you simply want to spawn an object after a delay. You don't really need a Coroutine to do this. Coroutines are good for manipulating objects over a number of frames, or frame by frame.

To simply run a function after a delay try the Invoke method:

void Start()
{
    Invoke("SpawnClone", 5.0f); //Call SpawnClone 5 seconds after start
}

void SpawnClone()
{
    print("fixed clone");

    Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);

    Rigidbody clone;
    clone = Instantiate(original, originalPosition, transform.rotation);
    clone.velocity = rb.velocity * speed;
}

OR Try this to trigger as Coroutine

private IEnumerator coroutine;
void Start()
{
    coroutine = SpawnClone(5.0f);
    StartCoroutine(coroutine); //Trigger SpawnClone coroutine and pass in the delay of 5 seconds
    print("Triggered Coroutine SpawnClone");
}

private IEnumerator SpawnClone(float delay)
{
    print("Coroutine tick");
    yield return new WaitForSeconds(delay);

    print("Coroutine logic stared: " + Time.time + " seconds");

    Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);
    Rigidbody clone;
    clone = Instantiate(original, originalPosition, transform.rotation);
    clone.velocity = rb.velocity * speed;

    print("Coroutine ended: " + Time.time + " seconds");
}


问:
ExcludeFromCodeCoverageAttribute does not take effect in azuredevops pipeline
I add some [ExcludeFromCodeCoverage] in my class method in order to get the proper code coverage.It works well in visual studio so that I can get the right results.
But we I use a visual studio test in azuredevops pipeline,It does not take any effect.The method which include this attribute appears in Code Coverage result.
I also specify a CodeCoverage.runsettings file in my pipeline,I'm not clear it will effect the result.

```<code>steps:
- task: VSTest@2
  displayName: 'VsTest - Test Function App Project'
  inputs:
    runSettingsFile: src/DWP.CDA.FunctionApp/DWP.CDA.FunctionApp.Test/CodeCoverage.runsettings
    codeCoverageEnabled: true
    diagnosticsEnabled: true
</code>```

答:
Not sure what's your runsetting files look like. But on my side, everything work fine and the classes which configured with [ExcludeFromCodeCoverage] are excluded successfully.

Please try with ensuring below script in your runsetting file:

```<code> <Attributes>
   <Exclude>
     <Attribute>^System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute$</Attribute>
   </Exclude>
 </Attributes>
</code>```

Here is my compared result between non-exclude and excluded:

Body:
I add some [ExcludeFromCodeCoverage] in my class method in order to get the proper code coverage.It works well in visual studio so that I can get the right results.
But we I use a visual studio test in azuredevops pipeline,It does not take any effect.The method which include this attribute appears in Code Coverage result.
I also specify a CodeCoverage.runsettings file in my pipeline,I'm not clear it will effect the result.

steps:
- task: VSTest@2
  displayName: 'VsTest - Test Function App Project'
  inputs:
    runSettingsFile: src/DWP.CDA.FunctionApp/DWP.CDA.FunctionApp.Test/CodeCoverage.runsettings
    codeCoverageEnabled: true
    diagnosticsEnabled: true

Body:
Not sure what's your runsetting files look like. But on my side, everything work fine and the classes which configured with [ExcludeFromCodeCoverage] are excluded successfully.

Please try with ensuring below script in your runsetting file:

 <Attributes>
   <Exclude>
     <Attribute>^System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute$</Attribute>
   </Exclude>
 </Attributes>

Here is my compared result between non-exclude and excluded:


问:
How to check if all items in a list are of the same type?
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Edit:

I've now tried combining a couple of the answers into a section of the code:

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

答:
Going by the question title, you can check if all values are of same type using:

```<code>value = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
</code>```

Body:
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Edit:

I've now tried combining a couple of the answers into a section of the code:

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

Body:
Going by the question title, you can check if all values are of same type using:

value = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])


问:
How I can merge two audio files - JavaScript?
I have two audio files from RecordRTC both local & remote streams. Now I want to merge the two files into one file and upload it to the server via AJAX.

e.g. (audio1.webm) and (audio2.webm).

```<code>mediaRecorder.stopRecording(function() {
    var blob = mediaRecorder.getBlob();
    var fileName = getFileName('webm');

    var fileObject = new File([blob], fileName, {
        type: 'audio/webm'
    });

    var formData = new FormData();
        formData.append('blob', fileObject);
        formData.append('filename', fileObject.name);

    $.ajax({
        url: '{{ url('/') }}/save-audio',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            console.log(response);
        }
    });
});
</code>```

Thank you in advance.

UPDATE:

I made it this way instead of recorder.addStreams, and still I can get the recorded.

```<code>var remoteVideos = $('#remoteVideos video');
var el = [];

$.each($('#remoteVideos video'), function(index, val) {
     el[index] = val.srcObject;
});
el.push(stream);
multiMediaRecorder = new MultiStreamRecorder(el);
</code>```

答:
I got it now by doing this, as below;

```<code>function onMediaSuccess(localStream) {

            var remoteVideos = $('#remoteVideos video')[0];
            multiMediaRecorder = new MultiStreamRecorder([localStream, remoteVideos.srcObject]);
            multiMediaRecorder.ondataavailable = function (blob) {
                // POST/PUT "Blob" using FormData/XHR2
                var blobURL = URL.createObjectURL(blob);
                console.log(blobURL);
            };
            multiMediaRecorder.start();
    }
</code>```

But now there's another problem, ondataavailable is called twice but the first video is playable and working properly, while the second video is playable but (less than one second) I think it might be corrupted.

Cheers!

Body:
I have two audio files from RecordRTC both local & remote streams. Now I want to merge the two files into one file and upload it to the server via AJAX.

e.g. (audio1.webm) and (audio2.webm).

mediaRecorder.stopRecording(function() {
    var blob = mediaRecorder.getBlob();
    var fileName = getFileName('webm');

    var fileObject = new File([blob], fileName, {
        type: 'audio/webm'
    });

    var formData = new FormData();
        formData.append('blob', fileObject);
        formData.append('filename', fileObject.name);

    $.ajax({
        url: '{{ url('/') }}/save-audio',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            console.log(response);
        }
    });
});

Thank you in advance.

UPDATE:

I made it this way instead of recorder.addStreams, and still I can get the recorded.

var remoteVideos = $('#remoteVideos video');
var el = [];

$.each($('#remoteVideos video'), function(index, val) {
     el[index] = val.srcObject;
});
el.push(stream);
multiMediaRecorder = new MultiStreamRecorder(el);

Body:
I got it now by doing this, as below;

function onMediaSuccess(localStream) {

            var remoteVideos = $('#remoteVideos video')[0];
            multiMediaRecorder = new MultiStreamRecorder([localStream, remoteVideos.srcObject]);
            multiMediaRecorder.ondataavailable = function (blob) {
                // POST/PUT "Blob" using FormData/XHR2
                var blobURL = URL.createObjectURL(blob);
                console.log(blobURL);
            };
            multiMediaRecorder.start();
    }

But now there's another problem, ondataavailable is called twice but the first video is playable and working properly, while the second video is playable but (less than one second) I think it might be corrupted.

Cheers!


问:
Get data from RowCommand
I have a grid which shows product versions and have a few link buttons like edit, delete, preview etc.
On click of the edit button I want to get the Product ID and Version ID and redirect to some xyz.aspx page where the product details can be edited.

Here is how my Grid looks:

<asp:GridView ID="grdBindVersion" runat="server" AutoGenerateColumns="false"
            onrowcommand="grdBindVersion_RowCommand" >

        <RowStyle BorderStyle="Solid" BorderWidth="1px" />
        <Columns>
            <asp:BoundField datafield="HistoryId"  HeaderText="Version ID.">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

            <asp:BoundField datafield="Title" HeaderText="Title">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

             <asp:TemplateField HeaderText = "Edit">
                   <ItemTemplate>

                       <asp:LinkButton ID="Edit" runat="server" CommandArgument='<%# Container.DataItem %>'  CommandName ="Add">Edit</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Delete">
                   <ItemTemplate>
                           <asp:LinkButton ID="Delete" runat="server">Delete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Sub Page">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddSubPage" runat="server">Add Sub Page</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Rank">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddRank" runat="server">Add Rank</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Approve/DisApprove">
                   <ItemTemplate>
                           <asp:LinkButton ID="ApproveStatus" runat="server">Approve/DisApprove</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Complete">
                   <ItemTemplate>
                            <asp:LinkButton ID="Complete" runat="server">Complete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Preview">
                   <ItemTemplate>
                            <asp:LinkButton ID="Preview" runat="server">Preview</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Comment">
                   <ItemTemplate>
                            <asp:LinkButton ID="Comment" runat="server">Comment</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

        </Columns>
        </asp:GridView>
```

I am tracking the clicking on the link button  in the RowCommand event of the GridView.
Here i want to get the VersionID and ProductID and then redirect to another page.
Please help me.
I am really new to coding.
I did a bit of Google but none of the solutions are helping me.

答:
You can get the data on gridview_RowCommand event by placing below code:

```<code> Int32 HistoryId = Convert.ToInt32(e.Row.Cells[0].Text.ToString());
</code>```

You can set the [index] in Cells[index] according to your GridView items, then redirect to another page with that fetched HistoryId or ProductId.

Title: Get data from RowCommand

Body:
I have a grid which shows product versions and have a few link buttons like edit, delete, preview etc.
On click of the edit button I want to get the Product ID and Version ID and redirect to some xyz.aspx page where the product details can be edited.

Here is how my Grid looks:

<asp:GridView ID="grdBindVersion" runat="server" AutoGenerateColumns="false"
            onrowcommand="grdBindVersion_RowCommand" >

        <RowStyle BorderStyle="Solid" BorderWidth="1px" />
        <Columns>
            <asp:BoundField datafield="HistoryId"  HeaderText="Version ID.">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

            <asp:BoundField datafield="Title" HeaderText="Title">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

             <asp:TemplateField HeaderText = "Edit">
                   <ItemTemplate>

                       <asp:LinkButton ID="Edit" runat="server" CommandArgument='<%# Container.DataItem %>'  CommandName ="Add">Edit</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Delete">
                   <ItemTemplate>
                           <asp:LinkButton ID="Delete" runat="server">Delete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Sub Page">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddSubPage" runat="server">Add Sub Page</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Rank">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddRank" runat="server">Add Rank</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Approve/DisApprove">
                   <ItemTemplate>
                           <asp:LinkButton ID="ApproveStatus" runat="server">Approve/DisApprove</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Complete">
                   <ItemTemplate>
                            <asp:LinkButton ID="Complete" runat="server">Complete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Preview">
                   <ItemTemplate>
                            <asp:LinkButton ID="Preview" runat="server">Preview</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Comment">
                   <ItemTemplate>
                            <asp:LinkButton ID="Comment" runat="server">Comment</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

        </Columns>
        </asp:GridView>

I am tracking the clicking on the link button  in the RowCommand event of the GridView.
Here i want to get the VersionID and ProductID and then redirect to another page.
Please help me.
I am really new to coding.
I did a bit of Google but none of the solutions are helping me.

Body:
You can get the data on gridview_RowCommand event by placing below code:

 Int32 HistoryId = Convert.ToInt32(e.Row.Cells[0].Text.ToString());

You can set the [index] in Cells[index] according to your GridView items, then redirect to another page with that fetched HistoryId or ProductId.


答:
You can use list comprehension and compare both:</p>

```<code>def func(list1):
    list2 = [x for x in list1 if type(x) == int]
    if list1 == list2:
        return True
    else:
        return False
</code>```

Title: How to check if all items in a list are of the same type?

Body:
You can use list comprehension and compare both:

def func(list1):
    list2 = [x for x in list1 if type(x) == int]
    if list1 == list2:
        return True
    else:
        return False