问:
try to create an array in js then send to controller
Im try to send an array to my controller in Codeigniter,To then be able to use this array in my controller, but gettting a problem in the creation the array repeat the line

here my js function

```<code> function get_array(){
   var datos = [];
   row = {};
  $("#tbl_esctructura tbody > tr").each(function() {
    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(3)').text();
     row["item"] = item;
     row["cantidad"] = cantidad;
     datos.push(row); // you push it to the array
  });

    datos =  JSON.stringify(datos);
}
</code>```

here my controller

```<code>public function data_from_array(){
    $data   =  array($this->input->post('datos', TRUE));

    foreach ($data as $row) {

        echo $row;
    }
}
</code>```

答:
Please modify your code like that.</p>

```<code> function get_array(){
   var datos = [];
  $("#tbl_esctructura tbody > tr").each(function() {
    var row = {};
    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(3)').text();
     row.item = item;
     row.cantidad = cantidad;
     datos.push(row); // you push it to the array
  });

    datos =  JSON.stringify(datos);
}
</code>```

Body:
Im try to send an array to my controller in Codeigniter,To then be able to use this array in my controller, but gettting a problem in the creation the array repeat the line

here my js function

 function get_array(){
   var datos = [];
   row = {};
  $("#tbl_esctructura tbody > tr").each(function() {
    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(3)').text();
     row["item"] = item;
     row["cantidad"] = cantidad;
     datos.push(row); // you push it to the array
  });

    datos =  JSON.stringify(datos);
}

here my controller

public function data_from_array(){
    $data   =  array($this->input->post('datos', TRUE));

    foreach ($data as $row) {

        echo $row;
    }
}

Body:
Please modify your code like that.

 function get_array(){
   var datos = [];
  $("#tbl_esctructura tbody > tr").each(function() {
    var row = {};
    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(3)').text();
     row.item = item;
     row.cantidad = cantidad;
     datos.push(row); // you push it to the array
  });

    datos =  JSON.stringify(datos);
}


来源: stackexchange

问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答:
I'd start by looking at the latest c# enhancements. Also, it really depends on what type of job it is as there are a lot of things an ASP.Net developer won't know about Winforms and vice versa.

Assuming asp.net, I've been asked the following in interviews over the past 18 months:

Page Life Cycle

Generics

Interfaces / basic OO design

SQL; e.g. joins, updates, inserts,
etc.  Also, how to use DataReader and
sqlcommand.

LINQ syntax; not because anyone is really using this, rather because they read about it.

Web Services ( asmx and wcf )

basic html / css

Session strategies for single server
/ load balanced

Differences between gridview,
repeater, etc.

What I've found is that most .net "web" dev's don't know diddly about sql or html.  If you can prove you know more than just how to "drag and drop" controls on a web form then you're already better than 90% of the guys you'll run into.

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: Chris Lively


问:
metrics for comparing training loss in same architecture
I have two models that are training by this architecture in tensorflow, that is not necessarily required for the question, but I am including it if it was important for some readers.

I want to know if I have the same training settings, with two different sub-dataset, but from one data distribution, does it mean if one of them is training slower, it is learning more features?

```<code>        features = tf.placeholder(
        tf.float32, shape=[None, IMAGE_SIZE * IMAGE_SIZE], name='features')
    labels = tf.placeholder(tf.int64, shape=[None], name='labels')
    input_layer = tf.reshape(features, [-1, IMAGE_SIZE, IMAGE_SIZE, 1])
    conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
    conv2 = tf.layers.conv2d(
        inputs=pool1,
        filters=64,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)
    pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
    dense = tf.layers.dense(inputs=pool2_flat, units=2048, activation=tf.nn.relu)
    logits = tf.layers.dense(inputs=dense, units=self.num_classes)
    predictions = {
      "classes": tf.argmax(input=logits, axis=1),
      "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }
    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
    # TODO: Confirm that opt initialized once is ok?
    train_op = self.optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    eval_metric_ops = tf.count_nonzero(tf.equal(labels, predictions["classes"]))
</code>```

答: If you are saying that it has the same setting, then training slower, it could mean that it is learning more. If one of them has a skewed dataset, then it might train faster on some distribution, and it can be an indication, that the training is not learning all feature of the main data distribution.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have two models that are training by this architecture in tensorflow, that is not necessarily required for the question, but I am including it if it was important for some readers.

I want to know if I have the same training settings, with two different sub-dataset, but from one data distribution, does it mean if one of them is training slower, it is learning more features?

        features = tf.placeholder(
        tf.float32, shape=[None, IMAGE_SIZE * IMAGE_SIZE], name='features')
    labels = tf.placeholder(tf.int64, shape=[None], name='labels')
    input_layer = tf.reshape(features, [-1, IMAGE_SIZE, IMAGE_SIZE, 1])
    conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
    conv2 = tf.layers.conv2d(
        inputs=pool1,
        filters=64,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)
    pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
    dense = tf.layers.dense(inputs=pool2_flat, units=2048, activation=tf.nn.relu)
    logits = tf.layers.dense(inputs=dense, units=self.num_classes)
    predictions = {
      "classes": tf.argmax(input=logits, axis=1),
      "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }
    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
    # TODO: Confirm that opt initialized once is ok?
    train_op = self.optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    eval_metric_ops = tf.count_nonzero(tf.equal(labels, predictions["classes"]))


问:
Javascript array of functions: Pass each function as parameter to another function
I have a usercase where I get an array of functions from backend something like:

```<code>var arr = [A(){}, B(){}, C(){}];
</code>```

Now I need a way to execute them such that each function in the array is passed as a parameter to another function in the array.

```<code>A(B(C()));
</code>```

答:
I'm curious how you managed to get the functions from the back-end, but it doesn't matter for your question, so here goes your answer:</p>

```<code>var arr = [A(){}, B(){}, C(){}];

var value = arr[arr.length - 1]();

for (var i = arr.length - 2; i >= 0; i--) {
 value = arr[i](value);
}

console.log(value);
</code>```

Body:
I have a usercase where I get an array of functions from backend something like:

var arr = [A(){}, B(){}, C(){}];

Now I need a way to execute them such that each function in the array is passed as a parameter to another function in the array.

A(B(C()));

Body:
I'm curious how you managed to get the functions from the back-end, but it doesn't matter for your question, so here goes your answer:

var arr = [A(){}, B(){}, C(){}];

var value = arr[arr.length - 1]();

for (var i = arr.length - 2; i >= 0; i--) {
 value = arr[i](value);
}

console.log(value);


问:
Increment all entries in an array by 'n' without a for loop
I have an array:

arr = [5,5,5,5,5,5]

I want to increment a particular range in the arr by 'n'. So if n=2 and the range is [2,5].
The array should look like this:

arr = [5,5,7,7,7,5]

Needed to do this without a for loop, for a problem im trying to solve.

Tried:

arr[2:5] = [n]*3

but that obviously replaces the entries and becomes:

arr = [5,5,3,3,3,5]

Any suggestions would be highly appriciated.

答:
```<code>n = 2
arr_range = slice(2, 5)
arr = [5,5,7,7,7,5]
arr[arr_range] = map(lambda x: x+n, arr[arr_range])
# arr
# [5, 5, 9, 9, 9, 5]
</code>```

But I would recommend using numpy...

```<code>import numpy as np
n = 2
arr_range = slice(2, 5)
arr = np.array([5,5,7,7,7,5])
arr[arr_range] += n
</code>```

Body:
n = 2
arr_range = slice(2, 5)
arr = [5,5,7,7,7,5]
arr[arr_range] = map(lambda x: x+n, arr[arr_range])
# arr
# [5, 5, 9, 9, 9, 5]

But I would recommend using numpy...

import numpy as np
n = 2
arr_range = slice(2, 5)
arr = np.array([5,5,7,7,7,5])
arr[arr_range] += n


问:
Is there any API to detect AWS stack name, where Lambda is running
I need to know stack name or at least function name in the lambda handler decorator code.
Any idea ? boto3.client('cloudformation') gettesr and describe function needs stack name as parameter. Lambda context is still None at that point.
Thank you !</p>

答:
If you need the stack name you should pass it in as an environment variable to the function. Those values are always available. You can use !Ref AWS::StackName in the environment definition. Something like this:

```<code>  MyFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      FunctionName: My-Function
      # other properties left out for brevity
      Environment:
        Variables:
          StackName: !Ref AWS::StackName
</code>```

Body:
If you need the stack name you should pass it in as an environment variable to the function. Those values are always available. You can use !Ref AWS::StackName in the environment definition. Something like this:

  MyFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      FunctionName: My-Function
      # other properties left out for brevity
      Environment:
        Variables:
          StackName: !Ref AWS::StackName


问:
array with o(1)
I am trying to find the sum of a random subset in a 2D array in o(1) complexity, size up to array[1000][1000] but lets take [4][4] as a basic example:

```<code>array[4][4] = {0, 1, 2 ,3
              4, 5, 6, 7
              8, 9, 10, 11
              12, 13, 14, 15}
</code>```

I have seen some implementations for 1 dimensional arrays where you store the running sum and then just subtract.

That makes sense but lets say I want the sum of array[2][2] to array[3][3] in o(1). So it'd be 10 + 11 + 14 + 15.

But how can this be done in o(1)? o(n) is easy.

Is it something to do with hash tables or a more complicated pre-processed array?

edit>>>

Just some additioanl notes for anyone who comes back to this question:

The specific wording that is useful when googling this seems to be 'summed-area table' or 'integral image' or 'Viola–Jones object detection framework'

Useful references include https://computersciencesource.wordpress.com/2010/09/03/computer-vision-the-integral-image/ and https://en.wikipedia.org/wiki/Viola%E2%80%93Jones_object_detection_framework and https://en.wikipedia.org/wiki/Summed-area_table

答:
For each element [i][j], precompute the sum of all elements in the rectangle spanning from array[0][0] to array[i][j]; denote this value sums[i][j].  Then, to compute the sum of a rectangular subset i1 <= i <= i2 and j1 <= j <= j2, compute:

```<code>sums[i2][j2]
- (i1 == 0 ? 0 : sums[i1 - 1][j2])
- (j1 == 0 ? 0 : sums[i2][j1 - 1])
+ ((i1 == 0 || j1 == 0) ? 0 : sums[i1-1][j1-1])
</code>```

The bounds checks are used to avoid an illegal access outside of array bounds when the region of interest includes i==0 or j==0.

As a rough geometric argument, see the below figure. To get the sum in the black rectangle, get the orange rectangle, subtract the red and green ones, and add back the purple one (since it got double-subtracted).

Title: array with o(1)

Body:
I am trying to find the sum of a random subset in a 2D array in o(1) complexity, size up to array[1000][1000] but lets take [4][4] as a basic example:

array[4][4] = {0, 1, 2 ,3
              4, 5, 6, 7
              8, 9, 10, 11
              12, 13, 14, 15}

I have seen some implementations for 1 dimensional arrays where you store the running sum and then just subtract.

That makes sense but lets say I want the sum of array[2][2] to array[3][3] in o(1). So it'd be 10 + 11 + 14 + 15.

But how can this be done in o(1)? o(n) is easy.

Is it something to do with hash tables or a more complicated pre-processed array?

edit>>>

Just some additioanl notes for anyone who comes back to this question:

The specific wording that is useful when googling this seems to be 'summed-area table' or 'integral image' or 'Viola–Jones object detection framework'

Useful references include https://computersciencesource.wordpress.com/2010/09/03/computer-vision-the-integral-image/ and https://en.wikipedia.org/wiki/Viola%E2%80%93Jones_object_detection_framework and https://en.wikipedia.org/wiki/Summed-area_table

Body:
For each element [i][j], precompute the sum of all elements in the rectangle spanning from array[0][0] to array[i][j]; denote this value sums[i][j].  Then, to compute the sum of a rectangular subset i1 <= i <= i2 and j1 <= j <= j2, compute:

sums[i2][j2]
- (i1 == 0 ? 0 : sums[i1 - 1][j2])
- (j1 == 0 ? 0 : sums[i2][j1 - 1])
+ ((i1 == 0 || j1 == 0) ? 0 : sums[i1-1][j1-1])

The bounds checks are used to avoid an illegal access outside of array bounds when the region of interest includes i==0 or j==0.

As a rough geometric argument, see the below figure. To get the sum in the black rectangle, get the orange rectangle, subtract the red and green ones, and add back the purple one (since it got double-subtracted).


问:
pm2-runtime inside docker container receives SIGTERM - why?
I'm running a virtual machine with docker, which implements our CI/CD infratructure.

docker-compose has an nginx reverse proxy and another service. Essentially, this docker container's start command is a shell script, which creates local copies of files from a central repository. Then this shell script starts (by means of yarn start) a nodejs script that selects a couple of services and creates a pm2 application startup json file.

Finally, pm2-runtime is launched with this application definition file. This is done by

```<code>const child = exec(`pm2-runtime build/pm2startup.json`)

child.stdout.on("data", data => { process.stdout.write(data); })

child.stderr.on("data", data => { process.stderr.write(data); })

child.on("close", (code,signal) => {
  process.stdout.write((`pm2-runtime process closed with code ${code}, signal ${signal}\n`));
})

child.on("error", error => {
  process.stderr.write((`pm2-runtime process error ${error}\n`));
})

child.on("exit", (code, signal) => {
  process.stdout.write((`pm2-runtime process exited with code ${code}, signal ${signal}\n`));
})
</code>```

There are about 10 apps managed by pm2, docker stats say, the container has memory consumption greater than 850MB. However, I have nowhere put any explicit memory limits. I cannot find any implicit either.

Every now and then the container of services is restarted. According to the dockerd logs its task has exited. That's true: the pm2-runtime process (see above) is reported to be closed because of SIGTERM.

And that's the only message I get related to this. No other pm2 message, no service message, no docker event.

Now I'm seeking advice how to find the cause of this SIGTERM because I'm running out of ideas.

答:
As it turned out, it was indeed the snippet inside the question that caused the problem.

pm2startup.json references long-running apps. Over time, depending on usage, they produce quite a few logs on stdout and/or stderr. At some point a certain buffer kept by exec is filled up and the node process that runs pm2-runtime stops. Unfortunately it stops without any kind of hint specifying the reason of the crash. But that's another story.

Solution in my case was to do without exec or execFile, but take spawn instead with the stdio option {stdio: "inherited"} (or the verbose version ["inherited", "inherited", "inherited"]).

Body:
I'm running a virtual machine with docker, which implements our CI/CD infratructure.

docker-compose has an nginx reverse proxy and another service. Essentially, this docker container's start command is a shell script, which creates local copies of files from a central repository. Then this shell script starts (by means of yarn start) a nodejs script that selects a couple of services and creates a pm2 application startup json file.

Finally, pm2-runtime is launched with this application definition file. This is done by

const child = exec(`pm2-runtime build/pm2startup.json`)

child.stdout.on("data", data => { process.stdout.write(data); })

child.stderr.on("data", data => { process.stderr.write(data); })

child.on("close", (code,signal) => {
  process.stdout.write((`pm2-runtime process closed with code ${code}, signal ${signal}\n`));
})

child.on("error", error => {
  process.stderr.write((`pm2-runtime process error ${error}\n`));
})

child.on("exit", (code, signal) => {
  process.stdout.write((`pm2-runtime process exited with code ${code}, signal ${signal}\n`));
})

There are about 10 apps managed by pm2, docker stats say, the container has memory consumption greater than 850MB. However, I have nowhere put any explicit memory limits. I cannot find any implicit either.

Every now and then the container of services is restarted. According to the dockerd logs its task has exited. That's true: the pm2-runtime process (see above) is reported to be closed because of SIGTERM.

And that's the only message I get related to this. No other pm2 message, no service message, no docker event.

Now I'm seeking advice how to find the cause of this SIGTERM because I'm running out of ideas.


问:
Javascript - avoid multiple array.filters being called
I have a piece of code that looks like:

```<code>const desktop = platform.filter(el => el == "desktop").length;
const mobile = platform.filter(el => el == "mobile").length;
const android = platform.filter(el => el == "android").length;
</code>```

and so on..

Basically I have an array that contains multiple entries of those strings and I want to collect the length of each property in a variable. The above works but I was wondering if there is a cleaner way to avoid filter through the array multiple times?

答:
You can use a single reduce to count the number of appearances of the items:

const platform = ['desktop', 'other', 'mobile', '', 'other', 'android', 'android'];

const { desktop, mobile, android } = platform.reduce((r, el) => {
  if (el in r) r[el]++;

  return r;
}, { desktop: 0, mobile: 0, android: 0 });

console.log({ desktop, mobile, android });```

Body:
I have a piece of code that looks like:

const desktop = platform.filter(el => el == "desktop").length;
const mobile = platform.filter(el => el == "mobile").length;
const android = platform.filter(el => el == "android").length;

and so on..

Basically I have an array that contains multiple entries of those strings and I want to collect the length of each property in a variable. The above works but I was wondering if there is a cleaner way to avoid filter through the array multiple times?


问:
retrieve forign key first value in laravel
I have three tables Products, Category and Images. Category and Image tables have relationship with Product table. when I have use $all_product = Product::with('category','image')->get();product information category information and image information are display successfully want i want is Question : how to retrieve the image arrays first value?

```<code>"all_objects": [
    {
        "id": 1,
        "name": "samsung",
        "price": "2000",
        "category_id": 1,
        "created_at": "2020-02-17 13:27:24",
        "updated_at": "2020-02-17 13:27:24",
        "category": {
            "id": 1,
            "category_name": "android",
            "created_at": "2020-02-17 13:26:42",
            "updated_at": "2020-02-17 13:26:42"
        },
        "image": [
            {
                "id": 1,
                "image_name": "image_787.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 2,
                "image_name": "image_539.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 3,
                "image_name": "image_606.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 4,
                "image_name": "image_102.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:26",
                "updated_at": "2020-02-17 13:27:26"
            }
        ]
    },
</code>```

答:
The get() method returns an instance of Illuminate\Database\Eloquent\Collection so you can use all available methods on Laravel collections.

To get your first image:

$all_product = Product::with('category','image')->get();

foreach ($all_product as $product) {
    $first_image = optional($product->image)->first();

    // do whatever you want with the $first_image
}
```

The optional() method is used in a case product had no images (i.e $product->images was null).

Body:
I have three tables Products, Category and Images. Category and Image tables have relationship with Product table. when I have use $all_product = Product::with('category','image')->get();product information category information and image information are display successfully want i want is Question : how to retrieve the image arrays first value?

"all_objects": [
    {
        "id": 1,
        "name": "samsung",
        "price": "2000",
        "category_id": 1,
        "created_at": "2020-02-17 13:27:24",
        "updated_at": "2020-02-17 13:27:24",
        "category": {
            "id": 1,
            "category_name": "android",
            "created_at": "2020-02-17 13:26:42",
            "updated_at": "2020-02-17 13:26:42"
        },
        "image": [
            {
                "id": 1,
                "image_name": "image_787.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 2,
                "image_name": "image_539.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 3,
                "image_name": "image_606.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:25",
                "updated_at": "2020-02-17 13:27:25"
            },
            {
                "id": 4,
                "image_name": "image_102.jpeg",
                "product_id": 1,
                "created_at": "2020-02-17 13:27:26",
                "updated_at": "2020-02-17 13:27:26"
            }
        ]
    },

Body:
The get() method returns an instance of Illuminate\Database\Eloquent\Collection so you can use all available methods on Laravel collections.

To get your first image:

$all_product = Product::with('category','image')->get();

foreach ($all_product as $product) {
    $first_image = optional($product->image)->first();

    // do whatever you want with the $first_image
}

The optional() method is used in a case product had no images (i.e $product->images was null).


问:
Flutter Future & Sqflite
I use Sqflite to save data (for example a name of a person).
With this function I get the data of the DB:

```<code>Future<List<Student>> getStudentList() async {
await openDb();
final List<Map<String, dynamic>> maps = await _database.query('student', orderBy: 'name ASC');
return List.generate(maps.length, (i) {
  return Student(
      id: maps[i]['id'], name: maps[i]['name']);
});
}
</code>```

At the start I want to add the names in the DB into a List.

```<code>  @override
void initState() {
foo();
//userList.add(User('Test1', 'Test, false));
//userList.add(User('test2', 'test', false));
userList
    .sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
filterList();
searchController.addListener(() {
  filterList();
});
super.initState();
}
</code>```

This is how I defined foo() where I want to get the data out of the DB:

```<code>Future foo() async{
studlist = await dbmanager.getStudentList();
 var tl = studlist.length;
  for (var i = 0; i < tl; i++) {
  userList.add(User(studlist[i].name, 'Test', false));
  // print('${studlist[i].name}');
 // print('$i');
}
}
</code>```

The problem is, that this function doesn't save anything in the List.
If I use in void initState() this test code instead of foo(), it works:

```<code>userList.add(User('Test1', 'Test, false));
userList.add(User('test2', 'test', false));
</code>```

So something must be wrong with foo().
I also added  print('${studlist[i].name}'); print('$i'); in the for loop to test, if studlist[i] works, and it printed out every name.

Thanks for your help!

答:
The problem is your foo method is async and you're not awaiting it. So, the initState calling code is returned to as soon as that await is hit and before your userList adds. The adds will happen eventually, but you're initState logic is running before that happens. For this to work, you need to wait until foo has completed. You can't just go and make initState async and await foo, but you can do your work after the Future is complete by using then then method.

```<code>void initState() {
  foo().then((result) {
      userList
        .sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
    filterList();
    searchController.addListener(() {
      filterList();
    });
    setState(() => {});
  });

  super.initState();
}
</code>```

Now your build will need to handle the loading case in which you don't yet have users, but this code should populate your userList and rebuild your view with the users. If this gets more complex, you may want to consider using StreamBuilder which is more setup for dealing with this async behavior.

Title: Flutter Future & Sqflite

Body:
I use Sqflite to save data (for example a name of a person).
With this function I get the data of the DB:

Future<List<Student>> getStudentList() async {
await openDb();
final List<Map<String, dynamic>> maps = await _database.query('student', orderBy: 'name ASC');
return List.generate(maps.length, (i) {
  return Student(
      id: maps[i]['id'], name: maps[i]['name']);
});
}

At the start I want to add the names in the DB into a List.

  @override
void initState() {
foo();
//userList.add(User('Test1', 'Test, false));
//userList.add(User('test2', 'test', false));
userList
    .sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
filterList();
searchController.addListener(() {
  filterList();
});
super.initState();
}

This is how I defined foo() where I want to get the data out of the DB:

Future foo() async{
studlist = await dbmanager.getStudentList();
 var tl = studlist.length;
  for (var i = 0; i < tl; i++) {
  userList.add(User(studlist[i].name, 'Test', false));
  // print('${studlist[i].name}');
 // print('$i');
}
}

The problem is, that this function doesn't save anything in the List.
If I use in void initState() this test code instead of foo(), it works:

userList.add(User('Test1', 'Test, false));
userList.add(User('test2', 'test', false));

So something must be wrong with foo().
I also added  print('${studlist[i].name}'); print('$i'); in the for loop to test, if studlist[i] works, and it printed out every name.

Thanks for your help!

Body:
The problem is your foo method is async and you're not awaiting it. So, the initState calling code is returned to as soon as that await is hit and before your userList adds. The adds will happen eventually, but you're initState logic is running before that happens. For this to work, you need to wait until foo has completed. You can't just go and make initState async and await foo, but you can do your work after the Future is complete by using then then method.

void initState() {
  foo().then((result) {
      userList
        .sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
    filterList();
    searchController.addListener(() {
      filterList();
    });
    setState(() => {});
  });

  super.initState();
}

Now your build will need to handle the loading case in which you don't yet have users, but this code should populate your userList and rebuild your view with the users. If this gets more complex, you may want to consider using StreamBuilder which is more setup for dealing with this async behavior.


问:
node-sass throws errors when installing on Windows
I'm working on a front-end project with a friend who is on a Mac and has been able to install and run node-sass on his side. I'm running Windows 10, so when I've pulled the project and tried to run npm install I now get a bunch of errors coming from CI.exe like the following:

```<code>C:\Program Files (x86)\Windows Kits\10\Include\10.0.10240.0\ucrt\corecrt.h(10): fatal error C1083: Cannot open include
file: 'vcruntime.h': No such file or directory (compiling source file ..\..\src\libsass\src\check_nesting.cpp) [C:\Deve
lopment\xxx\xxx\node_modules\gulp-sass\node_modules\node-sass\build\src\libsass.vcxproj]
</code>```

I've downloaded the C++ binaries, installed the node windows-build-tools, I've ensured that CI.exe is in PATH. I'm at my wits end!

I'm running node v8.2.1, npm v5.3.0, VS 2017 (v15.2, 26430.16 release)(C++ build tools installed, etc)

Full npm debug log for running command npm install node-sass from project directory

答:
NodeJS v10 fix this but new versions also have the same issue.

Also try :

```<code>npm install -g --unsafe-perm node-sass --save
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a front-end project with a friend who is on a Mac and has been able to install and run node-sass on his side. I'm running Windows 10, so when I've pulled the project and tried to run npm install I now get a bunch of errors coming from CI.exe like the following:

C:\Program Files (x86)\Windows Kits\10\Include\10.0.10240.0\ucrt\corecrt.h(10): fatal error C1083: Cannot open include
file: 'vcruntime.h': No such file or directory (compiling source file ..\..\src\libsass\src\check_nesting.cpp) [C:\Deve
lopment\xxx\xxx\node_modules\gulp-sass\node_modules\node-sass\build\src\libsass.vcxproj]

I've downloaded the C++ binaries, installed the node windows-build-tools, I've ensured that CI.exe is in PATH. I'm at my wits end!

I'm running node v8.2.1, npm v5.3.0, VS 2017 (v15.2, 26430.16 release)(C++ build tools installed, etc)

Full npm debug log for running command npm install node-sass from project directory

Body:
NodeJS v10 fix this but new versions also have the same issue.

Also try :

npm install -g --unsafe-perm node-sass --save


问:
How to update output with continuous user inputs until terminated with "."?
New to Java and trying to figure out how to keep a running evaluated expression given by a user continuously until they type in "." to terminate it and then print the output. I need to use methods outside of the main that I have already placed.I don't have to worry about order of operation but I'm confused on how to take on a continuous amount of operations/numbers while keeping track of their outputs and then how to finally print the result when they put ".".

```<code>import java.util.Scanner;

public class Evaluator {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int num1;
        char expression;
        int num2;
        String numlist = "";

        System.out.println("Enter the expression: ");
        num1 = scan.nextInt();
        expression = scan.next().charAt(0);
        num2 = scan.nextInt();
        scan.close();

        if (expression == '+') {
            add(num1, num2);
        } else if (expression == '-') {
            subtract(num1, num2);
        } else if (expression == '*') {
            multiply(num1, num2);
        } else if (expression == '/') {
            divide(num1, num2);
        } else if (expression == '%') {
            modulus(num1, num2);
        } else if (expression == '.'){

        }
    }

    static int add(int num1, int num2) {
        return (num1 + num2);
    }

    static int subtract(int num1, int num2) {
        return (num1 - num2);
    }

    static int divide(int num1, int num2) {
        return (num1/num2);
    }

    static int multiply(int num1, int num2) {
        return (num1*num2);
    }

    static int modulus(int num1, int num2) {
        return (num1%num2);
    }
}
</code>```

OUTPUT:

Enter the expression:

```<code>1
+
26
*
2
%
19
/
5
.
</code>```

The result is 3

答:
I would recommend to start with "0 +" followed by whatever the user entered. Because then you do not need special handling for the first number.

```<code>import java.util.Scanner;

class Main
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the expression: ");

        // Start with "0 +"
        int value = 0;
        String operator = "+";

        while (true) // loop
        {
            int operand = scan.nextInt();

            switch (operator)
            {
                case "+": value += operand; break;
                case "-": value -= operand; break;
                case "*": value *= operand; break;
                case "/": value /= operand; break;
                case "%": value %= operand; break;
                default: throw new UnsupportedOperationException(operator);
            }

            operator = scan.next();

            if (".".equals(operator))
            {
                break; // exit the loop
            }
        }

        System.out.println("result=" + value);
        scan.close();
    }

}
</code>```

However, this algorithm does not care mathematical rules of operator order. it simply processes the input from left to right like a cheap 3€ pocket calculator.

Other example based on your if-else construct and methods:

```<code>import java.util.Scanner;

class Main
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the expression: ");

        // Start with "0 +"
        int value = 0;
        char operator = '+';

        while (true) // loop
        {
            int operand = scan.nextInt();

            if (operator == '+') {
                value=add(value, operand);
            } else if (operator == '-') {
                value=subtract(value, operand);
            } else if (operator == '*') {
                value=multiply(value, operand);
            } else if (operator == '/') {
                value=divide(value, operand);
            } else if (operator == '%') {
                value=modulus(value, operand);
            } else {
                throw new UnsupportedOperationException(String.valueOf(operator));
            }

            operator = scan.next().charAt(0);

            if (operator=='.')
            {
                break; // exit the loop
            }
        }

        System.out.println("result=" + value);
        scan.close();
    }

    static int add(int num1, int num2) {
        return (num1 + num2);
    }

    static int subtract(int num1, int num2) {
        return (num1 - num2);
    }

    static int divide(int num1, int num2) {
        return (num1/num2);
    }

    static int multiply(int num1, int num2) {
        return (num1*num2);
    }

    static int modulus(int num1, int num2) {
        return (num1%num2);
    }
}
</code>```

Body:
New to Java and trying to figure out how to keep a running evaluated expression given by a user continuously until they type in "." to terminate it and then print the output. I need to use methods outside of the main that I have already placed.I don't have to worry about order of operation but I'm confused on how to take on a continuous amount of operations/numbers while keeping track of their outputs and then how to finally print the result when they put ".".

import java.util.Scanner;

public class Evaluator {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int num1;
        char expression;
        int num2;
        String numlist = "";

        System.out.println("Enter the expression: ");
        num1 = scan.nextInt();
        expression = scan.next().charAt(0);
        num2 = scan.nextInt();
        scan.close();

        if (expression == '+') {
            add(num1, num2);
        } else if (expression == '-') {
            subtract(num1, num2);
        } else if (expression == '*') {
            multiply(num1, num2);
        } else if (expression == '/') {
            divide(num1, num2);
        } else if (expression == '%') {
            modulus(num1, num2);
        } else if (expression == '.'){

        }
    }

    static int add(int num1, int num2) {
        return (num1 + num2);
    }

    static int subtract(int num1, int num2) {
        return (num1 - num2);
    }

    static int divide(int num1, int num2) {
        return (num1/num2);
    }

    static int multiply(int num1, int num2) {
        return (num1*num2);
    }

    static int modulus(int num1, int num2) {
        return (num1%num2);
    }
}

OUTPUT:

Enter the expression:

1
+
26
*
2
%
19
/
5
.

The result is 3

Body:
I would recommend to start with "0 +" followed by whatever the user entered. Because then you do not need special handling for the first number.

import java.util.Scanner;

class Main
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the expression: ");

        // Start with "0 +"
        int value = 0;
        String operator = "+";

        while (true) // loop
        {
            int operand = scan.nextInt();

            switch (operator)
            {
                case "+": value += operand; break;
                case "-": value -= operand; break;
                case "*": value *= operand; break;
                case "/": value /= operand; break;
                case "%": value %= operand; break;
                default: throw new UnsupportedOperationException(operator);
            }

            operator = scan.next();

            if (".".equals(operator))
            {
                break; // exit the loop
            }
        }

        System.out.println("result=" + value);
        scan.close();
    }

}

However, this algorithm does not care mathematical rules of operator order. it simply processes the input from left to right like a cheap 3€ pocket calculator.

Other example based on your if-else construct and methods:

import java.util.Scanner;

class Main
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the expression: ");

        // Start with "0 +"
        int value = 0;
        char operator = '+';

        while (true) // loop
        {
            int operand = scan.nextInt();

            if (operator == '+') {
                value=add(value, operand);
            } else if (operator == '-') {
                value=subtract(value, operand);
            } else if (operator == '*') {
                value=multiply(value, operand);
            } else if (operator == '/') {
                value=divide(value, operand);
            } else if (operator == '%') {
                value=modulus(value, operand);
            } else {
                throw new UnsupportedOperationException(String.valueOf(operator));
            }

            operator = scan.next().charAt(0);

            if (operator=='.')
            {
                break; // exit the loop
            }
        }

        System.out.println("result=" + value);
        scan.close();
    }

    static int add(int num1, int num2) {
        return (num1 + num2);
    }

    static int subtract(int num1, int num2) {
        return (num1 - num2);
    }

    static int divide(int num1, int num2) {
        return (num1/num2);
    }

    static int multiply(int num1, int num2) {
        return (num1*num2);
    }

    static int modulus(int num1, int num2) {
        return (num1%num2);
    }
}


问:
404 Error on Google OAuth API Token Request
I am trying to get a token from the Google OAuth api. I have already successfully been able to get the temporary auth code.

However, my requests are returning a 404 error, with the normal Google "That's an error" 404 page. Here is my Python code:

```<code>data = {
    "code":auth_code,
    "client_id":client_id,
    "client_secret":client_secret,
    "redirect_uri":redirect_uri,
    "grant_type":"authorization_code"
    }
headers = {"Content-Type":"application/x-www-form-urlencoded"}
r = requests.post("https://googleapis.com/oauth/v4/token",data=data,headers=headers)
</code>```

I get the same error no matter if I url-encode my parameters or not (I think the requests library does it anyway).

Here are the data I am sending in more detail (censored of course)

```<code>'client_id':'2-------------------------------------------0.apps.googleusercontent.com',
'client_secret': '5----------------------p',
'code': '4/A-------------------------- ... ------------------------------------fGE#',
'grant_type': 'authorization_code',
'redirect_uri': 'https://localhost'
</code>```

I understand the question here is very similar to mine but all the solutions provided either don't work (url encoding) or don't apply (everything else).

I am using this official documentation for reference.

This is probably very obvious, like most of the questions I ask here.

Edit - I tried

```<code>data = "code="+auth_code+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"&grant_type=authorization_code"
</code>```

...which returned a 400. With or without url-encoding.

答: For me the issue was that I was sending a GET. You have to send a POST.</p>

Body:
I am trying to get a token from the Google OAuth api. I have already successfully been able to get the temporary auth code.

However, my requests are returning a 404 error, with the normal Google "That's an error" 404 page. Here is my Python code:

data = {
    "code":auth_code,
    "client_id":client_id,
    "client_secret":client_secret,
    "redirect_uri":redirect_uri,
    "grant_type":"authorization_code"
    }
headers = {"Content-Type":"application/x-www-form-urlencoded"}
r = requests.post("https://googleapis.com/oauth/v4/token",data=data,headers=headers)

I get the same error no matter if I url-encode my parameters or not (I think the requests library does it anyway).

Here are the data I am sending in more detail (censored of course)

'client_id':'2-------------------------------------------0.apps.googleusercontent.com',
'client_secret': '5----------------------p',
'code': '4/A-------------------------- ... ------------------------------------fGE#',
'grant_type': 'authorization_code',
'redirect_uri': 'https://localhost'

I understand the question here is very similar to mine but all the solutions provided either don't work (url encoding) or don't apply (everything else).

I am using this official documentation for reference.

This is probably very obvious, like most of the questions I ask here.

Edit - I tried

data = "code="+auth_code+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"&grant_type=authorization_code"

...which returned a 400. With or without url-encoding.


问:
Cannot set font-family to AvantGard in React.js
I want to add AvantGard font to one paragraph in my React app, but it seems the font has no effect and I don't know why, here is how I am adding it:

I keep it as a ttf file in my assets folder.

I have global scss file index.css and I declare it there like this:

```<code>@font-face {
  font-family: 'AvantGard';
  font-style: normal;
  src: url('./assets/fonts/avant_gartt/AvantGard.ttf');
}
</code>```

I also have a variables.scss in which I keep it like this:

```<code>$avantGard: 'AvantGuard';
</code>```

I import my variables in my component's css like this:

```<code>@import './variables.scss';
</code>```

and then I just set the font-size of my paragraph:

```<code> font-family: $avantGard;
</code>```

Does anyone have any idea why my font does not work? The rest of my fonts work the same way, but not this one.

答:
Check your spelling on number 3.
AvantGard or AvantGuard?</p>

Body:
I want to add AvantGard font to one paragraph in my React app, but it seems the font has no effect and I don't know why, here is how I am adding it:

I keep it as a ttf file in my assets folder.

I have global scss file index.css and I declare it there like this:

@font-face {
  font-family: 'AvantGard';
  font-style: normal;
  src: url('./assets/fonts/avant_gartt/AvantGard.ttf');
}

I also have a variables.scss in which I keep it like this:

$avantGard: 'AvantGuard';

I import my variables in my component's css like this:

@import './variables.scss';

and then I just set the font-size of my paragraph:

 font-family: $avantGard;

Does anyone have any idea why my font does not work? The rest of my fonts work the same way, but not this one.


问:
Elastic Search Bool Query for multiple fields
I have index mapping like follows:

Request

```<code>|-> tilte
|-> countryCode
|-> isOpen
|-> location
|-> date
</code>```

I want to make bool and geoquery at the same time fetching the docs that within the same country and near me also which isOpen I have tried the below but always I am getting an empty hits object.

```<code>{   "from" : 5,
    "size": 5,
    "query": {
        "bool" : {
            "must" : [
                {"match" : {"countryCode": "US"}},
                {"match": {"isOpen": true }}
            ],
            "filter" : {
                "geo_distance" : {
                    "distance" : "150km",
                    "location" : {
                        "lat" : 1111111111,
                        "lon" : 3333333333
                        }
                }
            }
        }
    },

    "sort": [ { "date" : {"order" : "desc"} } ]
 }
</code>```

The response

```<code>{
    "took": 8,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}
</code>```

even though I am sure that there are many documents matches the query but I can't get it. Any one can help?

答: I would start with changing from value from 5 to 0. Nextly I would check index definition - are you sure each of the field can be searched in a way you're using it? Can you show exact index definiton (mapping) and show sample item from Elastic?

Body:
I have index mapping like follows:

Request

|-> tilte
|-> countryCode
|-> isOpen
|-> location
|-> date

I want to make bool and geoquery at the same time fetching the docs that within the same country and near me also which isOpen I have tried the below but always I am getting an empty hits object.

{   "from" : 5,
    "size": 5,
    "query": {
        "bool" : {
            "must" : [
                {"match" : {"countryCode": "US"}},
                {"match": {"isOpen": true }}
            ],
            "filter" : {
                "geo_distance" : {
                    "distance" : "150km",
                    "location" : {
                        "lat" : 1111111111,
                        "lon" : 3333333333
                        }
                }
            }
        }
    },

    "sort": [ { "date" : {"order" : "desc"} } ]
 }

The response

{
    "took": 8,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}

even though I am sure that there are many documents matches the query but I can't get it. Any one can help?


问:
convert to list every value is dictionary in python
i have output of print response is </p>

```<code>Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  480M     0  480M   0% /dev
tmpfs          tmpfs      99M  756K   98M   1% /run
/dev/xvda1     ext4      7.7G  2.9G  4.9G  38% /
tmpfs          tmpfs     492M     0  492M   0% /dev/shm
tmpfs          tmpfs     5.0M     0  5.0M   0% /run/lock
tmpfs          tmpfs     492M     0  492M   0% /sys/fs/cgroup
/dev/loop0     squashfs   18M   18M     0 100% /snap/amazon-ssm-agent/1480
/dev/loop2     squashfs   90M   90M     0 100% /snap/core/8268
/dev/loop3     squashfs   92M   92M     0 100% /snap/core/8592
</code>```

<p>how to convert it to list or dictionary to easy get value of every filesystem, type and mounted
then make loop to get every value and put them in variables and use them in the code.   </p>

答:
You can generate the dictionary iterating over every line like that:

data = '''Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  480M     0  480M   0% /dev
tmpfs          tmpfs      99M  756K   98M   1% /run
/dev/xvda1     ext4      7.7G  2.9G  4.9G  38% /
tmpfs          tmpfs     492M     0  492M   0% /dev/shm
tmpfs          tmpfs     5.0M     0  5.0M   0% /run/lock
tmpfs          tmpfs     492M     0  492M   0% /sys/fs/cgroup
/dev/loop0     squashfs   18M   18M     0 100% /snap/amazon-ssm-agent/1480
/dev/loop2     squashfs   90M   90M     0 100% /snap/core/8268
/dev/loop3     squashfs   92M   92M     0 100% /snap/core/8592'''

header = ['filesystem', 'type', 'size', 'used', 'avail', 'use%', 'mounted on']
d = {}
for line in data.split('\n')[1:]:
    for i, j in enumerate(line.split()):
        if i == 0:
            fs= j
            d[fs] = {}
        else:
            d[fs][header[i]] = j

print(d)
```

<p>Output:</p>

<pre class="lang-py prettyprint-override"><code>{

    'udev':{
        'type':'devtmpfs',
        'size':'480M',
        'used':'0',
        'avail':'480M',
        'use%':'0%',
        'mounted on':'/dev'
    },
    'tmpfs':{
        'type':'tmpfs',
        'size':'492M',
        'used':'0',
        'avail':'492M',
        'use%':'0%',
        'mounted on':'/sys/fs/cgroup'
    },
    '/dev/xvda1':{
        'type':'ext4',
        'size':'7.7G',
        'used':'2.9G',
        'avail':'4.9G',
        'use%':'38%',
        'mounted on':'/'
    },
    '/dev/loop0':{
        'type':'squashfs',
        'size':'18M',
        'used':'18M',
        'avail':'0',
        'use%':'100%',
        'mounted on':'/snap/amazon-ssm-agent/1480'
    },
    '/dev/loop2':{
        'type':'squashfs',
        'size':'90M',
        'used':'90M',
        'avail':'0',
        'use%':'100%',
        'mounted on':'/snap/core/8268'
    },
    '/dev/loop3':{
        'type':'squashfs',
        'size':'92M',
        'used':'92M',
        'avail':'0',
        'use%':'100%',
        'mounted on':'/snap/core/8592'
    }

}
</code>```

Body:
i have output of print response is

Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  480M     0  480M   0% /dev
tmpfs          tmpfs      99M  756K   98M   1% /run
/dev/xvda1     ext4      7.7G  2.9G  4.9G  38% /
tmpfs          tmpfs     492M     0  492M   0% /dev/shm
tmpfs          tmpfs     5.0M     0  5.0M   0% /run/lock
tmpfs          tmpfs     492M     0  492M   0% /sys/fs/cgroup
/dev/loop0     squashfs   18M   18M     0 100% /snap/amazon-ssm-agent/1480
/dev/loop2     squashfs   90M   90M     0 100% /snap/core/8268
/dev/loop3     squashfs   92M   92M     0 100% /snap/core/8592

how to convert it to list or dictionary to easy get value of every filesystem, type and mounted
then make loop to get every value and put them in variables and use them in the code.

Body:
You can generate the dictionary iterating over every line like that:

data = '''Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  480M     0  480M   0% /dev
tmpfs          tmpfs      99M  756K   98M   1% /run
/dev/xvda1     ext4      7.7G  2.9G  4.9G  38% /
tmpfs          tmpfs     492M     0  492M   0% /dev/shm
tmpfs          tmpfs     5.0M     0  5.0M   0% /run/lock
tmpfs          tmpfs     492M     0  492M   0% /sys/fs/cgroup
/dev/loop0     squashfs   18M   18M     0 100% /snap/amazon-ssm-agent/1480
/dev/loop2     squashfs   90M   90M     0 100% /snap/core/8268
/dev/loop3     squashfs   92M   92M     0 100% /snap/core/8592'''

header = ['filesystem', 'type', 'size', 'used', 'avail', 'use%', 'mounted on']
d = {}
for line in data.split('\n')[1:]:
    for i, j in enumerate(line.split()):
        if i == 0:
            fs= j
            d[fs] = {}
        else:
            d[fs][header[i]] = j

print(d)

Output:

{

    'udev':{
        'type':'devtmpfs',
        'size':'480M',
        'used':'0',
        'avail':'480M',
        'use%':'0%',
        'mounted on':'/dev'
    },
    'tmpfs':{
        'type':'tmpfs',
        'size':'492M',
        'used':'0',
        'avail':'492M',
        'use%':'0%',
        'mounted on':'/sys/fs/cgroup'
    },
    '/dev/xvda1':{
        'type':'ext4',
        'size':'7.7G',
        'used':'2.9G',
        'avail':'4.9G',
        'use%':'38%',
        'mounted on':'/'
    },
    '/dev/loop0':{
        'type':'squashfs',
        'size':'18M',
        'used':'18M',
        'avail':'0',
        'use%':'100%',
        'mounted on':'/snap/amazon-ssm-agent/1480'
    },
    '/dev/loop2':{
        'type':'squashfs',
        'size':'90M',
        'used':'90M',
        'avail':'0',
        'use%':'100%',
        'mounted on':'/snap/core/8268'
    },
    '/dev/loop3':{
        'type':'squashfs',
        'size':'92M',
        'used':'92M',
        'avail':'0',
        'use%':'100%',
        'mounted on':'/snap/core/8592'
    }

}


问:
how to disable one button when clicked in mat table Angular material
I have a problem, I have a mat table and inside this table I have a column to display buttons. The problem is that when I click on one button, all of them disable when I only want to disable the one I click...

my .html:

```<code><table *ngIf="buildingImageList.length > 0" mat-table [dataSource]="buildingImageList" class="mat-elevation-z8">
<ng-container matColumnDef="buildId">
<th mat-header-cell *matHeaderCellDef> Cancel </th>
<td mat-cell *matCellDef="let element">
<button mat-flat-button color="accent" [disabled]="clicked"
(click)="cancelBuildingImage(element.buildId); clicked = true;">
Cancel build
</button>
</td>
</ng-container>
</table>

</code>```

my .ts:

```<code>
import { Component, OnInit, OnDestroy } from "@angular/core";
import { BuildingImage } from "../buildingImage.model";
import { BuilderService } from "../../builder.service";
import { SnackMessageService } from "app/main/common/services/snackMessage.service";

@Component({
  selector: "building-images",
  templateUrl: "./building-images.component.html",
  styleUrls: ["./building-images.component.scss"]
})
export class BuildingImagesComponent implements OnInit, OnDestroy {
  buildingImageList: BuildingImage[];
  displayedColumns: string[] = ["tag", "created", "startedBuilding", "finishDate", "buildId"];
  buildingImageErrorMessage: string;
  callLoop: any;
  clicked: boolean;

  constructor(private builderService: BuilderService, private snackMessageService: SnackMessageService) {
    this.buildingImageList = new Array();

    this.clicked = false;

</code>```

答:
How about to translate clicked to an array.

my .ts:

```<code>clicked  = new Array();

ngOnInit() {
  this.buildingImageList.foreach(el => {
    this.clicked.push(false);
  });
}
</code>```

Then you just need to be aware of which line number you are clicking. For that, you can append let i=index to your for loop (which is matCellDef in matTable).

my.html

```<code><table *ngIf="buildingImageList.length > 0" mat-table [dataSource]="buildingImageList" class="mat-elevation-z8">
<ng-container matColumnDef="buildId">
<th mat-header-cell *matHeaderCellDef> Cancel </th>
<td mat-cell *matCellDef="let element; let i=index">
<button mat-flat-button color="accent" [disabled]="clicked[i]"
(click)="cancelBuildingImage(element.buildId); clicked[i] = true;">
Cancel build
</button>
</td>
</ng-container>
</table>
</code>```

Body:
I have a problem, I have a mat table and inside this table I have a column to display buttons. The problem is that when I click on one button, all of them disable when I only want to disable the one I click...

my .html:

 0" mat-table [dataSource]="buildingImageList" class="mat-elevation-z8">
<ng-container matColumnDef="buildId">
 Cancel

<button mat-flat-button color="accent" [disabled]="clicked"
(click)="cancelBuildingImage(element.buildId); clicked = true;">
Cancel build
</button>

</ng-container>

my .ts:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { BuildingImage } from "../buildingImage.model";
import { BuilderService } from "../../builder.service";
import { SnackMessageService } from "app/main/common/services/snackMessage.service";

@Component({
  selector: "building-images",
  templateUrl: "./building-images.component.html",
  styleUrls: ["./building-images.component.scss"]
})
export class BuildingImagesComponent implements OnInit, OnDestroy {
  buildingImageList: BuildingImage[];
  displayedColumns: string[] = ["tag", "created", "startedBuilding", "finishDate", "buildId"];
  buildingImageErrorMessage: string;
  callLoop: any;
  clicked: boolean;

  constructor(private builderService: BuilderService, private snackMessageService: SnackMessageService) {
    this.buildingImageList = new Array();

    this.clicked = false;

Body:
How about to translate clicked to an array.

my .ts:

clicked  = new Array();

ngOnInit() {
  this.buildingImageList.foreach(el => {
    this.clicked.push(false);
  });
}

Then you just need to be aware of which line number you are clicking. For that, you can append let i=index to your for loop (which is matCellDef in matTable).

my.html

<table *ngIf="buildingImageList.length > 0" mat-table [dataSource]="buildingImageList" class="mat-elevation-z8">
<ng-container matColumnDef="buildId">
<th mat-header-cell *matHeaderCellDef> Cancel </th>
<td mat-cell *matCellDef="let element; let i=index">
<button mat-flat-button color="accent" [disabled]="clicked[i]"
(click)="cancelBuildingImage(element.buildId); clicked[i] = true;">
Cancel build
</button>
</td>
</ng-container>
</table>


问:
How to convert String of date format "dd-MMM-yy" into DateType
Example "31-Jan-19" should be 2019-01-31

My code:

```<code>df.withColumn("formattedDate", to_date($"date", "dd-MMM-yyyy").cast(DateType))
//this line gives same result
df.withColumn("unixDate", to_date(unix_timestamp($"date", "dd-MMM-yyyy")
   .cast("timestamp")))
</code>```

Result of this code: 0019-01-31

Body:
Example "31-Jan-19" should be 2019-01-31

My code:

df.withColumn("formattedDate", to_date($"date", "dd-MMM-yyyy").cast(DateType))
//this line gives same result
df.withColumn("unixDate", to_date(unix_timestamp($"date", "dd-MMM-yyyy")
   .cast("timestamp")))

Result of this code: 0019-01-31

Body:
In date format specify yy instead of yyyy.

df.withColumn("formattedDate", to_date($"date", "dd-MMM-yy").cast(DateType)).show()

//+---------+-------------+
//|     date|formattedDate|
//+---------+-------------+
//|31-Jan-19|   2019-01-31|
//+---------+-------------+

df.withColumn("unixDate", to_date(unix_timestamp($"date", "dd-MMM-yy").cast("timestamp"))).show()

//+---------+----------+
//|     date|  unixDate|
//+---------+----------+
//|31-Jan-19|2019-01-31|
//+---------+----------+


问:
Insufficient Permission: Request had insufficient authentication scopes in google directory API when logging through admin
I'm using google admin directory API to get all accounts public information using following API
https://www.googleapis.com/admin/directory/v1/users

here is link for this api link
when I logged in using g suite domain account let say abc@somedomain.com with non administrative user this api works fine and fetch the data of all accounts in array
 but When I call this API by logging in as admin it gives me following error /

Insufficient Permission: Request had insufficient authentication
  scopes

why its happening Im using same auth and API key for both users

my code is here

```<code>const token =localStorage.getItem('token')
 fetch(`https://www.googleapis.com/admin/directory/v1/users?
 domain=${domain.url}&viewType=domain_public&key=${apiKey.key}`
  ,{ headers: {
'authorization': 'Bearer '+token
  },})

  .then(response => response.json())
  .then(data => this.setState({ users:data.users }));
</code>```

token is coming from this module npm react google login google sign in button

答:
It seems that the issue you are encountering is related to the way you are using the access token, more precisely in the way you use the scopes for the admin account in relation to the access token you have.

If the scopes you want to use with the two accounts don't match entirely, you will need to get another access token when you use the admin account.

So in order to solve your issue, you will have to get a new access token for the scopes you will be using for the admin account. You can declare them like this:

```<code>const SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly' 'OTHER_SCOPE_1' 'OTHER_SCOPE_2'...];
</code>```

Same goes for the non-admin account; if the scopes don't match entirely, declare them like above and get another access token which will be the one matching them.

Reference

Authorizing Requests with OAuth 2.0

Body:
I'm using google admin directory API to get all accounts public information using following API
https://www.googleapis.com/admin/directory/v1/users

here is link for this api link
when I logged in using g suite domain account let say abc@somedomain.com with non administrative user this api works fine and fetch the data of all accounts in array
 but When I call this API by logging in as admin it gives me following error /

Insufficient Permission: Request had insufficient authentication
  scopes

why its happening Im using same auth and API key for both users

my code is here

const token =localStorage.getItem('token')
 fetch(`https://www.googleapis.com/admin/directory/v1/users?
 domain=${domain.url}&viewType=domain_public&key=${apiKey.key}`
  ,{ headers: {
'authorization': 'Bearer '+token
  },})

  .then(response => response.json())
  .then(data => this.setState({ users:data.users }));

token is coming from this module npm react google login google sign in button

Body:
It seems that the issue you are encountering is related to the way you are using the access token, more precisely in the way you use the scopes for the admin account in relation to the access token you have.

If the scopes you want to use with the two accounts don't match entirely, you will need to get another access token when you use the admin account.

So in order to solve your issue, you will have to get a new access token for the scopes you will be using for the admin account. You can declare them like this:

const SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly' 'OTHER_SCOPE_1' 'OTHER_SCOPE_2'...];

Same goes for the non-admin account; if the scopes don't match entirely, declare them like above and get another access token which will be the one matching them.

Reference

Authorizing Requests with OAuth 2.0


问:
Codewars Challenge - JavaScript - Find the first non-consecutive number in Array
Link to Codewars challenge

This is very basic, but for some reason, I can't figure out why I'm not able to return null when there are not any non-consecutive numbers in an array. My code works fine when the array is not totally consecutive:

function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));```
</div>
</div>
</p>

<p>But if the array <em>is</em> consecutive, i.e. like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 6, 7, 8, 9, 10, 11, 12 ]));</code>```

You can see that it returns undefined instead of null. Why isn't it returning null? The return is outside of the for-loop.

I tried to create an initial check to see if the array is not consecutive, like this:

function firstNonConsecutive(arr) {
  let newArr = [];
  for (let j = arr[0]; j < arr[arr.length - 1]; j++) {
    newArr.push(j);
  }
  //check if arr does not contain consecutive characters
  if (String(arr) !== String(newArr)) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i + 1] - arr[i] !== 1) {
        return arr[i + 1];
      }
    }
  }
  else {
    return null;
  }
}
console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));```

But it did not make a difference. Any ideas?

答:
I suggest to start from the second item and check the element and the element before.

This approach does not change the length to check for and it omits the problem to check non existent elements.

function firstNonConsecutive(arr) {
    for (let i = 1; i < arr.length; i++) {
        if (arr[i - 1] + 1 !== arr[i]) return arr[i];
    }
    return null;
}

console.log(firstNonConsecutive([0, 1, 2, 3, 4, 6, 7, 8, 9]));
console.log(firstNonConsecutive([0, 1, 2, 3, 4, 5, 6, 7, 8]));```

Body:
Link to Codewars challenge

This is very basic, but for some reason, I can't figure out why I'm not able to return null when there are not any non-consecutive numbers in an array. My code works fine when the array is not totally consecutive:

function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));

But if the array is consecutive, i.e. like this:

function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 6, 7, 8, 9, 10, 11, 12 ]));

You can see that it returns undefined instead of null. Why isn't it returning null? The return is outside of the for-loop.

I tried to create an initial check to see if the array is not consecutive, like this:

function firstNonConsecutive(arr) {
  let newArr = [];
  for (let j = arr[0]; j < arr[arr.length - 1]; j++) {
    newArr.push(j);
  }
  //check if arr does not contain consecutive characters
  if (String(arr) !== String(newArr)) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i + 1] - arr[i] !== 1) {
        return arr[i + 1];
      }
    }
  }
  else {
    return null;
  }
}
console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));

But it did not make a difference. Any ideas?


问:
error log truncated in laravel 5.3
i have this entry in my laravel 5.3 log

2016-12-22 17:23:37] local.ERROR:
  GuzzleHttp\Exception\ClientException: Client error: POST
  https://api.sparkpost.com/api/v1/transmissions resulted in a 400 Bad
  Request response: { "errors": [ { "message": "Message generation
  rejected", "description": "recipient address suppressed due to
  customer p (truncated...)

why does it truncate an important error message? now i cannot figure out what is going wrong...

答:
None of these solutions here helped me. I found a solution here that helped. By the user sidk2020. Here is his solution in case the link breaks:

I did something very adventurous. I modified guzzel's exception handler

guzzel on purpose only reads up 120 bytes of info and prints truncated next to it.

The file is located at : /vendor/guzzlehttp/guzzle/src/Exception/RequestException.php

So I modified that function and below is what my function looks like:

```<code>public static function getResponseBodySummary(ResponseInterface $response) {
    $body = $response->getBody();

    if (!$body->isSeekable() || !$body->isReadable()) {
        return null;
    }

    $size = $body->getSize();

    if ($size === 0) {
        return null;
    }

    // Matches any printable character, including unicode characters:
    // letters, marks, numbers, punctuation, spacing, and separators.
    if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $body)) {
        return null;
    }

    return $body;

}
</code>```

Title: error log truncated in laravel 5.3

Body:
None of these solutions here helped me. I found a solution here that helped. By the user sidk2020. Here is his solution in case the link breaks:

I did something very adventurous. I modified guzzel's exception handler

guzzel on purpose only reads up 120 bytes of info and prints truncated next to it.

The file is located at : /vendor/guzzlehttp/guzzle/src/Exception/RequestException.php

So I modified that function and below is what my function looks like:

public static function getResponseBodySummary(ResponseInterface $response) {
    $body = $response->getBody();

    if (!$body->isSeekable() || !$body->isReadable()) {
        return null;
    }

    $size = $body->getSize();

    if ($size === 0) {
        return null;
    }

    // Matches any printable character, including unicode characters:
    // letters, marks, numbers, punctuation, spacing, and separators.
    if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $body)) {
        return null;
    }

    return $body;

}


问:
BigQuery: Persistent UDF with optional parameters
I'm using the persisten UDF functions, but not sure how to make them using optional parameters, like default value.

For example a simple function replacing NaN:

```<code>CREATE OR REPLACE FUNCTION
`my_project.functions.ifnan`(number ANY TYPE, default_value ANY TYPE)
AS
(
if(is_nan(number),default_value,number)
);
</code>```

How can I make it work like ifnan(value) returning 0 by default and only if other default value specified overwrite the 0?

Something like ifnan(number [,default value])

答:
Looking at the documentation we can see that for both SQL and JavaScript UDFs this kind of structure is not specified.

In the SQL syntax:

```<code>CREATE [OR REPLACE] [TEMPORARY | TEMP] FUNCTION [IF NOT EXISTS]
    [[`project_name`.]dataset_name.]function_name
    ([named_parameter[, ...]])
  [RETURNS data_type]
  AS (sql_expression)

named_parameter:
  param_name param_type
</code>```

In the JavaScript syntax:

```<code>CREATE [OR REPLACE] [TEMPORARY | TEMP] FUNCTION [IF NOT EXISTS]
    [[`project_name`.]dataset_name.]function_name
    ([named_parameter[, ...]])
  RETURNS data_type
  LANGUAGE js
  [OPTIONS (library = library_array)]
  AS javascript_code
</code>```

Besides that, we can find the followig statement:

named_parameter. Consists of a comma-separated param_name and
  param_type pair. The value of param_type is a BigQuery data type. For
  a SQL UDF, the value of param_type may also be ANY TYPE.

Hence, it would unfortunately appear that this is not a possibility when using UDFs in BigQuery.

If you need any further assistence, please let me know.

Body:
I'm using the persisten UDF functions, but not sure how to make them using optional parameters, like default value.

For example a simple function replacing NaN:

CREATE OR REPLACE FUNCTION
`my_project.functions.ifnan`(number ANY TYPE, default_value ANY TYPE)
AS
(
if(is_nan(number),default_value,number)
);

How can I make it work like ifnan(value) returning 0 by default and only if other default value specified overwrite the 0?

Something like ifnan(number [,default value])

Body:
Looking at the documentation we can see that for both SQL and JavaScript UDFs this kind of structure is not specified.

In the SQL syntax:

CREATE [OR REPLACE] [TEMPORARY | TEMP] FUNCTION [IF NOT EXISTS]
    [[`project_name`.]dataset_name.]function_name
    ([named_parameter[, ...]])
  [RETURNS data_type]
  AS (sql_expression)

named_parameter:
  param_name param_type

In the JavaScript syntax:

CREATE [OR REPLACE] [TEMPORARY | TEMP] FUNCTION [IF NOT EXISTS]
    [[`project_name`.]dataset_name.]function_name
    ([named_parameter[, ...]])
  RETURNS data_type
  LANGUAGE js
  [OPTIONS (library = library_array)]
  AS javascript_code

Besides that, we can find the followig statement:

named_parameter. Consists of a comma-separated param_name and
  param_type pair. The value of param_type is a BigQuery data type. For
  a SQL UDF, the value of param_type may also be ANY TYPE.

Hence, it would unfortunately appear that this is not a possibility when using UDFs in BigQuery.

If you need any further assistence, please let me know.


问:
Pandas how to count frequencies of patterns in dataframe
I have this sample dataframe:

```<code>ID,Action,Station
01,P,S1
01,R,S2
01,P,S1
01,R,S2
02,P,S2
02,R,S1
02,P,S2
02,R,S1
03,P,S2
03,R,S1
</code>```

My goal is to count patterns of occurrencies in Action and Station columns such as ordered couples like (P,R) and corresponding Station values. So that the resulting dataframe would appear as:

```<code>S1,S2,2
S2,S1,3
</code>```

So the pattern to find is the (P,R) tuple for each ID (ID values may be duplicated) and count their frequencies in Station.

My attemps so far went to groupby by Action and Station and get their value counts:

```<code>g = df.groupby(['Station','ID'])['Action'].size()
</code>```

and get:

```<code>Station  ID
S1       1     2
         2     2
         3     1
S2       1     2
         2     2
         3     1
Name: Action, dtype: int64
</code>```

but still I cannot take care of the (P,R) tuple and their frequencies.

答:
One way is to group P,R by cumsum(), and use cumcount:

```<code>(df.assign(order=df.Action.eq('P')
                   .groupby(df['ID'])  # this might not be necessary
                   .cumsum())
   .groupby(['ID', 'order'])
   .Station.agg(tuple)
   .groupby('ID').value_counts()
)
</code>```

Output:

```<code>ID  Station
1   (S1, S2)    2
2   (S2, S1)    2
3   (S2, S1)    1
Name: Station, dtype: int64
</code>```

Body:
I have this sample dataframe:

ID,Action,Station
01,P,S1
01,R,S2
01,P,S1
01,R,S2
02,P,S2
02,R,S1
02,P,S2
02,R,S1
03,P,S2
03,R,S1

My goal is to count patterns of occurrencies in Action and Station columns such as ordered couples like (P,R) and corresponding Station values. So that the resulting dataframe would appear as:

S1,S2,2
S2,S1,3

So the pattern to find is the (P,R) tuple for each ID (ID values may be duplicated) and count their frequencies in Station.

My attemps so far went to groupby by Action and Station and get their value counts:

g = df.groupby(['Station','ID'])['Action'].size()

and get:

Station  ID
S1       1     2
         2     2
         3     1
S2       1     2
         2     2
         3     1
Name: Action, dtype: int64

but still I cannot take care of the (P,R) tuple and their frequencies.

Body:
One way is to group P,R by cumsum(), and use cumcount:

(df.assign(order=df.Action.eq('P')
                   .groupby(df['ID'])  # this might not be necessary
                   .cumsum())
   .groupby(['ID', 'order'])
   .Station.agg(tuple)
   .groupby('ID').value_counts()
)

Output:

ID  Station
1   (S1, S2)    2
2   (S2, S1)    2
3   (S2, S1)    1
Name: Station, dtype: int64


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答:
Obviously, include will only generate a warning...

So, if you have potentially missing files (such as dynamically including templates that may be safe to fail) and you are suppressing warnings (or don't mind bloated logs) then file_exists & require simply becomes include.

However, that doesn't seem like a very common use case.  The reason that include is still very common (Occam's Razor?) is more likely, simply this:

include makes more semantic sense, and is seen in other languages.


问:
Can't get razor page route to work using anchor tag helper
Background

This is a follow on issue to an initial question I asked around asp.net core v3.1 razor page routes.

I added the following to the startup as suggested in the solution here which allowed me to route to the razor page in both ways I wanted:

services.AddMvc()
        .AddRazorPagesOptions(options =>
                 options.Conventions.AddAreaPageRoute("Identity", "/account/signupandapply", "/identity/account/signup")
        );
```

<pre class="lang-cs prettyprint-override"><code>/identity/account/signup
/identity/account/signupandapply/<fooapplyid>
</code>```

Issue

I'm struggling to use the anchor tag helper to respect the path route /identity/account/signupandapply/<fooapplyid>. The href shows using the parameter instead /identity/account/signupandapply?fooapplyid=<fooapplyid>. This is my anchor tag helper markup:

Apply here
```

<p>Currently, I'm manually setting the href but would like to know how to get this working using the tag helper.</p>

<pre class="lang-html prettyprint-override"><code>Apply here
</code>```

Note: The anchor markup is being added to a view outside of the identity area.

Attempted

I've tried adding the below which shows the href as I want. I.e /identity/account/signupandapply/<fooapplyid>

.AddAreaPageRoute("Identity", "/account/signupandapply", "/identity/account/signupandapply/{applyid}")
```

<p>But I then get an error when I go to the page, which makes sense</p>

<pre class="lang-cs prettyprint-override"><code>AmbiguousMatchException: The request matched multiple endpoints. Matches: /Account/SignUpAndApply /Account/SignUpAndApply
</code>```

Neither of these work, the href still shows as ?applyid=:

.AddAreaPageRoute("Identity", "/account/signupandapply?applyid=", "/identity/account/signupandapply/{applyid}")

.AddAreaPageRoute("Identity", "/account/signupandapply/{applyid?}", "/identity/account/signupandapply/{applyid}")
```

Question

Is there a further startup route that needs defining or how do I get the anchor tag helper to respect the path route?

答:
```<code>AddAreaPageRoute("Identity", "/account/signupandapply", "/identity/account/signup")
</code>```

To quote the docs on this (emphasis mine):

conventions.AddAreaPageRoute(string areaName, string pageName, string route)

Adds the specified route to the page at the specified pageName located in the specified area.

The page can be routed via route in addition to the default set of path based routes. All links generated for this page will use the specified route.

So this convention effectively tells the routing to use the /identity/acount/signup route from now on to generate all links, while accepting incoming routes to hit both these routes.

Unfortunately, I don’t think that you can control this any better using the page conventions. Razor pages do not really fit a routing model where you are having different route to reach the same page. After all, Razor pages are page-centric instead of route-centric like MVC actions.

So if this is a hard requirement for you, you might want to look at using a controller for this one use-case instead that renders the same view. For what it’s worth, controllers do mix nicely with an application that is otherwise using Razor pages.

Body:
Background

This is a follow on issue to an initial question I asked around asp.net core v3.1 razor page routes.

I added the following to the startup as suggested in the solution here which allowed me to route to the razor page in both ways I wanted:

services.AddMvc()
        .AddRazorPagesOptions(options =>
                 options.Conventions.AddAreaPageRoute("Identity", "/account/signupandapply", "/identity/account/signup")
        );

/identity/account/signup
/identity/account/signupandapply/<fooapplyid>

Issue

I'm struggling to use the anchor tag helper to respect the path route /identity/account/signupandapply/<fooapplyid>. The href shows using the parameter instead /identity/account/signupandapply?fooapplyid=<fooapplyid>. This is my anchor tag helper markup:

Apply here

Currently, I'm manually setting the href but would like to know how to get this working using the tag helper.

Apply here

Note: The anchor markup is being added to a view outside of the identity area.

Attempted

I've tried adding the below which shows the href as I want. I.e /identity/account/signupandapply/<fooapplyid>

.AddAreaPageRoute("Identity", "/account/signupandapply", "/identity/account/signupandapply/{applyid}")

But I then get an error when I go to the page, which makes sense

AmbiguousMatchException: The request matched multiple endpoints. Matches: /Account/SignUpAndApply /Account/SignUpAndApply

Neither of these work, the href still shows as ?applyid=:

.AddAreaPageRoute("Identity", "/account/signupandapply?applyid=", "/identity/account/signupandapply/{applyid}")

.AddAreaPageRoute("Identity", "/account/signupandapply/{applyid?}", "/identity/account/signupandapply/{applyid}")

Question

Is there a further startup route that needs defining or how do I get the anchor tag helper to respect the path route?

Body:
AddAreaPageRoute("Identity", "/account/signupandapply", "/identity/account/signup")

To quote the docs on this (emphasis mine):

conventions.AddAreaPageRoute(string areaName, string pageName, string route)

Adds the specified route to the page at the specified pageName located in the specified area.

The page can be routed via route in addition to the default set of path based routes. All links generated for this page will use the specified route.

So this convention effectively tells the routing to use the /identity/acount/signup route from now on to generate all links, while accepting incoming routes to hit both these routes.

Unfortunately, I don’t think that you can control this any better using the page conventions. Razor pages do not really fit a routing model where you are having different route to reach the same page. After all, Razor pages are page-centric instead of route-centric like MVC actions.

So if this is a hard requirement for you, you might want to look at using a controller for this one use-case instead that renders the same view. For what it’s worth, controllers do mix nicely with an application that is otherwise using Razor pages.