问:
Append a rule to a k8s ingress object
We have a kubernetes Ingress object defined. All the ingress rules are not available when defining object for the first time, hence we would like to append rules to it on the fly when configuring respective services to use with it.

Example:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    alb.ingress.kubernetes.io/certificate-arn: ${acm_arn}
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/target-type: instance
    kubernetes.io/ingress.class: alb
  name: ${ingress_name}
  namespace: ${namespace}
spec:
  rules:
    - host: api.${region}.infra.${hosted_zone}
      http:
        paths:
          - backend:
              service:
               name: istio-ingressgateway
               port:
                number: 80
            path: /*
            pathType: Prefix
    - http:
        paths:
          - backend:
              service:
               name: nginx-ingress-controller
               port:
                number: 80
            path: /*
            pathType: Prefix

```
<p>The above object is created in the beginning. Now, we would like to append a third rule to it at later point in time.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
  name: ${ingress_name}
  namespace: ${namespace}
spec:
  rules:
    - host: api.${region}.${some_dynamic_variable}.${hosted_zone}
      http:
        paths:
          - backend:
              service:
               name: istio-ingressgateway
               port:
                number: 80
            path: /*
            pathType: Prefix
</code>```

I could have used kubectl patch but because the merge strategy is not specified in the api docs, I understand it follows the merge strategy replace which is not what I intend to do.

What is the best available option to get this issue resolved?

答:
There is a kubectl plugin called ingress-rule. It allows you to configure an Ingress on the command line.
The plugin is available via krew. If you have krew installed simply install the plugin with:

```<code>kubectl krew install ingress-rule
</code>```

Add a new rule to a existing Ingress:

```<code>kubectl ingress-rule -n $NAMESPACE set $INGRESSNAME --service $SERVICENAME --port 80 --host $HOST
</code>```

Delete the previously added rule:

```<code>kubectl ingress-rule -n $NAMESPACE delete $INGRESSNAME --service $SERVICENAME
</code>```

Title: Append a rule to a k8s ingress object

Body:
We have a kubernetes Ingress object defined. All the ingress rules are not available when defining object for the first time, hence we would like to append rules to it on the fly when configuring respective services to use with it.

Example:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    alb.ingress.kubernetes.io/certificate-arn: ${acm_arn}
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/target-type: instance
    kubernetes.io/ingress.class: alb
  name: ${ingress_name}
  namespace: ${namespace}
spec:
  rules:
    - host: api.${region}.infra.${hosted_zone}
      http:
        paths:
          - backend:
              service:
               name: istio-ingressgateway
               port:
                number: 80
            path: /*
            pathType: Prefix
    - http:
        paths:
          - backend:
              service:
               name: nginx-ingress-controller
               port:
                number: 80
            path: /*
            pathType: Prefix

The above object is created in the beginning. Now, we would like to append a third rule to it at later point in time.

apiVersion: networking.k8s.io/v1
kind: Ingress
  name: ${ingress_name}
  namespace: ${namespace}
spec:
  rules:
    - host: api.${region}.${some_dynamic_variable}.${hosted_zone}
      http:
        paths:
          - backend:
              service:
               name: istio-ingressgateway
               port:
                number: 80
            path: /*
            pathType: Prefix

I could have used kubectl patch but because the merge strategy is not specified in the api docs, I understand it follows the merge strategy replace which is not what I intend to do.

What is the best available option to get this issue resolved?

Body:
There is a kubectl plugin called ingress-rule. It allows you to configure an Ingress on the command line.
The plugin is available via krew. If you have krew installed simply install the plugin with:

kubectl krew install ingress-rule

Add a new rule to a existing Ingress:

kubectl ingress-rule -n $NAMESPACE set $INGRESSNAME --service $SERVICENAME --port 80 --host $HOST

Delete the previously added rule:

kubectl ingress-rule -n $NAMESPACE delete $INGRESSNAME --service $SERVICENAME


来源: stackexchange

问:
Passing js variable to php using ajax does not work
I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution

```<code>$('#add-review').click(function(){
    var user_name = $('#reviewer-name').val();
    var user_review = $('#review').val();
    console.log(user_name);
    console.log(rating_index);
    console.log(user_review);
    if(user_name == '' || user_review == '')
    {
        alert("Please Fill Both Field");
        return false;
    }
    else
    {
        $.ajax({
            url:"rating-data.php",
            method:"GET",
            data:{
                rating_index: rating_index,
                user_name: user_name,
                user_review: user_review
            },
            success:function(data)
            {
                $('#review_modal').modal('hide');
                load_rating_data();
                console.log(data);
            }
        })
    }
});
</code>```

This is my php code when I can get the variable and send them to the database:

```<code><?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
    $data = array(
        ':user_name'        =>  $_GET["user_name"],
        ':user_rating'      =>  $_GET["rating_index"],
        ':user_review'      =>  $_GET["user_review"],
        ':datetime'         =>  time()
    );
    $query = "
    INSERT INTO review_table
    (user_name, user_rating, user_review, datetime)
    VALUES (:user_name, :user_rating, :user_review, :datetime)
    ";

    $query_run = mysqli_query($conn, $query);
    if($query_run){
        echo "Your Review & Rating Successfully Submitted";
    } else{
        echo '<script type="text/javascript"> alert("Something went wrong") </script>';
        echo mysqli_error($conn);
    }
}
?>
</code>```

When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions

答:
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.

```<code>var x = " < ? php echo"$name" ? >";
</code>```

you can pass your PHP variable like this but in only the .php file not in the .js

ContentLicense: CC BY-SA 4.0

Body:
I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution

$('#add-review').click(function(){
    var user_name = $('#reviewer-name').val();
    var user_review = $('#review').val();
    console.log(user_name);
    console.log(rating_index);
    console.log(user_review);
    if(user_name == '' || user_review == '')
    {
        alert("Please Fill Both Field");
        return false;
    }
    else
    {
        $.ajax({
            url:"rating-data.php",
            method:"GET",
            data:{
                rating_index: rating_index,
                user_name: user_name,
                user_review: user_review
            },
            success:function(data)
            {
                $('#review_modal').modal('hide');
                load_rating_data();
                console.log(data);
            }
        })
    }
});

This is my php code when I can get the variable and send them to the database:

<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
    $data = array(
        ':user_name'        =>  $_GET["user_name"],
        ':user_rating'      =>  $_GET["rating_index"],
        ':user_review'      =>  $_GET["user_review"],
        ':datetime'         =>  time()
    );
    $query = "
    INSERT INTO review_table
    (user_name, user_rating, user_review, datetime)
    VALUES (:user_name, :user_rating, :user_review, :datetime)
    ";

    $query_run = mysqli_query($conn, $query);
    if($query_run){
        echo "Your Review & Rating Successfully Submitted";
    } else{
        echo '';
        echo mysqli_error($conn);
    }
}
?>

When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions

Body:
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.

var x = " < ? php echo"$name" ? >";

you can pass your PHP variable like this but in only the .php file not in the .js


问:
I have a problrm with if statement and while loop and dictionary in python
```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif r not in men:
        print('Sorry, the number is not found')
    elif r >= 11:
        while r >= 11:
            r = r + 1 == 1
            print('This is invalid number')
mo()
</code>```

I have problem in the elif. What I want is if I write more than 10 characters in the console, then the code will print 'This is invalid number'. But instead the code prints 'Sorry, the number is not found'.

Output:

```<code>Please Enter The Number: 111111111111111
Sorry, the number is not found

Process finished with exit code 0
</code>```

答:
I am not sure why are you using while loop and r = r + 1 == 1 in your code. But I guess you want something like this:

```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif len(str(r)) >= 11:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
mo()

</code>```

Body:
men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif r not in men:
        print('Sorry, the number is not found')
    elif r >= 11:
        while r >= 11:
            r = r + 1 == 1
            print('This is invalid number')
mo()

I have problem in the elif. What I want is if I write more than 10 characters in the console, then the code will print 'This is invalid number'. But instead the code prints 'Sorry, the number is not found'.

Output:

Please Enter The Number: 111111111111111
Sorry, the number is not found

Process finished with exit code 0

Body:
I am not sure why are you using while loop and r = r + 1 == 1 in your code. But I guess you want something like this:

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif len(str(r)) >= 11:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
mo()


问:
Problems with react & material UI
It shows hook err, but the thing is I do not have any hooks.Only Material UI causes this problem. If i delete these strings after return, it works

Project code:

```<code>
    import React from 'react'
    import { Container, AppBar, Typography, Grow, Grid } from '@mui/material'
    import memories from './images/memories.png'

    const App = () => {
      return (
        <Container maxwidth='lg'>
          <AppBar position='static' color='inherit'>
            <Typography variant='h2' align='center'>
              Memories
            </Typography>
            <img src={memories} alt='memories' height='60' />
          </AppBar>
        </Container>
      )
    }

export default App```

error:

    Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
```

答:
Maybe you used some hooks inside index,js file.
i have copied your code into my editor and removed img tag and

```<code>import memories from './images/memories.png'
</code>```

and everything worked.

Title: Problems with react & material UI

Body:
It shows hook err, but the thing is I do not have any hooks.Only Material UI causes this problem. If i delete these strings after return, it works

Project code:

    import React from 'react'
    import { Container, AppBar, Typography, Grow, Grid } from '@mui/material'
    import memories from './images/memories.png'

    const App = () => {
      return (
        <Container maxwidth='lg'>
          <AppBar position='static' color='inherit'>
            <Typography variant='h2' align='center'>
              Memories
            </Typography>

          </AppBar>
        </Container>
      )
    }

export default App```

error:

    Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Body:
Maybe you used some hooks inside index,js file.
i have copied your code into my editor and removed img tag and

import memories from './images/memories.png'

and everything worked.


问:
My code is outputting an extra line why is this?
This code I've been working on is so close to being done. However, it keeps printing out an extra line in the output. There is only supposed to be 5 lines in the output but there is six and I can't figure out why this is happening.

This is my book.h file this file cannot be changed in order to complete the code.

```<code>#include <string>

using namespace std;

enum Type
{
    UNKNOWN = -1,
   PAPERBACK,
    HARDBACK
};

const string TYPE_WORDS[] = { "Paperback", "Hardback" };

class Book
{
public:
    //default constructor - not actually used but should be implemented anyway
    Book();
    //constructor
    Book( const string& name, Type type, int pages, float ounces );
    //destructor
    ~Book(){};

    string formatReportLine();  //return a string with all the info for the book
    float getWeightLbs();  //calculate and return the weight of the book in lbs
    string getTypeName();  //return the string which correlates with the book type

    //accessors
    string getName(){ return bName; };
    Type getType(){ return bType; };
    int getPages(){ return bPages; };
    float getOunces(){ return bOunces; };

private:
    string bName;  //name of the book
    Type bType;  //the type of book (Type is an enumerated type)
    int bPages;  //how many pages the book contains
    float bOunces;  //how much the book weighs in ounces
};
</code>```

This is the main.cpp file this file can be changed but should only have code added not taken out.

```<code>#include <iostream>
#include <fstream>
#include <string>
#include "book.h"

using namespace std;

int main()
{
    const string FILENAME("books.txt");
  const int INT_MAX = 1;

    ifstream input(FILENAME);
    if( input.good() )
    {
        while( !input.eof() )
        {
            string name;
            int type;
            int pages;
            float ounces;
            getline( input, name );
            input >> type >> pages >> ounces;
            input.ignore(INT_MAX, '\n');  //ignore the newline char at the end of the line

            //create Book object here!
      Book myBook(name,(Type)type, pages, ounces);
            //write out report line for book here!
            cout << myBook.formatReportLine();
        }
    }
    else
    {
        cout << "File not found: " << FILENAME << endl;
    }

    system("pause");
    return 0;
}
</code>```

This is the book.cpp file this is where the most change will be done file has some functions but most code will have to be added.

```<code>#include <iostream>
#include <fstream>
#include <string>
#include "book.h"
#include "sstream"

Book::Book()
{

}

Book::Book( const string& name, Type type, int pages, float ounces )
{
  bName = name;
  bType = type;
  bPages = pages;
  bOunces = ounces;
}

float Book::getWeightLbs()
{
  float answer;
  answer = bOunces / 16;
  return answer;
}

string Book::getTypeName()
{
  string typeName = "";
  if(bType == PAPERBACK)
  typeName = TYPE_WORDS[bType];

  else if (bType == HARDBACK)
  typeName = TYPE_WORDS[bType];

  else
  typeName = "Unknown";

  return typeName;
}

string Book::formatReportLine()
{
  stringstream sout;
  sout << bName << " | Type: " << getTypeName() << " Pages: " << bPages << " Weight(lbs): " << getWeightLbs() << endl;
  return sout.str();
}
</code>```

This is the book.txt file that the code is getting its data from.

```<code>The Human Use of Human Beings
0
200
8.0
Utopia
0
176
4.8
Hackers
0
520
22.4
The Information
1
544
33.6
Sterling's Gold
1
176
8.0
</code>```

This is what it is currently outputting. The extra line at the end that reads " | Type: Hardback Pages: 176 Weight(lbs): 0.5" should not be there and I can't figure out why it is outputting like that.

```<code>The Human Use of Human Beings | Type: Paperback Pages: 200 Weight(lbs): 0.5
Utopia | Type: Paperback Pages: 176 Weight(lbs): 0.3
Hackers | Type: Paperback Pages: 520 Weight(lbs): 1.4
The Information | Type: Hardback Pages: 544 Weight(lbs): 2.1
Sterling's Gold | Type: Hardback Pages: 176 Weight(lbs): 0.5
 | Type: Hardback Pages: 176 Weight(lbs): 0.5
</code>```

答:
There's probably a blank line at the end of the data file. Put in

```<code>if (name.empty()) {
    continue;
}
</code>```

just before you construct the book object.

Also as @Eljay said in comments you shouldn't iterate over a file by doing while (!file.eof()): see here.

Body:
This code I've been working on is so close to being done. However, it keeps printing out an extra line in the output. There is only supposed to be 5 lines in the output but there is six and I can't figure out why this is happening.

This is my book.h file this file cannot be changed in order to complete the code.

#include <string>

using namespace std;

enum Type
{
    UNKNOWN = -1,
   PAPERBACK,
    HARDBACK
};

const string TYPE_WORDS[] = { "Paperback", "Hardback" };

class Book
{
public:
    //default constructor - not actually used but should be implemented anyway
    Book();
    //constructor
    Book( const string& name, Type type, int pages, float ounces );
    //destructor
    ~Book(){};

    string formatReportLine();  //return a string with all the info for the book
    float getWeightLbs();  //calculate and return the weight of the book in lbs
    string getTypeName();  //return the string which correlates with the book type

    //accessors
    string getName(){ return bName; };
    Type getType(){ return bType; };
    int getPages(){ return bPages; };
    float getOunces(){ return bOunces; };

private:
    string bName;  //name of the book
    Type bType;  //the type of book (Type is an enumerated type)
    int bPages;  //how many pages the book contains
    float bOunces;  //how much the book weighs in ounces
};

This is the main.cpp file this file can be changed but should only have code added not taken out.

#include <iostream>
#include <fstream>
#include <string>
#include "book.h"

using namespace std;

int main()
{
    const string FILENAME("books.txt");
  const int INT_MAX = 1;

    ifstream input(FILENAME);
    if( input.good() )
    {
        while( !input.eof() )
        {
            string name;
            int type;
            int pages;
            float ounces;
            getline( input, name );
            input >> type >> pages >> ounces;
            input.ignore(INT_MAX, '\n');  //ignore the newline char at the end of the line

            //create Book object here!
      Book myBook(name,(Type)type, pages, ounces);
            //write out report line for book here!
            cout << myBook.formatReportLine();
        }
    }
    else
    {
        cout << "File not found: " << FILENAME << endl;
    }

    system("pause");
    return 0;
}

This is the book.cpp file this is where the most change will be done file has some functions but most code will have to be added.

#include <iostream>
#include <fstream>
#include <string>
#include "book.h"
#include "sstream"

Book::Book()
{

}

Book::Book( const string& name, Type type, int pages, float ounces )
{
  bName = name;
  bType = type;
  bPages = pages;
  bOunces = ounces;
}

float Book::getWeightLbs()
{
  float answer;
  answer = bOunces / 16;
  return answer;
}

string Book::getTypeName()
{
  string typeName = "";
  if(bType == PAPERBACK)
  typeName = TYPE_WORDS[bType];

  else if (bType == HARDBACK)
  typeName = TYPE_WORDS[bType];

  else
  typeName = "Unknown";

  return typeName;
}

string Book::formatReportLine()
{
  stringstream sout;
  sout << bName << " | Type: " << getTypeName() << " Pages: " << bPages << " Weight(lbs): " << getWeightLbs() << endl;
  return sout.str();
}

This is the book.txt file that the code is getting its data from.

The Human Use of Human Beings
0
200
8.0
Utopia
0
176
4.8
Hackers
0
520
22.4
The Information
1
544
33.6
Sterling's Gold
1
176
8.0

This is what it is currently outputting. The extra line at the end that reads " | Type: Hardback Pages: 176 Weight(lbs): 0.5" should not be there and I can't figure out why it is outputting like that.

The Human Use of Human Beings | Type: Paperback Pages: 200 Weight(lbs): 0.5
Utopia | Type: Paperback Pages: 176 Weight(lbs): 0.3
Hackers | Type: Paperback Pages: 520 Weight(lbs): 1.4
The Information | Type: Hardback Pages: 544 Weight(lbs): 2.1
Sterling's Gold | Type: Hardback Pages: 176 Weight(lbs): 0.5
 | Type: Hardback Pages: 176 Weight(lbs): 0.5

Body:
There's probably a blank line at the end of the data file. Put in

if (name.empty()) {
    continue;
}

just before you construct the book object.

Also as @Eljay said in comments you shouldn't iterate over a file by doing while (!file.eof()): see here.


问:
Use random file
I have this piece of code:

```<code>com = "node file1.js {var1} {var2} {var3} {var4} {var5}".format(
    var1 = self.CURRENTENTRY[0],
    var2 = self.CURRENTENTRY[1],
    var3 = self.CURRENTENTRY[2],
    var4 = self.CURRENTENTRY[3],
    var5 = ",".join(elist)
)
</code>```

I would like to use more .js files (file2.js, file3.js, ..., filex.js) and let the script to chose one at random each time.

答:
```<code>import random

foo = ["file2.js", "file3.js","file4.js"]
print(random.choice(foo))
</code>```

Title: Use random file

Body:
I have this piece of code:

com = "node file1.js {var1} {var2} {var3} {var4} {var5}".format(
    var1 = self.CURRENTENTRY[0],
    var2 = self.CURRENTENTRY[1],
    var3 = self.CURRENTENTRY[2],
    var4 = self.CURRENTENTRY[3],
    var5 = ",".join(elist)
)

I would like to use more .js files (file2.js, file3.js, ..., filex.js) and let the script to chose one at random each time.


问:
What's the point of blessed in Perl?
```<code>[root@ ~]$ perl -e "print 1 if blessed $a;"
1
[root@ ~]$ perl -e "print 1 if blessed $c;"
1
[root@ ~]$ perl -e "print 1 if blessed $cee;"
1
</code>```

It seems always true,the version is 5.8.8.

UPDATE

I'm not running as root, it's CHANGED by me for the sake of privacy:)

答:
Do you mean blessed from Scalar::Util? You probably want to load the function first:

```<code>perl -MScalar::Util=blessed -e "print 1 if blessed $a;"
</code>```

otherwise your blessed is just bareword (string), which is obviously true.

ContentLicense: CC BY-SA 3.0

Title: What's the point of blessed in Perl?

Body:
[root@ ~]$ perl -e "print 1 if blessed $a;"
1
[root@ ~]$ perl -e "print 1 if blessed $c;"
1
[root@ ~]$ perl -e "print 1 if blessed $cee;"
1

It seems always true,the version is 5.8.8.

UPDATE

I'm not running as root, it's CHANGED by me for the sake of privacy:)

Body:
Do you mean blessed from Scalar::Util? You probably want to load the function first:

perl -MScalar::Util=blessed -e "print 1 if blessed $a;"

otherwise your blessed is just bareword (string), which is obviously true.


问:
Excel: How to merge two columns into one (from different sheets or separated columns)
I have met some problem with merging two columns to one.
I have some solution but not exactly fits to my problem (found here: Excel: Merge two columns into one column with alternating values)

As I understand two columns has to be one by one:

```<code>A       B       C
==================
A       1       A
B       2       1
C       3       B
                2
                C
                3
</code>```

To get the above solution in C column I should use:

```<code>=INDEX($A$2:$B$9;ROUND(ROW(A1)/2;0);MOD(ROW();2)+1)
</code>```

So in the formula I'm using data like A1:B4.

How to do it if I will have columns with data A and D and I dont want to include columns B and C?
Or for instance I will have one column from sheet_A and second column from sheet_B?

答:
The Index function can be used in two different way. This example use the index function with multiple range area. The 4th parameter is the sequence number of the individual reference range.

Here is the equation for the result combined in one column.

```<code>=LET(RC,ROW(M9)-ROW($M$8),Rx,IF(ISODD(RC),(RC+1)/2,RC/2),Ax,IF(ISODD(RC),1,2),INDEX(($F$11:$F$20,$I$18:$I$27),Rx,,Ax))
</code>```

RC is the variable representing the row in the result column.  Rx represent the row in the reference area, Ax is the reference area number.

NOTE: M9 is my 1st row in the RC column

Body:
I have met some problem with merging two columns to one.
I have some solution but not exactly fits to my problem (found here: Excel: Merge two columns into one column with alternating values)

As I understand two columns has to be one by one:

A       B       C
==================
A       1       A
B       2       1
C       3       B
                2
                C
                3

To get the above solution in C column I should use:

=INDEX($A$2:$B$9;ROUND(ROW(A1)/2;0);MOD(ROW();2)+1)

So in the formula I'm using data like A1:B4.

How to do it if I will have columns with data A and D and I dont want to include columns B and C?
Or for instance I will have one column from sheet_A and second column from sheet_B?

Body:
The Index function can be used in two different way. This example use the index function with multiple range area. The 4th parameter is the sequence number of the individual reference range.

Here is the equation for the result combined in one column.

=LET(RC,ROW(M9)-ROW($M$8),Rx,IF(ISODD(RC),(RC+1)/2,RC/2),Ax,IF(ISODD(RC),1,2),INDEX(($F$11:$F$20,$I$18:$I$27),Rx,,Ax))

RC is the variable representing the row in the result column.  Rx represent the row in the reference area, Ax is the reference area number.

NOTE: M9 is my 1st row in the RC column


问:
Which AWS Service to make videos webready?
I have users uploading videos in all kinds of formats, some not supported by chrome.

I just want to transcode all videos so they play in the browser, e.g. h.264.

I have looked at AWS Elastic Media Convert that does not have any documentation that is actually explaining how to go from zero to hero, let alone having meaningful templates for jobs.

Is it at all possible to do that with media convert and if not, what would be an appropriate service?

答:
In general, yes.  Existing AWS Blog articles describe workflows using S3 "watch folders" to convert new files as they arrive, using MediaConvert to covert files to a ubiquitous output format and deliver the converted output to a specified S3 location which can support web access both directly and as an origin for CDN distributions.

There are several considerations (for example: very long input files, exotic file formats, nature of content, etc) for which you may want to account. The design and testing of a multi-step workflow with error handling can be complex. If you wish to use outside expertise, you have at least three options:

[a]  AWS Paid Professional Services  -
There is a large global AWS ProServices team able to help via paid service engagements. The fastest way to start this dialog is by submitting the AWS Sales team 'contact me' form found at this link and specifying 'Sales Support'  :   https://aws.amazon.com/contact-us/

[b]  AWS Certified Consulting Partners  -- The partner search tool & listings are here:  https://iq.aws.amazon.com/services/aws/medialive

[c]  AWS Solutions Architects -- for AWS Enterprise Support customers.  The TAM or the Sales contact linked in item [a] is the best way to engage them. Purchasing AWS Enterprise Support will entitle the customer to a dedicated TAM / SA combination.


问:
How to console.dir() on extendScript?
I want to familiarize with the DOM in extendScript , I want to console.log(certainObject) or console.dir(certainObject) in order to check its properties.

There is a way to console.log() such as $.writeln(certainVariable) but that won't return the properties of that object.

I can use the extendScript toolkit but in the Data Browser I can't identify all the objects.

Going to the documentation is confusing , for instance for this object app.activeDocument.placedItems it list certain properties , but a basic property such as the method app.activeDocument.placedItems.add(); is not there.

Where does that method come from? Inheritance ? , How can I check this?.

答:
The simplest way to get all (?) properties of the object is just to loop through them and to print the result in the console:

```<code>var obj = app.selection[0];
var props = '';
for (var prop in obj) {
    try { props += prop + ' : ' + obj[prop] + '\n' }
    catch(e) { props += prop + ': ???\n' }
}
$.writeln(props.split('\n').sort().join('\n'));
</code>```

Not sure if it's the best way, but I'm doing it sometimes. )

I saw the solution that does the same and put the result into a panel. It can be done quite easy if you know how to create a panel and to fill it with a text.

As for the methods... Well, I don't know the answer.

Title: How to console.dir() on extendScript?

Body:
The simplest way to get all (?) properties of the object is just to loop through them and to print the result in the console:

var obj = app.selection[0];
var props = '';
for (var prop in obj) {
    try { props += prop + ' : ' + obj[prop] + '\n' }
    catch(e) { props += prop + ': ???\n' }
}
$.writeln(props.split('\n').sort().join('\n'));

Not sure if it's the best way, but I'm doing it sometimes. )

I saw the solution that does the same and put the result into a panel. It can be done quite easy if you know how to create a panel and to fill it with a text.

As for the methods... Well, I don't know the answer.


问:
What happens to the 513th concurrent request to nginx?
Nginx is event based and by default runs as 1 process supporting max 512 concurrent connections. Another process would allow another 512 concurrent connections.

I'm using nginx as a reverse proxy to a kestrel server. Kestrel supports unlimited connections.

Assuming 512 requests are concurrently processing, when the 513th request comes in then will nginx reject it or will it get added to a queue?

答:
According to the docs

Sets the maximum number of simultaneous connections that can be opened by a worker process.

and the source of ngx_get_connection() it'll simply emit a warning and won't open a new connection:

"%ui worker_connections are not enough"

so there doesn't appear do be any queueing.

And if the returned value is NULL (it is for this case), then it'll simply close the socket(if there's any), so won't handle the connection, but will kill it instead. The same behavior appears to be consistent between UDP and other types as well.

Regarding the "unlimited," I'd be highly skeptical about anything that mentions it. One type of the resources will eventually not be enough be it CPU utilization, memory, filesystem resources or whatever else, so if the library/application mentions "unlimited" go check what does it really mean and what happens when such "unlimited" thing can't be unlimited anymore. Then, you'll find the metrics according to which you can adjust Nginx config to match (or be a bit higher, so it can handle all incoming) connections.

I did a quick search and found microsoft.aspnetcore.server.kestrel.core.kestrelserverlimits.maxconcurrentconnections and its related ConnectionLimitMiddleware which if enabled seems to do some kind of queueing of connections and if disabled I'd guess it'll be limited by the OS's underlying socket limitations, however I found only very brief references to Windows' socket buffer size (TCP), thus you'll need to dig deeper.

For testing purposes, simply use the lowest possible value of worker_connections for Nginx until it starts and keeps running, similarly for Kestrel and see how it behaves when:

Kestrel > Nginx

Kestrel == Nginx

Kestrel < Nginx

with opening sockets against the server and send a byte or two once in a while so the socket is busy.


问:
Ways to propagate changes to content children
I'm trying to develop a good (maintainable, easy to reason about) way to propagate changes from a top-level parent to its content children.

Currently I trigger changes to the content children in ngOnChanges of the top-level parent which in turn triggers ngOnChanges of its content children and so on. I feel this is a bit clunky.

What are some alternatives I can use here? Thanks

```<code><grandparent
  [inputOne]=""
  [inputTwo]=""
  [inputThree]=""
>
  <parent>
    <child>
    </child>
  </parent>
</grandparent>
</code>```

grandparent.ts

```<code>@ContentChild(ParentComponent) parent: ParentComponent
ngOnChanges(changes: SimpleChanges) {
  this.parent.ngOnChanges(changes);
}
</code>```

parent.ts

```<code>export class ParentComponent {
  ...
  @ContentChild(ChildComponent) child: ChildComponent
  ngOnChanges(changes: SimpleChanges) {
    this.child.ngOnChanges(changes);
  }
}
</code>```

child.ts

```<code>export class ChildComponent {
  ...
  ngOnChanges(changes: SimpleChanges) {
    switch(changes.currentValue) {
      case 'one':
        // handle changes
      ...
    }
  }
}
</code>```

答:
You can use @Input() and @Output() decorators.

@Input() lets a parent component update data in the child component.

Conversely, @Output() lets the child send data to a parent component.

learn more in the documentation by angular:
https://angular.io/guide/inputs-outputs

P.S. if you want a grandparent to communicate with its grand kids, you have to pass by the original parents, it's not possible directly.

Body:
I'm trying to develop a good (maintainable, easy to reason about) way to propagate changes from a top-level parent to its content children.

Currently I trigger changes to the content children in ngOnChanges of the top-level parent which in turn triggers ngOnChanges of its content children and so on. I feel this is a bit clunky.

What are some alternatives I can use here? Thanks

<grandparent
  [inputOne]=""
  [inputTwo]=""
  [inputThree]=""
>
  <parent>
    <child>
    </child>
  </parent>
</grandparent>

grandparent.ts

@ContentChild(ParentComponent) parent: ParentComponent
ngOnChanges(changes: SimpleChanges) {
  this.parent.ngOnChanges(changes);
}

parent.ts

export class ParentComponent {
  ...
  @ContentChild(ChildComponent) child: ChildComponent
  ngOnChanges(changes: SimpleChanges) {
    this.child.ngOnChanges(changes);
  }
}

child.ts

export class ChildComponent {
  ...
  ngOnChanges(changes: SimpleChanges) {
    switch(changes.currentValue) {
      case 'one':
        // handle changes
      ...
    }
  }
}


答:
If you do indeed have a Series of DataFrame objects, then this should work:

s.apply(lambda df: pd.merge(template.copy(), df, on="date", how="outer"))
```
<p>Where <code>s</code> is a series of DataFrame objects with datetime column "date" and "value" column of any type, and <code>template</code> is a DataFrame representing all the rows each DataFrame in your series <em>should</em> have:</p>
<pre class="lang-py prettyprint-override"><code>                 date
0 2021-01-20 11:00:00
1 2021-01-20 11:20:00
2 2021-01-20 11:22:00
3 2021-01-20 11:23:00
4 2021-01-20 11:40:00
5 2021-01-21 09:00:00
6 2021-01-21 10:00:00
</code>```

Note: your DataFrame objects in your series need to have column names for this to work easily.

Result:

In [5]: s[0]  # first dataframe in series s
                 date  value
0 2021-01-20 11:00:00    NaN
1 2021-01-20 11:20:00    4.0
2 2021-01-20 11:22:00    5.0
3 2021-01-20 11:23:00    4.0
4 2021-01-20 11:40:00    3.0
5 2021-01-21 09:00:00    NaN
6 2021-01-21 10:00:00    NaN
```
<p>To create a <code>template</code> DataFrame, from e.g. June 20, 2020 to June 21, 2020, in increments of 5 minutes:</p>
<pre class="lang-py prettyprint-override"><code>template = pd.DataFrame(pd.date_range("2020-06-20", "2020-06-22", freq="5T"))
</code>```

Title: How to reindex pandas dataframes of different lengths?

Body:
I have a list series of pandas dataframes of different lengths. I need to transform them into the dataframes of the same (maximum) length max_len.

0:
2021-01-20 11:20    4
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3

1:
2021-01-20 11:00    1
2021-01-20 11:22    2
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 10:00    1

2:
2021-01-20 11:20    2
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     2

Expected result:

In this example the maximum length is 7. Thus, all dataframes should have the same length:

0:
2021-01-20 11:00    NaN
2021-01-20 11:20    4
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     NaN
2021-01-21 10:00    NaN

1:
2021-01-20 11:00    1
2021-01-20 11:20    NaN
2021-01-20 11:22    2
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     NaN
2021-01-21 10:00    1

2:
2021-01-20 11:00    NaN
2021-01-20 11:20    2
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     2
2021-01-21 10:00    NaN

This is my code:

for i in range(len(series)):
    if len(series[i])!= max_len:
        series[i] = series[i].reindex(longest_series.index)

However, the reindex results in an i-th dataframe with all Nan values. Also, I'm not sure how to retrieve max_len.

How can I have Nan values only in new index values in each dataframe?

Update:

selected_series = []

l = pd.DataFrame([{'2021-01-20 11:20': 4, '2021-01-20 11:22': 5, '2021-01-20 11:23': 4, '2021-01-20 11:40': 3}])
selected_series.append(l)
l = pd.DataFrame([{'2021-01-20 11:00': 1, '2021-01-20 11:22': 2, '2021-01-20 11:23': 4, '2021-01-20 11:40': 3, '2021-01-21 10:00': 1}])
selected_series.append(l)
l = pd.DataFrame([{'2021-01-20 11:20': 2, '2021-01-20 11:22': 5, '2021-01-20 11:23': 4, '2021-01-20 11:40': 3, '2021-01-21 9:00': 2}])
selected_series.append(l)

Body:
If you do indeed have a Series of DataFrame objects, then this should work:

s.apply(lambda df: pd.merge(template.copy(), df, on="date", how="outer"))

Where s is a series of DataFrame objects with datetime column "date" and "value" column of any type, and template is a DataFrame representing all the rows each DataFrame in your series should have:

                 date
0 2021-01-20 11:00:00
1 2021-01-20 11:20:00
2 2021-01-20 11:22:00
3 2021-01-20 11:23:00
4 2021-01-20 11:40:00
5 2021-01-21 09:00:00
6 2021-01-21 10:00:00

Note: your DataFrame objects in your series need to have column names for this to work easily.

Result:

In [5]: s[0]  # first dataframe in series s
                 date  value
0 2021-01-20 11:00:00    NaN
1 2021-01-20 11:20:00    4.0
2 2021-01-20 11:22:00    5.0
3 2021-01-20 11:23:00    4.0
4 2021-01-20 11:40:00    3.0
5 2021-01-21 09:00:00    NaN
6 2021-01-21 10:00:00    NaN

To create a template DataFrame, from e.g. June 20, 2020 to June 21, 2020, in increments of 5 minutes:

template = pd.DataFrame(pd.date_range("2020-06-20", "2020-06-22", freq="5T"))


问:
What is the best way to execute a function after TWO or more async functions finish in React?
I have two functions that run asynchronously getting data from the API. Both of them are called from their own useEffect().

I have a third function that needs to run once those two functions have been fully completed.

How can this be accomplished?

Edit:
Both of the async functions look like this:

```<code>   useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

  useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

 const fetchBudgetsData = async () => {
    setIsFetchingBudgets(true);
    const res = await getBudgets(orgID, `${parseInt(fiscalYear)}`, '', budgetType);
    setIsFetchingBudgets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgets(res.budgets);
  };

 const fetchBudgetBucketsData = async () => {
    setIsLoadingBudgetBuckets(true);
    if (orgID === undefined) {
      return;
    }

    const res = await getBudgetBuckets(orgID, fiscalYear);
    setIsLoadingBudgetBuckets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgetBuckets(res.buckets);
  };
</code>```

Whenever the budget data or bucket data is updated, I want to call another function that checks for errors. However when the page loads, I need it to wait for both of those functions to be finished before it checks for errors.

Edit #2:

After some debugging, it looks like the issue might have to do with when React updates the state. Since I am trying to check for errors in data saved in the state.

答:
I discovered the issue was caused by how React chooses when to update the state and not how I was calling these functions asynchronously.

I was able to call my Error check function by hooking it into the output of the data fetch calls. This makes sure that the error check only runs when either the budgets or buckets are edited and finished being changed.

```<code>useEffect(() => {
    getWarningsAndErrors();
  }, [budgets, budgetBuckets]) //Update errors whenever we edit budgets or buckets
</code>```

Body:
I have two functions that run asynchronously getting data from the API. Both of them are called from their own useEffect().

I have a third function that needs to run once those two functions have been fully completed.

How can this be accomplished?

Edit:
Both of the async functions look like this:

   useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

  useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

 const fetchBudgetsData = async () => {
    setIsFetchingBudgets(true);
    const res = await getBudgets(orgID, `${parseInt(fiscalYear)}`, '', budgetType);
    setIsFetchingBudgets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgets(res.budgets);
  };

 const fetchBudgetBucketsData = async () => {
    setIsLoadingBudgetBuckets(true);
    if (orgID === undefined) {
      return;
    }

    const res = await getBudgetBuckets(orgID, fiscalYear);
    setIsLoadingBudgetBuckets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgetBuckets(res.buckets);
  };

Whenever the budget data or bucket data is updated, I want to call another function that checks for errors. However when the page loads, I need it to wait for both of those functions to be finished before it checks for errors.

Edit #2:

After some debugging, it looks like the issue might have to do with when React updates the state. Since I am trying to check for errors in data saved in the state.

Body:
I discovered the issue was caused by how React chooses when to update the state and not how I was calling these functions asynchronously.

I was able to call my Error check function by hooking it into the output of the data fetch calls. This makes sure that the error check only runs when either the budgets or buckets are edited and finished being changed.

useEffect(() => {
    getWarningsAndErrors();
  }, [budgets, budgetBuckets]) //Update errors whenever we edit budgets or buckets


问:
Minecraft Server Paused after my Custom Plugin Loading
this problem has started after I fixed my Plugin in the maven file with erasing this.

```<code><outputDirectory>D:\My New Plugins\Server\plugins</outputDirectory>
</code>```

this breaked my first test Server erasing all the Plugin Folder Files and damaged the code. Then after reopening the server, the server always stops at this part:

Which I was worried considering my Plugin is broken. Do I have to make a new Plugin and transfer most of the files?

Note: the Last Yellow Lines in the picture Indicate the Use of the JScoreboard dependency used in my plugin. Thanks.

Edit: There is also a warning in the build log:

maven-shade-plugin has detected that some class files are
present in two or more JARs. When this happens, only one
single version of the class is copied to the uber jar.
Usually this is not harmful and you can skip these warnings,
otherwise try to manually exclude artifacts based on
mvn dependency:tree -Ddetail=true and the above output.
See http://maven.apache.org/plugins/maven-shade-plugin/

This might be Related.

答: The problem appears to be JScoreBoards. It does not support Minecraft version 1.18, and therefore is unable to load up properly.</p>

Body:
this problem has started after I fixed my Plugin in the maven file with erasing this.

<outputDirectory>D:\My New Plugins\Server\plugins</outputDirectory>

this breaked my first test Server erasing all the Plugin Folder Files and damaged the code. Then after reopening the server, the server always stops at this part:

Which I was worried considering my Plugin is broken. Do I have to make a new Plugin and transfer most of the files?

Note: the Last Yellow Lines in the picture Indicate the Use of the JScoreboard dependency used in my plugin. Thanks.

Edit: There is also a warning in the build log:

maven-shade-plugin has detected that some class files are
present in two or more JARs. When this happens, only one
single version of the class is copied to the uber jar.
Usually this is not harmful and you can skip these warnings,
otherwise try to manually exclude artifacts based on
mvn dependency:tree -Ddetail=true and the above output.
See http://maven.apache.org/plugins/maven-shade-plugin/

This might be Related.


问:
How do I render a list on API response in vue 3?
I am new to vue and trying to render a list of items from an API response

<template>

        <ServiceCard :name="service.subdomain" :host="yaml.host" :subdomain="service.subdomain" />

</template>
```

Coming from react, I would expect a re-render to occur when I update the value of yaml. I have tried wrapping it with reactive() but I don't understand vue well enough.
I don't understand why my v-if remains falsy after I set yaml's value.

Is v-if even the right way to handle this?

With this code, I get the error:

TypeError: Cannot read properties of undefined (reading 'services')

答:
To be reactive a variable must be wrapped in a ref (or reactive (the difference is not important for you for now)),

in your case, init your variable with an empty object

```<code>import { Ref, ref } from 'vue'
let yaml: Ref<ServiceAPIResponse> = ref({})
</code>```

then when you want to assign new values

```<code>yaml.value = data;
</code>```

Body:
I am new to vue and trying to render a list of items from an API response

<template>

        <ServiceCard :name="service.subdomain" :host="yaml.host" :subdomain="service.subdomain" />

</template>

Coming from react, I would expect a re-render to occur when I update the value of yaml. I have tried wrapping it with reactive() but I don't understand vue well enough.
I don't understand why my v-if remains falsy after I set yaml's value.

Is v-if even the right way to handle this?

With this code, I get the error:

TypeError: Cannot read properties of undefined (reading 'services')

Body:
To be reactive a variable must be wrapped in a ref (or reactive (the difference is not important for you for now)),

in your case, init your variable with an empty object

import { Ref, ref } from 'vue'
let yaml: Ref<ServiceAPIResponse> = ref({})

then when you want to assign new values

yaml.value = data;


问:
ERC20: transfer amount exceeds allowance, even when it is approved
Returned error: VM Exception while processing transaction: revert ERC20: transfer amount exceeds allowance

Code:

```<code>ERC20Tokens[tokenTicker].token.approve(ERC20Tokens[tokenTicker].tokenHolder, 10);

emit tokenOwnerBalance(ERC20Tokens[tokenTicker].token.balanceOf(ERC20Tokens[tokenTicker].tokenHolder));

ERC20Tokens[tokenTicker].token.transferFrom(ERC20Tokens[tokenTicker].tokenHolder, address(this), 1);
</code>```

Logs:

```<code>[
   {
      "from":"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
      "topic":"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925",
      "event":"Approval",
      "args":{
         "0":"0x7A2946b37399fa3F1C9EF81c7Bcf94AE1099D18F",
         "1":"0x95Ba4cF87D6723ad9C0Db21737D862bE80e93911",
         "2":"10",
         "owner":"0x7A2946b37399fa3F1C9EF81c7Bcf94AE1099D18F",
         "spender":"0x95Ba4cF87D6723ad9C0Db21737D862bE80e93911",
         "value":"10"
      }
   },
   {
      "from":"0x7A2946b37399fa3F1C9EF81c7Bcf94AE1099D18F",
      "topic":"0xcff530ae4ada35c1dd7ac314ef643b9eb7ae40665958ad5899e2fbc18865444a",
      "event":"tokenOwnerBalance",
      "args":{
         "0":"31000000"
      }
   }
]
</code>```

答: For me, it was a mistake of using transferFrom instead of transfer when transferring tokens from the contract.

Body:
Returned error: VM Exception while processing transaction: revert ERC20: transfer amount exceeds allowance

Code:

ERC20Tokens[tokenTicker].token.approve(ERC20Tokens[tokenTicker].tokenHolder, 10);

emit tokenOwnerBalance(ERC20Tokens[tokenTicker].token.balanceOf(ERC20Tokens[tokenTicker].tokenHolder));

ERC20Tokens[tokenTicker].token.transferFrom(ERC20Tokens[tokenTicker].tokenHolder, address(this), 1);

Logs:

[
   {
      "from":"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
      "topic":"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925",
      "event":"Approval",
      "args":{
         "0":"0x7A2946b37399fa3F1C9EF81c7Bcf94AE1099D18F",
         "1":"0x95Ba4cF87D6723ad9C0Db21737D862bE80e93911",
         "2":"10",
         "owner":"0x7A2946b37399fa3F1C9EF81c7Bcf94AE1099D18F",
         "spender":"0x95Ba4cF87D6723ad9C0Db21737D862bE80e93911",
         "value":"10"
      }
   },
   {
      "from":"0x7A2946b37399fa3F1C9EF81c7Bcf94AE1099D18F",
      "topic":"0xcff530ae4ada35c1dd7ac314ef643b9eb7ae40665958ad5899e2fbc18865444a",
      "event":"tokenOwnerBalance",
      "args":{
         "0":"31000000"
      }
   }
]


问:
Single XMLHTTPRequest object to make multiple requests
Does anyone know if there is a way to use a single XMLHTTPRequest object to send multiple asynchronous requests.  I can do it with a single request and get a response back from my onreadystatechange() handler.

I'm wondering if there's a way to use the same object to send multiple parallel requests but I'm not seeing any way to match a response to a request from the onreadystatechange() function.

答: +1 to Martijn's answer, but I wanted to add that the enlightenment you're missing is that a Request is by definition a one time object.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brian Campbell

OwnerDisplayName: annakata


问:
ApplicationSettings isn't saved properly
I'm trying to save two Lists of objects in the phone ApplicationSettings, but I'm stuck at a strange issue (But it's probably me making a silly mistake somewhere).

If I only save one of the lists, it works as supposed - It'll save it, and reload it when app is launched next time.
But if I try to save 2 lists, none of them seem to be saved correctly. No errors or anything, just "blankness".

See code below.

```<code>//My save method
public void Gem()
        {
            var settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains(INDTASTNINGER_LIST))
            {
                settings[INDTASTNINGER_LIST] = _indtastningsListe;
            }
            else
                settings.Add(INDTASTNINGER_LIST, _indtastningsListe);

            if (settings.Contains(INDTASTNINGER_LIST2))
            {
                settings[INDTASTNINGER_LIST2] = _indtastningsListe2;
            }
            else
                settings.Add(INDTASTNINGER_LIST2, _indtastningsListe2);
            settings.Save();
        }

        //Constructor supposed to load settings
        public Indtastninger()
        {
            var settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains(INDTASTNINGER_LIST))
            {
                _indtastningsListe = null;
                _indtastningsListe = (List<Indtastning>)settings[INDTASTNINGER_LIST];
            }
            if (settings.Contains(INDTASTNINGER_LIST2))
            {
                _indtastningsListe2 = null;
                _indtastningsListe2 = (List<Indtastning>)settings[INDTASTNINGER_LIST2];
            }
        }
</code>```

What am I doing wrong?
If I comment out the part with "list2" stuff, the first one will be saved/retrieved perfectly.

答:
I have faced the same issue some time ago, the problem is that you only can save on the IsolatedStorage objects that are XML serializables.

if you save other object, it will work even with the debugger but when the app is restarted, all the saved data is lost.

Body:
I'm trying to save two Lists of objects in the phone ApplicationSettings, but I'm stuck at a strange issue (But it's probably me making a silly mistake somewhere).

If I only save one of the lists, it works as supposed - It'll save it, and reload it when app is launched next time.
But if I try to save 2 lists, none of them seem to be saved correctly. No errors or anything, just "blankness".

See code below.

//My save method
public void Gem()
        {
            var settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains(INDTASTNINGER_LIST))
            {
                settings[INDTASTNINGER_LIST] = _indtastningsListe;
            }
            else
                settings.Add(INDTASTNINGER_LIST, _indtastningsListe);

            if (settings.Contains(INDTASTNINGER_LIST2))
            {
                settings[INDTASTNINGER_LIST2] = _indtastningsListe2;
            }
            else
                settings.Add(INDTASTNINGER_LIST2, _indtastningsListe2);
            settings.Save();
        }

        //Constructor supposed to load settings
        public Indtastninger()
        {
            var settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains(INDTASTNINGER_LIST))
            {
                _indtastningsListe = null;
                _indtastningsListe = (List<Indtastning>)settings[INDTASTNINGER_LIST];
            }
            if (settings.Contains(INDTASTNINGER_LIST2))
            {
                _indtastningsListe2 = null;
                _indtastningsListe2 = (List<Indtastning>)settings[INDTASTNINGER_LIST2];
            }
        }

What am I doing wrong?
If I comment out the part with "list2" stuff, the first one will be saved/retrieved perfectly.


问:
How to get ODATA to serialize NotMapped property
I have a WebAPI backend that provides inventory information, etc. to various clients, using ODATA v3 (I cannot use v4 due to a restriction in a component that we use).  The inventory database is quite large (100K+ records) and ODATA is great for server-side filtering, pagination, etc. and keeping the data transfers lean.

The inventory records have some properties that are not mapped, but rather calculated and populated on the fly as the queries are made.  For example:

```<code>[NotMapped]
public decimal RebateAmount { get; set; }
</code>```

The problem is that ODATA ignores any NotMapped properties, so they never get sent back to the clients.

I know this has been asked before, but that was a while ago now so I was hoping that support for this has been added by now or that somebody has a simple workaround (short of letting EF create these fields in the DB).

I have tried this ugly workaround, but it did not work (RebateAmount still does not get included by ODATA):

```<code>private decimal _rebateAmount;
public decimal RebateAmount { get {return _rebateAmount; } }

public void SetRebateAmount(decimal amount)
{
   _rebateAmount = amount;
}
</code>```

Is there a (preferably simple) way to include non-DB properties in ODATA result sets?

Edit 1/7/2017
For this to be useful in my scenario, ODATA needs to also include the calculated fields in its metadata, otherwise the auto-generated (client-side) proxy classes will not include them.

答:
If you run into this issue, the above suggestions don't work in later versions of EF.  I was able to get it working with the following:

```<code>// Add this to the DB Context:
// *****************************************
modelBuilder.Entity<ModelObject>().Ignore(a => a.PropertyName);

// Add this to the Model Object
// *****************************************
public string PropertyName {
    get { return _expression1.Evaluate(this); }
    set { }     // # This is the magic piece that makes it work
}
</code>```

The magic piece being the setter.

Body:
I have a WebAPI backend that provides inventory information, etc. to various clients, using ODATA v3 (I cannot use v4 due to a restriction in a component that we use).  The inventory database is quite large (100K+ records) and ODATA is great for server-side filtering, pagination, etc. and keeping the data transfers lean.

The inventory records have some properties that are not mapped, but rather calculated and populated on the fly as the queries are made.  For example:

[NotMapped]
public decimal RebateAmount { get; set; }

The problem is that ODATA ignores any NotMapped properties, so they never get sent back to the clients.

I know this has been asked before, but that was a while ago now so I was hoping that support for this has been added by now or that somebody has a simple workaround (short of letting EF create these fields in the DB).

I have tried this ugly workaround, but it did not work (RebateAmount still does not get included by ODATA):

private decimal _rebateAmount;
public decimal RebateAmount { get {return _rebateAmount; } }

public void SetRebateAmount(decimal amount)
{
   _rebateAmount = amount;
}

Is there a (preferably simple) way to include non-DB properties in ODATA result sets?

Edit 1/7/2017
For this to be useful in my scenario, ODATA needs to also include the calculated fields in its metadata, otherwise the auto-generated (client-side) proxy classes will not include them.

Body:
If you run into this issue, the above suggestions don't work in later versions of EF.  I was able to get it working with the following:

// Add this to the DB Context:
// *****************************************
modelBuilder.Entity<ModelObject>().Ignore(a => a.PropertyName);

// Add this to the Model Object
// *****************************************
public string PropertyName {
    get { return _expression1.Evaluate(this); }
    set { }     // # This is the magic piece that makes it work
}

The magic piece being the setter.


问:
Check if array value is between two array values within an array
I have an array containing another array of numbers such as:

```<code>[[0, 1350], [1350, 2700], [2700, 3375]]
</code>```

What I want to do loop though this array and check a given value is in between the two values and if it is add this to a new array.

For example say I have the value of 1320, the desired result would be this.

```<code>[0, 1350]
</code>```

I am a little stuck on how to achieve this I know it requires two loops however im unsure on how to match the value to the elements.

What I have so far

```<code>const exampleFunction = (number: number) => {
    const numberArray = [[0, 1350], [1350, 2700], [2700, 3375]];
      const array = [];
        numberArray.map((element, index) => {
          element.map((value) => {
    // do something here?
          });
        });
}

exampleFunction(1320);
</code>```

答:
```<code>            const findValuesInRange = (arr1, num)=>{
              return  arr1.filter(f => f.length > 1 && (Math.min(f[0], f[1]) < num && Math.max(f[0], f[1]) >= num))
            }

            const arr1 = [[0, 1350], [1350, 2700], [2700, 3375]]

            console.log(findValuesInRange(arr1,1350))
</code>```

Body:
I have an array containing another array of numbers such as:

[[0, 1350], [1350, 2700], [2700, 3375]]

What I want to do loop though this array and check a given value is in between the two values and if it is add this to a new array.

For example say I have the value of 1320, the desired result would be this.

[0, 1350]

I am a little stuck on how to achieve this I know it requires two loops however im unsure on how to match the value to the elements.

What I have so far

const exampleFunction = (number: number) => {
    const numberArray = [[0, 1350], [1350, 2700], [2700, 3375]];
      const array = [];
        numberArray.map((element, index) => {
          element.map((value) => {
    // do something here?
          });
        });
}

exampleFunction(1320);


问:
How to make noWrap work with Breadcrumbs?
I'm trying to make the MUI component Breadcrumbs responsive:

When the Breadcrumbs component takes all of its space, its items shrink using ellipsis like any Typography component with noWrap prop set.

I know it has itemsBeforeCollapse, itemsAfterCollapse and maxItems props but these props are about item number compared to viewport size, not about each item width.

I tried to set the noWrap property to Typography and Link components (as it extends Typography props), but the ellipsis does not show up and the Link or Typography component does not shrink.

```<code><Breadcrumbs>
  {links.map((link, i) =>
    i !== links.length - 1 ? (
      <Link
        key={i}
        underline={'hover'}
        noWrap
      >
        {link}
      </Link>
    ) : (
      <Typography noWrap key={i}>
        {link}
      </Typography>
    ),
  )}
</Breadcrumbs>
</code>```

You can reproduce the issue on this codeSandbox:

答:
If I understand you correctly, the problem is that the noWrap style is not affecting the right element.

Why?

noWrap affect elements that its width limited either explicit (e.g. width: 100px) or implicit (by parent's width).

In your case, the Link and the Typography's width is not limited.

What can you do?

Breadcrumbs renders ol with display: flex. In order to force the children (li) to stand a line (and take a third in your case) you should give it flex: 1. From this point, you can give the li the ellipsis styles.

The last part, how to give the li these styles? There are some ways as described at the css section.

I would take the styled approach and this is how it looks

import * as React from "react";
import Typography from "@mui/material/Typography";
import Breadcrumbs from "@mui/material/Breadcrumbs";
import Link from "@mui/material/Link";
import { styled } from "@mui/material/styles";

const StyledBreadcrumbs = styled(Breadcrumbs)`
  .MuiBreadcrumbs-li {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
  }
`;

export default function BasicBreadcrumbs() {
  const links = [
    "this is a waaaaaaaaaaaaay too long link",
    "and another link that can be long too",
    "this is the last link and guess what? It's waaaaaaaaaaaaaaaaaaayyy more longer"
  ];
  return (

  );
}
```

https://codesandbox.io/s/basicbreadcrumbs-material-demo-forked-y1bbo?file=/demo.js

Body:
I'm trying to make the MUI component Breadcrumbs responsive:

When the Breadcrumbs component takes all of its space, its items shrink using ellipsis like any Typography component with noWrap prop set.

I know it has itemsBeforeCollapse, itemsAfterCollapse and maxItems props but these props are about item number compared to viewport size, not about each item width.

I tried to set the noWrap property to Typography and Link components (as it extends Typography props), but the ellipsis does not show up and the Link or Typography component does not shrink.

<Breadcrumbs>
  {links.map((link, i) =>
    i !== links.length - 1 ? (
      <Link
        key={i}
        underline={'hover'}
        noWrap
      >
        {link}
      </Link>
    ) : (
      <Typography noWrap key={i}>
        {link}
      </Typography>
    ),
  )}
</Breadcrumbs>

You can reproduce the issue on this codeSandbox:

Body:
If I understand you correctly, the problem is that the noWrap style is not affecting the right element.

Why?

noWrap affect elements that its width limited either explicit (e.g. width: 100px) or implicit (by parent's width).

In your case, the Link and the Typography's width is not limited.

What can you do?

Breadcrumbs renders ol with display: flex. In order to force the children (li) to stand a line (and take a third in your case) you should give it flex: 1. From this point, you can give the li the ellipsis styles.

The last part, how to give the li these styles? There are some ways as described at the css section.

I would take the styled approach and this is how it looks

import * as React from "react";
import Typography from "@mui/material/Typography";
import Breadcrumbs from "@mui/material/Breadcrumbs";
import Link from "@mui/material/Link";
import { styled } from "@mui/material/styles";

const StyledBreadcrumbs = styled(Breadcrumbs)`
  .MuiBreadcrumbs-li {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
  }
`;

export default function BasicBreadcrumbs() {
  const links = [
    "this is a waaaaaaaaaaaaay too long link",
    "and another link that can be long too",
    "this is the last link and guess what? It's waaaaaaaaaaaaaaaaaaayyy more longer"
  ];
  return (
    <StyledBreadcrumbs>
      {links.map((link, i) =>
        i !== links.length - 1 ? (
          <Link key={i} underline={"hover"}>
            {link}
          </Link>
        ) : (
          <Typography key={i}>
            {link}
          </Typography>
        )
      )}
    </StyledBreadcrumbs>
  );
}

https://codesandbox.io/s/basicbreadcrumbs-material-demo-forked-y1bbo?file=/demo.js


问:
Must contain a non-null value and possible null reference
I'm trying to switch to .Net 6.0 from .Net 3.1 and I encounter a few issues.

Apparently, in .Net 6.0 models need to have non-nullable property, for example:

```<code>public string Email { get; set; } = String.Empty;
</code>```

The problem for the DbSet I fixed like:

```<code>public DbSet<User>? Users { get; set; }
</code>```

However, now I'm getting warnings of possible null reference argument/return as the image below:

答:
Models don't "need to have non-nullable properties". It's just a suggestion.

If this is not the behavior you want you can open csproj file and either remove this line or make it disable

```<code><Nullable>enable</Nullable>
</code>```

Body:
I'm trying to switch to .Net 6.0 from .Net 3.1 and I encounter a few issues.

Apparently, in .Net 6.0 models need to have non-nullable property, for example:

public string Email { get; set; } = String.Empty;

The problem for the DbSet I fixed like:

public DbSet<User>? Users { get; set; }

However, now I'm getting warnings of possible null reference argument/return as the image below:

Body:
Models don't "need to have non-nullable properties". It's just a suggestion.

If this is not the behavior you want you can open csproj file and either remove this line or make it disable

<Nullable>enable</Nullable>


问:
Chrome vertically aligns any image opened in a new tab
Whenever you open an image in chrome, it displays it in a dark background with vertically and horizontally centered.
I just wondered which CSS properties Chrome uses to achieve that. Chrome just uses

```<code>body{height:100%;} img{margin:auto, display:block}
</code>```

https://i.giphy.com/media/UqUHuT6y9mK5HfsYFm/giphy.webp

inspect this sample link. The problem is it doesn't work when you apply the same rules. Do I miss something? Also I did not see before vertically aligning an image with margin:auto.

答:
This alignment is done internally by Chrome rather than by using CSS.

If you look at the URL when you open a local file, Chrome uses file:/// rather than a standard http(s):// URL, which Chrome detects and adjusts the layout accordingly.

Quite misleading that they have the inline CSS on the elements when it's done internally, but the layout you talk about isn't achievable with only the CSS specified above.

The default HTML when rendering an image file directly is below and as you can see it has inline style attributes on the body/img tags, but the same HTML in a standalone document renders the image in the top left corner.

UPDATE

The CSS does seem to be affecting the layout, but the same CSS in a standalone HTML document does not layout the page with the content/image vertically and/or horizontally centred.

```<code><html style="height: 100%;">
  <head>
    <meta name="viewport" content="width=device-width, minimum-scale=0.1">
    <title>the-head.png (700×467)</title>
  </head>
  <body style="margin: 0px; background: #0e0e0e; height: 100%">
    <img style="-webkit-user-select: none;margin: auto;background-color: hsl(0, 0%, 90%);transition: background-color 300ms;" src="file:///C:/Users/djalx/Pictures/the-head.png">
  </body>
</html>
</code>```

Body:
Whenever you open an image in chrome, it displays it in a dark background with vertically and horizontally centered.
I just wondered which CSS properties Chrome uses to achieve that. Chrome just uses

body{height:100%;} img{margin:auto, display:block}

https://i.giphy.com/media/UqUHuT6y9mK5HfsYFm/giphy.webp

inspect this sample link. The problem is it doesn't work when you apply the same rules. Do I miss something? Also I did not see before vertically aligning an image with margin:auto.

Body:
This alignment is done internally by Chrome rather than by using CSS.

If you look at the URL when you open a local file, Chrome uses file:/// rather than a standard http(s):// URL, which Chrome detects and adjusts the layout accordingly.

Quite misleading that they have the inline CSS on the elements when it's done internally, but the layout you talk about isn't achievable with only the CSS specified above.

The default HTML when rendering an image file directly is below and as you can see it has inline style attributes on the body/img tags, but the same HTML in a standalone document renders the image in the top left corner.

UPDATE

The CSS does seem to be affecting the layout, but the same CSS in a standalone HTML document does not layout the page with the content/image vertically and/or horizontally centred.

<html style="height: 100%;">
  <head>
    <meta name="viewport" content="width=device-width, minimum-scale=0.1">
    <title>the-head.png (700×467)</title>
  </head>
  <body style="margin: 0px; background: #0e0e0e; height: 100%">
    <img style="-webkit-user-select: none;margin: auto;background-color: hsl(0, 0%, 90%);transition: background-color 300ms;" src="file:///C:/Users/djalx/Pictures/the-head.png">
  </body>
</html>


问:
How to add man and zip to "git bash" installation on Windows
I am using git bash on Windows - that is git for Windows via the integrated bash. Apparently it uses the MINGW/MSYS underpinning. (Update from @VonC: It now uses msys2 since msysgit is obsolete since Q4 2015.)

So there are already a lot of MSYS tools installed - from awk to zcat. However I miss the man command and zip to compress multiple files into a zip file (unzip exists!).

Where from can I install them? I do not want to install another copy of the MINGW system! Any way just to add some pre-compiled tools to the git bash installation?

答:
On Windows, you can use tar instead of zip.

```<code>tar -a -c -f output.zip myfile.txt
</code>```

which is same as,

```<code>zip output.zip myfile.txt
</code>```

no need to install any external zip tool.

Body:
On Windows, you can use tar instead of zip.

tar -a -c -f output.zip myfile.txt

which is same as,

zip output.zip myfile.txt

no need to install any external zip tool.


问:
How to fix "Head detached from <commit>"?
I checked out a previous commit in my project recently, and just noticed when I ran git status that it was returning HEAD detached from 7263532. These are my most recent two commits:

commit 8a870e8a1cb63bac7e9ec732908e54f20e841bb3 (HEAD)

commit 72635327285025d2e89962fc7ff854a8c67fdfe1 (dev-updates)

dev-updates is the name of my current branch.

I thought I had checked back out my most recent commit after checking out the previous one. I have edits in my working directory that I don't want to lose. What I want to know is, how do I fix the HEAD detached warning without losing any of my work?

答:
Make a temp branch. Add and commit to it. Switch to dev-updates. Cherry pick temp. Delete the temp branch. So:</p>
```<code>git switch -c temp
git add .
git commit -mtemp
git switch dev-updates
git cherry-pick temp
git branch -D temp
</code>```

Body:
Make a temp branch. Add and commit to it. Switch to dev-updates. Cherry pick temp. Delete the temp branch. So:

git switch -c temp
git add .
git commit -mtemp
git switch dev-updates
git cherry-pick temp
git branch -D temp


问:
Mysql on Ubuntu - variables - syntax error
I have mysql 8 installed on Ubuntu and when I do:

```<code>SET @test := 'test'; SELECT @test;
</code>```

Then I have error:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near 'SELECT @test' at line 1

Why? Should I set something special in mysql configuration?

答:
It looks like you're trying to use multi-query, sending more than one SQL statement in a single call to the query interface. This is not supported in most client connectors by default. Some connectors have an option to enable it.

Multi-query is not supported for prepared statements regardless of any connector options.

The use cases for multi-query are very rare exceptions. Almost certainly you don't need to use multi-query.

Instead, submit one SQL statement per call to the query interface. Your session variable @test will retain its value on subsequent calls using the same MySQL session.

Body:
I have mysql 8 installed on Ubuntu and when I do:

SET @test := 'test'; SELECT @test;

Then I have error:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near 'SELECT @test' at line 1

Why? Should I set something special in mysql configuration?


问:
String arrays methods and if statement
here, it gives b's element as null rather than storing array a's value. Basically, I can't go inside the if statement</p>
```<code>public class Dil {
    public static void main(String[] args) {
        String s = "is2 sentence4 This1 a3";
        String a[]=s.split(" ");
        String b[]=new String[a.length];
        System.out.println(Arrays.toString(a));
        for(int i=1;i<a.length;i++){
            for(int j=0;j<a.length-1;j++){
                if(a[j].charAt(a[j].length()-1)==i){
                    b[i-1]=a[j];
                    break;
                }

            }
        }
        System.out.println(Arrays.toString(b));
    }
}
</code>```

答:
You have two unrelated problems.

here, it gives b's element as null rather than storing array a's value.

That's because your instantiating a new and empty array, only providing to it the size of array a (not the values!), with:

String b[] = new String[a.length];
```
<p>If you want to copy an array, better do:</p>
<pre class="lang-java prettyprint-override"><code>String[] a = new String[] {/*..your array..*/};
String[] b = new String[a.length];
System.arraycopy(a, 0, b, 0, a.length);
</code>```

or

String[] b = Arrays.copyOf(a, a.length);
```
<hr />
<blockquote>
<p><em>Basically, I can't go inside the if statement</em></p>
</blockquote>
<p>Variable of type <code>char</code>, indeed can store a number, as under the hood, chars are represented as ASCII codes.</p>
<p>Therefore, your:</p>
```(a[j].charAt(a[j].length()-1)==i)
```

would only evaluate to true, when i will be equal to ASCII code of the char in question; however, characters represented with [0; 31] codes, are non-printable ones, which, most likely, will not be include in your strings and hence - your if's condition will not evaluate to true.

Title: String arrays methods and if statement

Body:
here, it gives b's element as null rather than storing array a's value. Basically, I can't go inside the if statement

public class Dil {
    public static void main(String[] args) {
        String s = "is2 sentence4 This1 a3";
        String a[]=s.split(" ");
        String b[]=new String[a.length];
        System.out.println(Arrays.toString(a));
        for(int i=1;i<a.length;i++){
            for(int j=0;j<a.length-1;j++){
                if(a[j].charAt(a[j].length()-1)==i){
                    b[i-1]=a[j];
                    break;
                }

            }
        }
        System.out.println(Arrays.toString(b));
    }
}

Body:
You have two unrelated problems.

here, it gives b's element as null rather than storing array a's value.

That's because your instantiating a new and empty array, only providing to it the size of array a (not the values!), with:

String b[] = new String[a.length];

If you want to copy an array, better do:

String[] a = new String[] {/*..your array..*/};
String[] b = new String[a.length];
System.arraycopy(a, 0, b, 0, a.length);

or

String[] b = Arrays.copyOf(a, a.length);

Basically, I can't go inside the if statement

Variable of type char, indeed can store a number, as under the hood, chars are represented as ASCII codes.

Therefore, your:

(a[j].charAt(a[j].length()-1)==i)

would only evaluate to true, when i will be equal to ASCII code of the char in question; however, characters represented with [0; 31] codes, are non-printable ones, which, most likely, will not be include in your strings and hence - your if's condition will not evaluate to true.


问:
React doesn't render autocomplete off
How do I make react render it?</p>

```<code><input
    id={field.name}
    className="form-control"
    type="text"
    placeholder={field.name}
    autocomplete="off"
    {...field}/>
</code>```

答:
First check if value is coming from auto complete feature

```<code>function isValueComingFromAutoComplete(_value, field) {
  return _value.length > 1 && inputs[field].value === "";
}
</code>```

And then add the condition

```<code>function handleInputChange(_value, field) {
  if (!isValueComingFromAutoComplete(_value, field)) {
     // change state
  }
}
</code>```

Note that it won't work if the input value has length 1.

Title: React doesn't render autocomplete off

Body:
How do I make react render it?

<input
    id={field.name}
    className="form-control"
    type="text"
    placeholder={field.name}
    autocomplete="off"
    {...field}/>

Body:
First check if value is coming from auto complete feature

function isValueComingFromAutoComplete(_value, field) {
  return _value.length > 1 && inputs[field].value === "";
}

And then add the condition

function handleInputChange(_value, field) {
  if (!isValueComingFromAutoComplete(_value, field)) {
     // change state
  }
}

Note that it won't work if the input value has length 1.


问:
How can I access the keys and values of the dictionary that is created by calling constructor __init__() from a function made inside a class?
I have created a class where I've passed an argument dictionary in the constructor. Now I need to make a function inside a class where I could access the information of that created dictionary and print users information. My attempt in doing so generates an error 'dict' object is not callabe.

class User:
    def __init__(self,first_name,last_name,**info):
        info['first_name']=first_name
        info['last_name']=last_name
        self.items=info

    def info_user(self):
            print(self.items)

    def users_information(self):
        print('Users Information:\n')
        for key, values in self.items():
            print(key,":",values)

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()
```

答:
Please try with below method:</p>
```<code> def users_information(self):
        print('Users Information:\n')
        for key in self.items:
          print(key, ':', self.items[key])
</code>```

Body:
Please try with below method:

 def users_information(self):
        print('Users Information:\n')
        for key in self.items:
          print(key, ':', self.items[key])


问:
How can I detect the scroll width and differentiate between the mobile and the desktop versions?
Because of diferent sizes of scrollbar I'm getting a problem while using a fixed component in both mobile and desktop:

While the desktop version get correctly aligned with the components below, the mobile version doesn't.
If I fix the width for the mobile the desktop will go over the component limit and it just doesn't work.

My css for it is as follow, the commented width is the one that works for the mobile.
Anyone have any ideas?

```<code>.fixed-header {
  position: fixed;
  top: 56px;
  left: 14px;
  width: calc(100vw - 45px); //calc(100vw - 30px);
  z-index: 2;

  @include md {
    position: relative;
  }
}
</code>```

答:
I managed to do it by testing the scroll width in the ngOnInit as suggested in this answer (I edited a little for convenience), to test if it was mobile or not:

```<code>testIsMobile() {
    var scrollbox = document.createElement('div');
    scrollbox.style.overflow = 'scroll';
    document.body.appendChild(scrollbox);

    var scrollWidth = scrollbox.offsetWidth - scrollbox.clientWidth;

    document.body.removeChild(scrollbox);

    this.isMobile = scrollWidth == 0
}
</code>```

Then I added the correct class through [ngClass]="fixedHeaderClass"

```<code>if (this.isMobile)
  this.fixedHeaderClass = "fixed-header-mobile";
else
  this.fixedHeaderClass = "fixed-header";
</code>```

Body:
Because of diferent sizes of scrollbar I'm getting a problem while using a fixed component in both mobile and desktop:

While the desktop version get correctly aligned with the components below, the mobile version doesn't.
If I fix the width for the mobile the desktop will go over the component limit and it just doesn't work.

My css for it is as follow, the commented width is the one that works for the mobile.
Anyone have any ideas?

.fixed-header {
  position: fixed;
  top: 56px;
  left: 14px;
  width: calc(100vw - 45px); //calc(100vw - 30px);
  z-index: 2;

  @include md {
    position: relative;
  }
}

Body:
I managed to do it by testing the scroll width in the ngOnInit as suggested in this answer (I edited a little for convenience), to test if it was mobile or not:

testIsMobile() {
    var scrollbox = document.createElement('div');
    scrollbox.style.overflow = 'scroll';
    document.body.appendChild(scrollbox);

    var scrollWidth = scrollbox.offsetWidth - scrollbox.clientWidth;

    document.body.removeChild(scrollbox);

    this.isMobile = scrollWidth == 0
}

Then I added the correct class through [ngClass]="fixedHeaderClass"

if (this.isMobile)
  this.fixedHeaderClass = "fixed-header-mobile";
else
  this.fixedHeaderClass = "fixed-header";


问:
Trigger an on screen keyboard on windows using react native
I am using a windows device with a touch screen, I would like for an input field that I have to open the on-screen windows keyboard, is there a way to do that in react native for windows?</p>

答:
You can initiate focus on component mount. Give a ref to TextInput using useRef().

```<code>const ref = useRef<TextInput|null>(null); // If you are using typescript

// If not then just
// const ref = useRef();

React.useEffect(() => {
  ref.current?.focus();
}, []);

<TextInput ref={ref} {...otherProps} />;

</code>```

Body:
You can initiate focus on component mount. Give a ref to TextInput using useRef().

const ref = useRef<TextInput|null>(null); // If you are using typescript

// If not then just
// const ref = useRef();

React.useEffect(() => {
  ref.current?.focus();
}, []);

<TextInput ref={ref} {...otherProps} />;


问:
Throwing exception from okhttp3 Intercepter crashing when using suspended functions in retrofit service

List item

I am making a simple network call where I thrown an exception from an Interceptor when network is not available to show appropriate message to the user.
When I model the call as a suspended function and emit the data in ViewModel, I am getting a crash in the app without a stack trace for the issue:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.x.x.x.debug, PID: 14247
</code>```

Definition causing crash:

Service

```<code>interface Service {
    @GET("v1/count")
    suspend fun getCounts(): Response<Counts>
}
</code>```

Repository:

```<code>suspend fun getCounts(): Response<Counts> {
    return withContext(Dispatchers.IO) { service.getCounts() }
}
</code>```

ViewModel

```<code>fun getCounts(): LiveData<Response<Counts>> = liveData { emit(repository.getCounts()) }
</code>```

Observer in Fragment:

```<code>viewModel.getCounts().observe(viewLifecycleOwner, {
            if (it.isSuccessful) {
                ...
            }
        })
</code>```

Definition working fine:

```<code>interface Service {
    @GET("v1/count")
    fun getCounts(): Call<FeesCounts>
}
</code>```

Note: The crash doesn't come in both cases above if there is no exception thrown in the Interceptor.

Any thoughts on what could be the root cause of such a behaviour?

Thanks.

答:
Modify it like this :

```<code>data class Hello (
    val count: Long = 0
)
</code>```

Keep the "count" same as JSON response.

Body:
List item

I am making a simple network call where I thrown an exception from an Interceptor when network is not available to show appropriate message to the user.
When I model the call as a suspended function and emit the data in ViewModel, I am getting a crash in the app without a stack trace for the issue:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.x.x.x.debug, PID: 14247

Definition causing crash:

Service

interface Service {
    @GET("v1/count")
    suspend fun getCounts(): Response<Counts>
}

Repository:

suspend fun getCounts(): Response<Counts> {
    return withContext(Dispatchers.IO) { service.getCounts() }
}

ViewModel

fun getCounts(): LiveData<Response<Counts>> = liveData { emit(repository.getCounts()) }

Observer in Fragment:

viewModel.getCounts().observe(viewLifecycleOwner, {
            if (it.isSuccessful) {
                ...
            }
        })

Definition working fine:

interface Service {
    @GET("v1/count")
    fun getCounts(): Call<FeesCounts>
}

Note: The crash doesn't come in both cases above if there is no exception thrown in the Interceptor.

Any thoughts on what could be the root cause of such a behaviour?

Thanks.

Body:
Modify it like this :

data class Hello (
    val count: Long = 0
)

Keep the "count" same as JSON response.


问:
I have a problrm with if statement and while loop and dictionary in python
```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif r not in men:
        print('Sorry, the number is not found')
    elif r >= 11:
        while r >= 11:
            r = r + 1 == 1
            print('This is invalid number')
mo()
</code>```

I have problem in the elif. What I want is if I write more than 10 characters in the console, then the code will print 'This is invalid number'. But instead the code prints 'Sorry, the number is not found'.

Output:

```<code>Please Enter The Number: 111111111111111
Sorry, the number is not found

Process finished with exit code 0
</code>```

答:
if / elif / else

runs until the first condition is met.
in your case, the first condition met is r not in men

if(condition):
  do something
elif(condition):
  do something else
elif(condition):
  do something else
else:
  do something
```

You could re-order them, so that the length check happens before checking if it's in the dict.

Body:
men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r = int(input('Please Enter The Number: '))
    if r in men:
        print(men[r])
    elif r not in men:
        print('Sorry, the number is not found')
    elif r >= 11:
        while r >= 11:
            r = r + 1 == 1
            print('This is invalid number')
mo()

I have problem in the elif. What I want is if I write more than 10 characters in the console, then the code will print 'This is invalid number'. But instead the code prints 'Sorry, the number is not found'.

Output:

Please Enter The Number: 111111111111111
Sorry, the number is not found

Process finished with exit code 0

Body:
if / elif / else

runs until the first condition is met.
in your case, the first condition met is r not in men

if(condition):
  do something
elif(condition):
  do something else
elif(condition):
  do something else
else:
  do something

You could re-order them, so that the length check happens before checking if it's in the dict.


问:
App crashes on simulator but works fine in device after upgrading to lion
My app is working fine on simulator all the while until i upgraded to OS Lion & xcode Version 4.1.

Now I got the error below.

EXC_BAD_ACCESS
warning: Unable to restore previously selected frame.

But It's working fine on iPhone.
Appreciate for any suggestion ...

答:
If you're getting an EXC_BAD_ACCESS error that means you're doing something wrong and dealing with either released or uninitialized objects. These errors don't always show up, and when they do, they show up well after the actual infraction. My point is this, just because its working fine on the iPhone doesn't mean the error does not exist.

Try enabling NSZombieEnabled

You can do by clicking on 'Product' in the Xcode top bar.

Press the option key and click on run.

Under environment variables click +

Added NSZombieEnabled and set its value to YES

This should give you more details about the object you're trying to access and help you debug the issue.


问:
Use random file
I have this piece of code:

```<code>com = "node file1.js {var1} {var2} {var3} {var4} {var5}".format(
    var1 = self.CURRENTENTRY[0],
    var2 = self.CURRENTENTRY[1],
    var3 = self.CURRENTENTRY[2],
    var4 = self.CURRENTENTRY[3],
    var5 = ",".join(elist)
)
</code>```

I would like to use more .js files (file2.js, file3.js, ..., filex.js) and let the script to chose one at random each time.

答:
Use following code.</p>
```<code>import random

files = ['file1.js', 'file2.js', 'file3.js']

filename = random.choice(files)
com = "node {filename} {var1} {var2} {var3} {var4} {var5}".format(
        filename,
        va1 = self.CURRENTENTRY[0],
        var2 = self.CURRENTENTRY[1],
        var3 = self.CURRENTENTRY[2],
        var4 = self.CURRENTENTRY[3],
        var5 = ",".join(elist)
    )
</code>```

Title: Use random file

Body:
I have this piece of code:

com = "node file1.js {var1} {var2} {var3} {var4} {var5}".format(
    var1 = self.CURRENTENTRY[0],
    var2 = self.CURRENTENTRY[1],
    var3 = self.CURRENTENTRY[2],
    var4 = self.CURRENTENTRY[3],
    var5 = ",".join(elist)
)

I would like to use more .js files (file2.js, file3.js, ..., filex.js) and let the script to chose one at random each time.

Body:
Use following code.

import random

files = ['file1.js', 'file2.js', 'file3.js']

filename = random.choice(files)
com = "node {filename} {var1} {var2} {var3} {var4} {var5}".format(
        filename,
        va1 = self.CURRENTENTRY[0],
        var2 = self.CURRENTENTRY[1],
        var3 = self.CURRENTENTRY[2],
        var4 = self.CURRENTENTRY[3],
        var5 = ",".join(elist)
    )


问:
jQuery ajax() function is ignoring dataType parameter in Firefox
I'm trying to use jQuery.ajax() to fetch some html, but Firefox is giving me a "junk after document element" error message. As explained here and here the problem seems to be that Firefox is expecting XML from the server, and when it doesn't parse correctly it throws the error. Here's my ajax code:

```<code>jQuery.ajax({
    url: name,
    dataType: "html",
    success: function(result) {
        console.log(result);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});
</code>```

The server returns the html with these response headers:

```<code>Accept-Ranges   bytes
Content-Length  2957
Last-Modified   Tue, 02 Jul 2013 16:16:59 GMT
</code>```

Note that there's no content-type header. I'm sure that adding one would solve the problem, but that's not an option.

The real problem is that Firefox appears to be ignoring the dataType: parameter in the ajax call. I've also tried adding contentType: and accepts: parameters, but it doesn't help.

What am I missing here? How do I force Firefox to process the response as plain text?

答:
The above code is working fine.

you can use the below code. As I noticed your file should be saved in .txt format.

```<code> jQuery.ajax({
    url: "https://www.w3schools.com/jquery/demo_test.txt",
    dataType: "html",
    success: function(result) {
        console.log(result);
        const parser = new DOMParser();
        const res = parser.parseFromString(result, 'text/html');
        console.log(res);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});
</code>```

I have tested this code in Firefox and it's working fine.

Body:
I'm trying to use jQuery.ajax() to fetch some html, but Firefox is giving me a "junk after document element" error message. As explained here and here the problem seems to be that Firefox is expecting XML from the server, and when it doesn't parse correctly it throws the error. Here's my ajax code:

jQuery.ajax({
    url: name,
    dataType: "html",
    success: function(result) {
        console.log(result);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

The server returns the html with these response headers:

Accept-Ranges   bytes
Content-Length  2957
Last-Modified   Tue, 02 Jul 2013 16:16:59 GMT

Note that there's no content-type header. I'm sure that adding one would solve the problem, but that's not an option.

The real problem is that Firefox appears to be ignoring the dataType: parameter in the ajax call. I've also tried adding contentType: and accepts: parameters, but it doesn't help.

What am I missing here? How do I force Firefox to process the response as plain text?

Body:
The above code is working fine.

you can use the below code. As I noticed your file should be saved in .txt format.

 jQuery.ajax({
    url: "https://www.w3schools.com/jquery/demo_test.txt",
    dataType: "html",
    success: function(result) {
        console.log(result);
        const parser = new DOMParser();
        const res = parser.parseFromString(result, 'text/html');
        console.log(res);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

I have tested this code in Firefox and it's working fine.