问:
I'm trying to automatically hide sheets in google sheets
I've set up timesheets in google sheets for my employees. Each employee has their own document, and each week at the start of the pay period, I'll make a new sheet in each document and hide the sheet from the previous week. The new sheet is named by the dates of that pay period (i.e. Feb 12 - Feb 18) I'm trying to write a script that can do this automatically for me. The script involves two functions that run on a time-based trigger. The first function is working perfectly and creates a new sheet each week at the start of the pay period with the correct dates as the name of the sheet. The second function to hide the old sheet is not working. I have the triggers staggered, so that the new sheet is created several hours before the old one should be hidden. Here is what I've tried for hiding the old sheet (the Template sheet is what is getting copied to each of the employee's documents, where B2 is the start date of the pay period and H2 is the end of the pay period).</p>

```<code>  var ss = SpreadsheetApp.openById('TEMPLATE SHEET ID').getActiveSheet()
  var newName1 = Utilities.formatDate(ss.getRange("B2").getValue(),"CST","MMM dd");
  var newName2 = Utilities.formatDate(ss.getRange("H2").getValue(),"CST","MMM dd");

  var EMPLOYEE = SpreadsheetApp.openById('EMPLOYEE SHEET ID');
  var hideEMPLOYEE = EMPLOYEE.getSheets();
    for(var i =0;i<hideEMPLOYEE.length;i++){
    Logger.log(i);
    if(hideEMPLOYEE[i].getName()!== newName1 + "-" + newName2){
    hideEMPLOYEE[i].hideSheet();
     }
  }
</code>```

答:
Try this:

If B2 or H2 are already dates that's okay this will just create another date from them but if they are strings that the constructor is familiar with then this will create a new date for them as well.

```<code>  var ss = SpreadsheetApp.openById('TEMPLATE SHEET ID').getActiveSheet()
  var newName1 = Utilities.formatDate(new Date(ss.getRange("B2").getValue()),"CST","MMM dd");
  var newName2 = Utilities.formatDate(new Date(ss.getRange("H2").getValue()),"CST","MMM dd");

  var EMPLOYEE = SpreadsheetApp.openById('EMPLOYEE SHEET ID');
  var hideEMPLOYEE = EMPLOYEE.getSheets();
    for(var i=0;i<hideEMPLOYEE.length;i++){
    Logger.log(i);
    if(hideEMPLOYEE[i].getName()!= newName1 + "-" + newName2){
    hideEMPLOYEE[i].hideSheet();
     }
  }
</code>```

Body:
I've set up timesheets in google sheets for my employees. Each employee has their own document, and each week at the start of the pay period, I'll make a new sheet in each document and hide the sheet from the previous week. The new sheet is named by the dates of that pay period (i.e. Feb 12 - Feb 18) I'm trying to write a script that can do this automatically for me. The script involves two functions that run on a time-based trigger. The first function is working perfectly and creates a new sheet each week at the start of the pay period with the correct dates as the name of the sheet. The second function to hide the old sheet is not working. I have the triggers staggered, so that the new sheet is created several hours before the old one should be hidden. Here is what I've tried for hiding the old sheet (the Template sheet is what is getting copied to each of the employee's documents, where B2 is the start date of the pay period and H2 is the end of the pay period).

  var ss = SpreadsheetApp.openById('TEMPLATE SHEET ID').getActiveSheet()
  var newName1 = Utilities.formatDate(ss.getRange("B2").getValue(),"CST","MMM dd");
  var newName2 = Utilities.formatDate(ss.getRange("H2").getValue(),"CST","MMM dd");

  var EMPLOYEE = SpreadsheetApp.openById('EMPLOYEE SHEET ID');
  var hideEMPLOYEE = EMPLOYEE.getSheets();
    for(var i =0;i<hideEMPLOYEE.length;i++){
    Logger.log(i);
    if(hideEMPLOYEE[i].getName()!== newName1 + "-" + newName2){
    hideEMPLOYEE[i].hideSheet();
     }
  }

Body:
Try this:

If B2 or H2 are already dates that's okay this will just create another date from them but if they are strings that the constructor is familiar with then this will create a new date for them as well.

  var ss = SpreadsheetApp.openById('TEMPLATE SHEET ID').getActiveSheet()
  var newName1 = Utilities.formatDate(new Date(ss.getRange("B2").getValue()),"CST","MMM dd");
  var newName2 = Utilities.formatDate(new Date(ss.getRange("H2").getValue()),"CST","MMM dd");

  var EMPLOYEE = SpreadsheetApp.openById('EMPLOYEE SHEET ID');
  var hideEMPLOYEE = EMPLOYEE.getSheets();
    for(var i=0;i<hideEMPLOYEE.length;i++){
    Logger.log(i);
    if(hideEMPLOYEE[i].getName()!= newName1 + "-" + newName2){
    hideEMPLOYEE[i].hideSheet();
     }
  }


来源: stackexchange

问:
How to create a firebase cloud function that could trigger when database is read
Is it possible to have a firebase cloud function that could trigger when sone one read the realtime database.  </p>

<p>As per this document https://firebase.google.com/docs/functions/database-events , We can have cloud function to trigger when data is created, updated, or deleted on Realtime Database. But i want to do some external network call if some one is reading the data. </p>

答:
Right now there is no OnRead trigger or a way to achieve this behavior, however Here is a feature request on Google to support this in the future.

I recommend you to follow up over there to see any progress made on this.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to have a firebase cloud function that could trigger when sone one read the realtime database.

As per this document https://firebase.google.com/docs/functions/database-events , We can have cloud function to trigger when data is created, updated, or deleted on Realtime Database. But i want to do some external network call if some one is reading the data.


问:
What is the best way to request input from user
I want to request info from user. See example below:

```<code>Your Name: |_________|
      Age: |_________|
  Address: |_________|
</code>```

What is the best way to code the above in HTML?

It is best to implement it in div. Have left and right div for label and input

It is best to implement it in table

答:
No

No

You only need the labels and inputs.

```<code>label {
  width: 16em; /* Adjust for taste */
  padding-right: 1em;
  text-align: right;
  float: left;
  clear: left;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to request info from user. See example below:

Your Name: |_________|
      Age: |_________|
  Address: |_________|

What is the best way to code the above in HTML?

It is best to implement it in div. Have left and right div for label and input

It is best to implement it in table

Body:
No

No

You only need the labels and inputs.

label {
  width: 16em; /* Adjust for taste */
  padding-right: 1em;
  text-align: right;
  float: left;
  clear: left;
}


问:
react button is called before onPress when using Hooks
I am trying to request an API request using hooks. But my problem is that my function is called before I onPress.

I have an custom API component like this:

```<code>const FetchDataPut = (URL) => {

  useEffect(() => {
      async function fetchData() {
          const res = await axios({
                    method: 'put',
                    url: URL,
                    data:{
                      name:'111',
                      email:'222',
                      password:'333',
                      id:'444',
                      phone:'555'
                    }
                  });
          const response = await res;
          console.log(response, 'completed')
      }
      fetchData()
  },[])
  return null
}
</code>```

I could see from the console.log that api request has completed. My problem is that my api component is called before I onPress the button.

This is my Button component:

```<code>const EditAccount = (props) => {

  const Desktop = () => {
    const URL = `MyURL...`
    return (
      <View>
        <Button title='edit account' onPress={FetchDataPut(URL)}/>
      </View>
    )
  }

  return(
    <div>
      <Desktop/>
    </div>
  )
}
</code>```

If I change my onPress function to an arrow function like this:
onPress={()=>FetchDataPut(URL)} component isn't called before I onPress it. But it will give me an error Invalid hook call. Hooks can only be called inside of the body of a function component

Any Idea how to my the api request when I onPress the Button ?

Any comments or advice would be really helpful. Thanks in advance! :)

答:
There are several issues here.

You’re setting the onPress prop to the result of calling FetchDataPut(URL). The prop should be the function itself, not the result of invoking it. By using an arrow function you’re declaring a new function that, when invoked, calls FetchDataPut.

If you’re invoking it on button press, there’s no need for it to be a hook.

Also, FetchDataPut isn’t a React component.

Declare your data fetching function by itself:

async function fetchData(url) {
  return axios({
    method: 'put',
    url: URL,
    data: {
       name:'111',
       email:'222',
       password:'333',
       id:'444',
       phone:'555'
     }
  })
}
```

<p>And then invoke it on button press.</p>

```const handler = async function ( ) {
  // or just inline the axios request right here
  // instead of declaring a separate function for it.
  const result = await fetchData(url);

  // do something with the result
}
```

```<Button onPress={handler} />
```

Apologies for the frequent edits. Trying to do this from my phone.

Body:
I am trying to request an API request using hooks. But my problem is that my function is called before I onPress.

I have an custom API component like this:

const FetchDataPut = (URL) => {

  useEffect(() => {
      async function fetchData() {
          const res = await axios({
                    method: 'put',
                    url: URL,
                    data:{
                      name:'111',
                      email:'222',
                      password:'333',
                      id:'444',
                      phone:'555'
                    }
                  });
          const response = await res;
          console.log(response, 'completed')
      }
      fetchData()
  },[])
  return null
}

I could see from the console.log that api request has completed. My problem is that my api component is called before I onPress the button.

This is my Button component:

const EditAccount = (props) => {

  const Desktop = () => {
    const URL = `MyURL...`
    return (
      <View>
        <Button title='edit account' onPress={FetchDataPut(URL)}/>
      </View>
    )
  }

  return(

      <Desktop/>

  )
}

If I change my onPress function to an arrow function like this:
onPress={()=>FetchDataPut(URL)} component isn't called before I onPress it. But it will give me an error Invalid hook call. Hooks can only be called inside of the body of a function component

Any Idea how to my the api request when I onPress the Button ?

Any comments or advice would be really helpful. Thanks in advance! :)

Body:
There are several issues here.

You’re setting the onPress prop to the result of calling FetchDataPut(URL). The prop should be the function itself, not the result of invoking it. By using an arrow function you’re declaring a new function that, when invoked, calls FetchDataPut.

If you’re invoking it on button press, there’s no need for it to be a hook.

Also, FetchDataPut isn’t a React component.

Declare your data fetching function by itself:

async function fetchData(url) {
  return axios({
    method: 'put',
    url: URL,
    data: {
       name:'111',
       email:'222',
       password:'333',
       id:'444',
       phone:'555'
     }
  })
}

And then invoke it on button press.

const handler = async function ( ) {
  // or just inline the axios request right here
  // instead of declaring a separate function for it.
  const result = await fetchData(url);

  // do something with the result
}

<Button onPress={handler} />

Apologies for the frequent edits. Trying to do this from my phone.


问:
Remove old remote branches from Git
When I use bash autocompletion in Git, it keeps showing me branches of old remotes that I don't have anymore. When I do a git branch -la it shows those old remotes and branches while a git branch -l won't. A ls .git/refs/remotes/ also shows them. However, they are not present in my .git/config and neither are they shown when I run git remote show.

So how do I get rid of them because my autocomplete list is too long right now.

I have already tried:

```<code>git reflog expire --expire=now --all
git gc --prune=now
rm .git/refs/remotes/theoldremote
git remote prune theoldremote
</code>```

I'm also aware of the fact that I can just re-clone the repo but that's just cheating ;-)

答:
I was getting confused when remote branches that had been deleted on the server side were still appearing when I ran:

```<code>$ git branch --all
</code>```

The following command fixed this for me (on git version 2.25.0):

```<code>$ git remote update --prune
</code>```

Title: Remove old remote branches from Git

Body:
When I use bash autocompletion in Git, it keeps showing me branches of old remotes that I don't have anymore. When I do a git branch -la it shows those old remotes and branches while a git branch -l won't. A ls .git/refs/remotes/ also shows them. However, they are not present in my .git/config and neither are they shown when I run git remote show.

So how do I get rid of them because my autocomplete list is too long right now.

I have already tried:

git reflog expire --expire=now --all
git gc --prune=now
rm .git/refs/remotes/theoldremote
git remote prune theoldremote

I'm also aware of the fact that I can just re-clone the repo but that's just cheating ;-)

Body:
I was getting confused when remote branches that had been deleted on the server side were still appearing when I ran:

$ git branch --all

The following command fixed this for me (on git version 2.25.0):

$ git remote update --prune


问:
TableView is not showing row headers properly
I have used this tableview in my android app. The problem i have is, the table doesn't show row headers properly. This is the table:

There are 5 rows and i have added 5 RowHeader items, but the first item is expanded to all row headers.

This is the code of initializing row headers:

```<code>// set row header
List<RowHeader> rowHeaders = new ArrayList<>();
for (PersianDate day : dataset.keySet())
    rowHeaders.add(new RowHeader(Integer.toString(day.getDayOfMonth())));

mTableAdapter.setRowHeaderItems(rowHeaders);
</code>```

in the adapter:

```<code>@Override
public void onBindRowHeaderViewHolder(@NonNull AbstractViewHolder holder, @Nullable RowHeader rowHeaderItemModel, int rowPosition) {
    RowHeader rowHeader = rowHeaderItemModel;

    // Get the holder to update row header item text
    MyRowHeaderViewHolder rowHeaderViewHolder = (MyRowHeaderViewHolder) holder;
    rowHeaderViewHolder.cell_textview.setText(rowHeader.getData());

    // It is necessary to remeasure itself.
    rowHeaderViewHolder.cell_textview.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
    rowHeaderViewHolder.cell_textview.requestLayout();
}
</code>```

Do you know what is the problem?

答: In row header xml file, set height & width for your rowHeaderViewHolder.cell_textview</p>

Body:
I have used this tableview in my android app. The problem i have is, the table doesn't show row headers properly. This is the table:

There are 5 rows and i have added 5 RowHeader items, but the first item is expanded to all row headers.

This is the code of initializing row headers:

// set row header
List<RowHeader> rowHeaders = new ArrayList<>();
for (PersianDate day : dataset.keySet())
    rowHeaders.add(new RowHeader(Integer.toString(day.getDayOfMonth())));

mTableAdapter.setRowHeaderItems(rowHeaders);

in the adapter:

@Override
public void onBindRowHeaderViewHolder(@NonNull AbstractViewHolder holder, @Nullable RowHeader rowHeaderItemModel, int rowPosition) {
    RowHeader rowHeader = rowHeaderItemModel;

    // Get the holder to update row header item text
    MyRowHeaderViewHolder rowHeaderViewHolder = (MyRowHeaderViewHolder) holder;
    rowHeaderViewHolder.cell_textview.setText(rowHeader.getData());

    // It is necessary to remeasure itself.
    rowHeaderViewHolder.cell_textview.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
    rowHeaderViewHolder.cell_textview.requestLayout();
}

Do you know what is the problem?


问:
Is it possible to perform a batch upload to amazon s3?
Does amazon s3 support batch uploads?
I have a job that needs to upload each night ~100K of files that can be up to 1G but is strongly skewed towards small files (90% are less than 100 bytes and 99% are less than 1000 bytes long).

Does the s3 API support uploading multiple objects in a single HTTP call?

All the objects must be available in S3 as individual objects. I cannot host them anywhere else (FTP, etc) or in another format (Database, EC2 local drive, etc). That is an external requirement that I cannot change.

答:
Here's a comprehensive batch solution that copies files from one folder to another using a single call of CommandPool::batch, although under the hood it runs a executeAsync command for each file, so not sure it counts as a single API call.

As I understand you should be able to copy hundreds of thousands of files using this method as there's no way to send a batch to AWS to be processed there, but if you're hosting this at an AWS instance or even running it on Lambda then its "technically" processed at AWS.

Install the SDK:

composer require aws/aws-sdk-php
```
<pre class="lang-php prettyprint-override"><code>use Aws\ResultInterface;
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
use Aws\S3\Exception\DeleteMultipleObjectsException;

$bucket = 'my-bucket-name';

// Setup your credentials in the .aws folder
// See: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_profiles.html
$s3 = new S3Client([
    'profile' => 'default',
    'region'  => 'us-east-2',
    'version' => 'latest'
]);

// Get all files in S3
$files = array();
try {
    $results = $s3->getPaginator('ListObjects', [
        'Bucket' => $bucket,
        'Prefix' => 'existing-folder' // Folder within bucket, or remove this to get all files in the bucket
    ]);

    foreach ($results as $result) {
        foreach ($result['Contents'] as $object) {
            $files[] = $object['Key'];
        }
    }
} catch (AwsException $e) {
    error_log($e->getMessage());
}

if(count($files) > 0){
    // Perform a batch of CopyObject operations.
    $batch = [];
    foreach ($files as $file) {
        $batch[] = $s3->getCommand('CopyObject', array(
            'Bucket'     => $bucket,
            'Key'        => str_replace('existing-folder/', 'new-folder/', $file),
            'CopySource' => $bucket . '/' . $file,
        ));
    }

    try {
        $results = CommandPool::batch($s3, $batch);

        // Check if all files were copied in order to safely delete the old directory
        $count = 0;
        foreach($results as $result) {
            if ($result instanceof ResultInterface) {
                $count++;
            }
            if ($result instanceof AwsException) {
            }
        }

        if($count === count($files)){
            // Delete old directory
            try {
                $s3->deleteMatchingObjects(
                    $bucket, // Bucket
                    'existing-folder' // Prefix, folder within bucket, as indicated above
                );
            } catch (DeleteMultipleObjectsException $exception) {
                return false;
            }

            return true;
        }

        return false;

    } catch (AwsException $e) {
        return $e->getMessage();
    }
}
</code>```

Body:
Here's a comprehensive batch solution that copies files from one folder to another using a single call of CommandPool::batch, although under the hood it runs a executeAsync command for each file, so not sure it counts as a single API call.

As I understand you should be able to copy hundreds of thousands of files using this method as there's no way to send a batch to AWS to be processed there, but if you're hosting this at an AWS instance or even running it on Lambda then its "technically" processed at AWS.

Install the SDK:

composer require aws/aws-sdk-php

use Aws\ResultInterface;
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
use Aws\S3\Exception\DeleteMultipleObjectsException;

$bucket = 'my-bucket-name';

// Setup your credentials in the .aws folder
// See: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_profiles.html
$s3 = new S3Client([
    'profile' => 'default',
    'region'  => 'us-east-2',
    'version' => 'latest'
]);

// Get all files in S3
$files = array();
try {
    $results = $s3->getPaginator('ListObjects', [
        'Bucket' => $bucket,
        'Prefix' => 'existing-folder' // Folder within bucket, or remove this to get all files in the bucket
    ]);

    foreach ($results as $result) {
        foreach ($result['Contents'] as $object) {
            $files[] = $object['Key'];
        }
    }
} catch (AwsException $e) {
    error_log($e->getMessage());
}

if(count($files) > 0){
    // Perform a batch of CopyObject operations.
    $batch = [];
    foreach ($files as $file) {
        $batch[] = $s3->getCommand('CopyObject', array(
            'Bucket'     => $bucket,
            'Key'        => str_replace('existing-folder/', 'new-folder/', $file),
            'CopySource' => $bucket . '/' . $file,
        ));
    }

    try {
        $results = CommandPool::batch($s3, $batch);

        // Check if all files were copied in order to safely delete the old directory
        $count = 0;
        foreach($results as $result) {
            if ($result instanceof ResultInterface) {
                $count++;
            }
            if ($result instanceof AwsException) {
            }
        }

        if($count === count($files)){
            // Delete old directory
            try {
                $s3->deleteMatchingObjects(
                    $bucket, // Bucket
                    'existing-folder' // Prefix, folder within bucket, as indicated above
                );
            } catch (DeleteMultipleObjectsException $exception) {
                return false;
            }

            return true;
        }

        return false;

    } catch (AwsException $e) {
        return $e->getMessage();
    }
}


问:
Is there a way to add performance counter in Azure Log Analytics from command line
Is there a way to added performance counter in Azure Log Analytics using Powershell or azure CLI. The only options I see are for querying. </p>

答:
According to my research, we can use PowerShell command new-azoperationalinsightswindowsperformancecounterdatasource to add windows performance counter. For more details, please refer to the document.
For example

```<code>Connect-AzAccount
$workspace=Get-AzOperationalInsightsWorkspace -ResourceGroupName jimtest -Name hybridWorkspace32979
New-AzOperationalInsightsWindowsPerformanceCounterDataSource -Workspace $workspace -Name "test" -ObjectName ".NET CLR Loading" -CounterName "Total Appdomains" -InstanceName "*" -IntervalSeconds 10
Get-AzOperationalInsightsDataSource -ResourceGroupName jimtest -WorkspaceName hybridWorkspace32979 -Kind WindowsPerformanceCounter
</code>```

Besides, if you want to add Linux performance counter, you can use the command New-AzOperationalInsightsLinuxPerformanceObjectDataSource and Enable-AzOperationalInsightsLinuxPerformanceCollection. For more details, please refer to the article

Body:
According to my research, we can use PowerShell command new-azoperationalinsightswindowsperformancecounterdatasource to add windows performance counter. For more details, please refer to the document.
For example

Connect-AzAccount
$workspace=Get-AzOperationalInsightsWorkspace -ResourceGroupName jimtest -Name hybridWorkspace32979
New-AzOperationalInsightsWindowsPerformanceCounterDataSource -Workspace $workspace -Name "test" -ObjectName ".NET CLR Loading" -CounterName "Total Appdomains" -InstanceName "*" -IntervalSeconds 10
Get-AzOperationalInsightsDataSource -ResourceGroupName jimtest -WorkspaceName hybridWorkspace32979 -Kind WindowsPerformanceCounter

Besides, if you want to add Linux performance counter, you can use the command New-AzOperationalInsightsLinuxPerformanceObjectDataSource and Enable-AzOperationalInsightsLinuxPerformanceCollection. For more details, please refer to the article


问:
Neo4j getting the system's datetime containing micro or nano seconds with cypher
In neo4j I know how to get the current datetime as in now() with milliseconds precision, however I would like to be able to store microseconds or nanoseconds. Is there a way to achieve this via apoc, or adjusting my system time. I was reading about the 'limitations' of java Date and Calendar only storing .SSS ?</p>

```<code>CREATE (l:LogEvent{
        eventID : 'I01'
        , dt : System.nanoTime({timezone:'UTC'})
        });
</code>```

答:
The temporal instants DateTime, LocalDateTime, Time, and LocalTime support the microsecond and nanosecond fields. Those fields can be set when using the appropriate temporal function to create an instant.

For example:

```<code>RETURN datetime({year:1984, month:11, day:11, hour:12, minute:31, second:14, nanosecond: 645876123, timezone:'Europe/Stockholm'})
</code>```

In addition, if you have an epoch time with microsecond (or nanosecond) precision that you want to store, just break it down into 2 parts: its epoch seconds, and the remaining microseconds (or nanoseconds). With those 2 parts, you can create a DateTime as illustrated here (assuming secs, micros, and nanos are passed as parameters):

```<code>RETURN datetime({epochSeconds: $secs, microsecond: $micros})
</code>```

or

```<code>RETURN datetime({epochSeconds: $secs, nanosecond: $nanos})
</code>```

Body:
In neo4j I know how to get the current datetime as in now() with milliseconds precision, however I would like to be able to store microseconds or nanoseconds. Is there a way to achieve this via apoc, or adjusting my system time. I was reading about the 'limitations' of java Date and Calendar only storing .SSS ?

CREATE (l:LogEvent{
        eventID : 'I01'
        , dt : System.nanoTime({timezone:'UTC'})
        });

Body:
The temporal instants DateTime, LocalDateTime, Time, and LocalTime support the microsecond and nanosecond fields. Those fields can be set when using the appropriate temporal function to create an instant.

For example:

RETURN datetime({year:1984, month:11, day:11, hour:12, minute:31, second:14, nanosecond: 645876123, timezone:'Europe/Stockholm'})

In addition, if you have an epoch time with microsecond (or nanosecond) precision that you want to store, just break it down into 2 parts: its epoch seconds, and the remaining microseconds (or nanoseconds). With those 2 parts, you can create a DateTime as illustrated here (assuming secs, micros, and nanos are passed as parameters):

RETURN datetime({epochSeconds: $secs, microsecond: $micros})

or

RETURN datetime({epochSeconds: $secs, nanosecond: $nanos})


问:
Linker: Moving all functions but two to a specific memory region
I am working on firmware for a PIC32MX microcontroller.  The program memory should be split into three segments:

Section 1: interrupt service routine and main function (startup_region)

Section 2: 50% of remaining program memory (program1)

Section 3: 50% of remaining program memory (program2)

The firmware is only stored in either Section 2 or 3.  The other is reserved for future updates.  As such the active region can safely override the other to store the update.  A config bit is flipped and the main() function of Section 0 now jumps to the other program on reboot.

As such I need the linker to put all functions except isr and main into Section 1 and everything else into Section 2.  Section 3 must be left completely empty, as it may be overridden in the future.

I already tried to achieve this by modifying the default linker script, however I had no success.

linkerscript.ld:

```<code>/* [...] */
INCLUDE procdefs.gld
/* [...] */
SECTIONS
{
  /* [...] */
  .text :
  {
    /* isr() and main() should be at the very first locations in program memory */
    *(.text.isr)
    *(.text.main)
    /* [...] */
    . = ALIGN(4) ;
  } >kseg0_program_mem

  .program1 :
  {
    *(*.text)
  } >program1

  /* [...] */
}
</code>```

procdefs.gld:

```<code>/* [...] */
MEMORY
{
  kseg0_program_mem     (rx)  : ORIGIN = 0x9D000000, LENGTH = 0x10000
  startup_region        (rx)  : ORIGIN = 0x9D000000, LENGTH = 0x01000
  program1              (rx)  : ORIGIN = 0x9D002000, LENGTH = 0x07000
  program2              (rx)  : ORIGIN = 0x9D009000, LENGTH = 0x07000
  kseg0_boot_mem              : ORIGIN = 0x9FC00490, LENGTH = 0x970
  /* [...] */
}
/* [...] */
</code>```

This results in the following:

isr() and main() are where they are supposed to be (0x9D00000 is the KSEG0 virtual address of the beginning of the program flash)

```<code>.text           0x9d000000       0x94
 *(.text.isr)
 .text.isr      0x9d000000       0x60 build/default/production/main.o
                0x9d000000                isr
 *(.text.main)
 .text.main     0x9d000060       0x34 build/default/production/main.o
                0x9d000060                main
</code>```

The program1 region is correctly placed and most object files are listed correctly (notice however, that main.o is listed again -- it was already used).

```<code>.program1       0x9d002000      0xc44
 *(*.text)
 .text          0x9d002000        0x0 /opt/microchip/xc32/v2.10/bin/bin/../../lib/gcc/pic32mx/4.8.3/../../../../pic32mx/lib/./proc/32MX330F064H/crt0_mips32r2.o
 .text          0x9d002000        0x0 /opt/microchip/xc32/v2.10/bin/bin/../../lib/gcc/pic32mx/4.8.3/../../../../pic32mx/lib/debug-exception-return.o
 .text          0x9d002000        0x0 build/default/production/main.o
 .text          0x9d002000        0x0 build/default/production/commands.o
 /* [...] */
 .text          0x9d002000        0x0 build/default/production/micro-ecc/uECC.o
</code>```

However, some function are located outside of this region:

```<code>.text.uECC_verify
                0x9d000b04      0x7c0
 .text.uECC_verify
                0x9d000b04      0x7c0 build/default/production/micro-ecc/uECC.o
                0x9d000b04                uECC_verify

.text.vli_mmod_fast_secp256r1
                0x9d0012c4      0x520
 .text.vli_mmod_fast_secp256r1
                0x9d0012c4      0x520 build/default/production/micro-ecc/uECC.o
</code>```

I do not understand why this happens.

My questions are:

How can I enforce the linker to put all functions (except main and isr) into program1.

How can I prohibit the linker to put anything into program2, so that it remains free.

I am compiling the software with the -ffunction-segments switch, so that each function gets its own segment.

The original linkerscript also contains this suspicious looking comment:

```<code>/* Code Sections - Note that input sections *(.text) and *(.text.*)
   are not mapped here. Starting in C32 v2.00, the best-fit allocator
   locates them, so that .text may flow around absolute sections
   as needed.
*/
</code>```

答:
The object file main.o is not the same as the function’s memory segment .tex.main. If this object file produces some other text segments they will be placed elsewhere. This is what you see in your map file.

As @Ctx mentioned the syntax of your text segment is wrong instead of *(*.text) it should be

```<code>  .program1 :
  {
    *(.text*)
  } >program1
</code>```

This way all other text segments will be properly placed in the program1 memory.

Body:
I am working on firmware for a PIC32MX microcontroller.  The program memory should be split into three segments:

Section 1: interrupt service routine and main function (startup_region)

Section 2: 50% of remaining program memory (program1)

Section 3: 50% of remaining program memory (program2)

The firmware is only stored in either Section 2 or 3.  The other is reserved for future updates.  As such the active region can safely override the other to store the update.  A config bit is flipped and the main() function of Section 0 now jumps to the other program on reboot.

As such I need the linker to put all functions except isr and main into Section 1 and everything else into Section 2.  Section 3 must be left completely empty, as it may be overridden in the future.

I already tried to achieve this by modifying the default linker script, however I had no success.

linkerscript.ld:

/* [...] */
INCLUDE procdefs.gld
/* [...] */
SECTIONS
{
  /* [...] */
  .text :
  {
    /* isr() and main() should be at the very first locations in program memory */
    *(.text.isr)
    *(.text.main)
    /* [...] */
    . = ALIGN(4) ;
  } >kseg0_program_mem

  .program1 :
  {
    *(*.text)
  } >program1

  /* [...] */
}

procdefs.gld:

/* [...] */
MEMORY
{
  kseg0_program_mem     (rx)  : ORIGIN = 0x9D000000, LENGTH = 0x10000
  startup_region        (rx)  : ORIGIN = 0x9D000000, LENGTH = 0x01000
  program1              (rx)  : ORIGIN = 0x9D002000, LENGTH = 0x07000
  program2              (rx)  : ORIGIN = 0x9D009000, LENGTH = 0x07000
  kseg0_boot_mem              : ORIGIN = 0x9FC00490, LENGTH = 0x970
  /* [...] */
}
/* [...] */

This results in the following:

isr() and main() are where they are supposed to be (0x9D00000 is the KSEG0 virtual address of the beginning of the program flash)

.text           0x9d000000       0x94
 *(.text.isr)
 .text.isr      0x9d000000       0x60 build/default/production/main.o
                0x9d000000                isr
 *(.text.main)
 .text.main     0x9d000060       0x34 build/default/production/main.o
                0x9d000060                main

The program1 region is correctly placed and most object files are listed correctly (notice however, that main.o is listed again -- it was already used).

.program1       0x9d002000      0xc44
 *(*.text)
 .text          0x9d002000        0x0 /opt/microchip/xc32/v2.10/bin/bin/../../lib/gcc/pic32mx/4.8.3/../../../../pic32mx/lib/./proc/32MX330F064H/crt0_mips32r2.o
 .text          0x9d002000        0x0 /opt/microchip/xc32/v2.10/bin/bin/../../lib/gcc/pic32mx/4.8.3/../../../../pic32mx/lib/debug-exception-return.o
 .text          0x9d002000        0x0 build/default/production/main.o
 .text          0x9d002000        0x0 build/default/production/commands.o
 /* [...] */
 .text          0x9d002000        0x0 build/default/production/micro-ecc/uECC.o

However, some function are located outside of this region:

.text.uECC_verify
                0x9d000b04      0x7c0
 .text.uECC_verify
                0x9d000b04      0x7c0 build/default/production/micro-ecc/uECC.o
                0x9d000b04                uECC_verify

.text.vli_mmod_fast_secp256r1
                0x9d0012c4      0x520
 .text.vli_mmod_fast_secp256r1
                0x9d0012c4      0x520 build/default/production/micro-ecc/uECC.o

I do not understand why this happens.

My questions are:

How can I enforce the linker to put all functions (except main and isr) into program1.

How can I prohibit the linker to put anything into program2, so that it remains free.

I am compiling the software with the -ffunction-segments switch, so that each function gets its own segment.

The original linkerscript also contains this suspicious looking comment:

/* Code Sections - Note that input sections *(.text) and *(.text.*)
   are not mapped here. Starting in C32 v2.00, the best-fit allocator
   locates them, so that .text may flow around absolute sections
   as needed.
*/

Body:
The object file main.o is not the same as the function’s memory segment .tex.main. If this object file produces some other text segments they will be placed elsewhere. This is what you see in your map file.

As @Ctx mentioned the syntax of your text segment is wrong instead of *(*.text) it should be

  .program1 :
  {
    *(.text*)
  } >program1

This way all other text segments will be properly placed in the program1 memory.


问:
SQL query to return the latest date when the column has changed
I have a table per_all_assignments_m paam that has position_id and other object ids. This table has effetive_start_Date and effective_end_date.
Whenever there is an update in this table, the effective_start_Date changes to the date when the change was made.

```<code>assignment_number    person_id             eff_start_Date         eff_end_date         POSISTION_ID    GRADE_ID
E12                   12                     12-JAN-2020           31-DEC-4712           10                 2
E12                   12                     25-NOV-2019           11-JAN-2020           10                 2
E12                   12                     02-APR-2019           24-NOV-2019           8                  2
---
E11                   11                    12-JAN-2020           31-DEC-4712           10                 2
E11                   11                     25-NOV-2019           11-JAN-2020           10                 2
E11                   11                     02-APR-2019           24-NOV-2019           10                  2
</code>```

The below query will not return anything for PREv_Job_TItle since there is no change in position_id in the latest 2 rows.

I want to fetch another column in the below query -  cur_eff_dt. If there is no change in the latest rows as of trunc(sysdate) in the PAAM table,
then the cur_eff_dt should return the last date when the position_id was changed or the first date that position was tagged to the employee.
From the above table - cur_eff_dt should be 25-Nov-2019 for employee E12.  FOR Employee number - E11 it should be 02-APR-2019.

Any function through which this can be achieved ?

```<code>    select distinct
PAPF.PERSON_NUMBER,
    NULLIF((select distinct name
from   (
  select distinct m.person_id,m.position_id,h.name,
         lead(m.position_id,1,0) over (order by m.position_id) as nextr ,
         lag(m.position_id,1,0) over (order by m.position_id) as prevr
  from   per_all_assignments_M m,HR_ALL_POSITIONS_F F,hr_all_positions_f_vL h
  where m.position_id=f.position_id
             and f.position_id=h.position_id
 and sysdate between h.effective_start_date and h.effective_end_date
and m.person_id=papf.person_id
and h.effective_end_date=TO_DATE('12/31/4712 00:00:00', 'MM/DD/YYYY HH24:MI:SS'))
where nextr<>prevr and rownum=1),POS.NAME)PREv_Job_TItle,
     POS.NAME Current_job_title

from    per_all_people_f PAPF
        ,PER_PERSON_NAMES_F PPNF
        ,PER_PERIODS_OF_SERVICE PPOS
        ,PER_ALL_ASSIGNMENTS_M PAAM
        ,PER_PERSON_TYPES PPT
        ,PER_GRADES_F_TL PGF
        ,hr_all_positions_f_vL POS
        ,PER_JOBS_F PJF

where   1=1
and papf.person_number = '111'

        AND PPOS.PERSON_ID =PAPF.PERSON_ID
        AND PPOS.PERSON_ID=PPNF.PERSON_ID
        AND PPNF.NAME_TYPE = 'GLOBAL'
        AND PAAM.PERSON_ID=PAPF.PERSON_ID
        AND PPOS.PERSON_ID=PAAM.PERSON_ID
        AND PPOS.LEGISLATION_CODE=PAAM.LEGISLATION_CODE
        AND PAAM.PRIMARY_ASSIGNMENT_FLAG = 'Y'
        AND PAAM.ASSIGNMENT_TYPE = 'E'
        AND PAAM.EFFECTIVE_LATEST_CHANGE = 'Y'
        AND PAAM.ASSIGNMENT_STATUS_TYPE = 'ACTIVE'
        AND PAAM.PRIMARY_FLAG='Y'
        AND PAAM.PERIOD_OF_SERVICE_ID = PPOS.PERIOD_OF_SERVICE_ID
        AND PGF.GRADE_ID(+)=  PAAM.GRADE_ID
        AND PGF.LANGUAGE='US'
        AND POS.POSITION_ID(+)=PAAM.POSITION_ID
        AND PJF.JOB_ID(+)=PAAM.JOB_ID
                        AND PAAM.EFFECTIVE_END_DATE=TO_DATE('12/31/4712 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
        AND TRUNC(SYSDATE) BETWEEN PAPF.EFFECTIVE_START_DATE AND PAPF.EFFECTIVE_END_DATE

        AND TRUNC(SYSDATE) BETWEEN PAAM.EFFECTIVE_START_DATE AND PAAM.EFFECTIVE_END_DATE
        AND TRUNC(SYSDATE) BETWEEN PGF.EFFECTIVE_START_DATE AND PGF.EFFECTIVE_END_DATE
        AND TRUNC(SYSDATE) BETWEEN POS.EFFECTIVE_START_DATE AND POS.EFFECTIVE_END_DATE
</code>```

答:
I am not sure about your current query but you can achieve what is required using following query:

```<code>Select person_id, assignment_number,
       Max(effective_start_date) keep (dense_rank last order by rn) as cut_off_date
From
(Select t.*,
        case when lead(position_id)
          over (partition by person_id, assignment_number order by effective_start_date)
        <> position_id then 1 else 0 end as rn
From per_all_assigments_m t
Where person_id in (11,12))
Group by person_id, assignment_number
</code>```

Cheers!!

Body:
I have a table per_all_assignments_m paam that has position_id and other object ids. This table has effetive_start_Date and effective_end_date.
Whenever there is an update in this table, the effective_start_Date changes to the date when the change was made.

assignment_number    person_id             eff_start_Date         eff_end_date         POSISTION_ID    GRADE_ID
E12                   12                     12-JAN-2020           31-DEC-4712           10                 2
E12                   12                     25-NOV-2019           11-JAN-2020           10                 2
E12                   12                     02-APR-2019           24-NOV-2019           8                  2
---
E11                   11                    12-JAN-2020           31-DEC-4712           10                 2
E11                   11                     25-NOV-2019           11-JAN-2020           10                 2
E11                   11                     02-APR-2019           24-NOV-2019           10                  2

The below query will not return anything for PREv_Job_TItle since there is no change in position_id in the latest 2 rows.

I want to fetch another column in the below query -  cur_eff_dt. If there is no change in the latest rows as of trunc(sysdate) in the PAAM table,
then the cur_eff_dt should return the last date when the position_id was changed or the first date that position was tagged to the employee.
From the above table - cur_eff_dt should be 25-Nov-2019 for employee E12.  FOR Employee number - E11 it should be 02-APR-2019.

Any function through which this can be achieved ?

    select distinct
PAPF.PERSON_NUMBER,
    NULLIF((select distinct name
from   (
  select distinct m.person_id,m.position_id,h.name,
         lead(m.position_id,1,0) over (order by m.position_id) as nextr ,
         lag(m.position_id,1,0) over (order by m.position_id) as prevr
  from   per_all_assignments_M m,HR_ALL_POSITIONS_F F,hr_all_positions_f_vL h
  where m.position_id=f.position_id
             and f.position_id=h.position_id
 and sysdate between h.effective_start_date and h.effective_end_date
and m.person_id=papf.person_id
and h.effective_end_date=TO_DATE('12/31/4712 00:00:00', 'MM/DD/YYYY HH24:MI:SS'))
where nextr<>prevr and rownum=1),POS.NAME)PREv_Job_TItle,
     POS.NAME Current_job_title

from    per_all_people_f PAPF
        ,PER_PERSON_NAMES_F PPNF
        ,PER_PERIODS_OF_SERVICE PPOS
        ,PER_ALL_ASSIGNMENTS_M PAAM
        ,PER_PERSON_TYPES PPT
        ,PER_GRADES_F_TL PGF
        ,hr_all_positions_f_vL POS
        ,PER_JOBS_F PJF

where   1=1
and papf.person_number = '111'

        AND PPOS.PERSON_ID =PAPF.PERSON_ID
        AND PPOS.PERSON_ID=PPNF.PERSON_ID
        AND PPNF.NAME_TYPE = 'GLOBAL'
        AND PAAM.PERSON_ID=PAPF.PERSON_ID
        AND PPOS.PERSON_ID=PAAM.PERSON_ID
        AND PPOS.LEGISLATION_CODE=PAAM.LEGISLATION_CODE
        AND PAAM.PRIMARY_ASSIGNMENT_FLAG = 'Y'
        AND PAAM.ASSIGNMENT_TYPE = 'E'
        AND PAAM.EFFECTIVE_LATEST_CHANGE = 'Y'
        AND PAAM.ASSIGNMENT_STATUS_TYPE = 'ACTIVE'
        AND PAAM.PRIMARY_FLAG='Y'
        AND PAAM.PERIOD_OF_SERVICE_ID = PPOS.PERIOD_OF_SERVICE_ID
        AND PGF.GRADE_ID(+)=  PAAM.GRADE_ID
        AND PGF.LANGUAGE='US'
        AND POS.POSITION_ID(+)=PAAM.POSITION_ID
        AND PJF.JOB_ID(+)=PAAM.JOB_ID
                        AND PAAM.EFFECTIVE_END_DATE=TO_DATE('12/31/4712 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
        AND TRUNC(SYSDATE) BETWEEN PAPF.EFFECTIVE_START_DATE AND PAPF.EFFECTIVE_END_DATE

        AND TRUNC(SYSDATE) BETWEEN PAAM.EFFECTIVE_START_DATE AND PAAM.EFFECTIVE_END_DATE
        AND TRUNC(SYSDATE) BETWEEN PGF.EFFECTIVE_START_DATE AND PGF.EFFECTIVE_END_DATE
        AND TRUNC(SYSDATE) BETWEEN POS.EFFECTIVE_START_DATE AND POS.EFFECTIVE_END_DATE

Body:
I am not sure about your current query but you can achieve what is required using following query:

Select person_id, assignment_number,
       Max(effective_start_date) keep (dense_rank last order by rn) as cut_off_date
From
(Select t.*,
        case when lead(position_id)
          over (partition by person_id, assignment_number order by effective_start_date)
        <> position_id then 1 else 0 end as rn
From per_all_assigments_m t
Where person_id in (11,12))
Group by person_id, assignment_number

Cheers!!


问:
Apollo client useQuery not updating data after useMutation
Using this mutation:

```<code>import produce from 'immer

const [createItem] = useMutation(CREATE_ITEM, {
update (client, { data: { createItem } }) {
  const queryResults = client.readQuery({
    query: GET_LATEST_ORDER,
    variables: { orderDepth: 1 }
  })

  client.writeQuery({
    query: GET_LATEST_ORDER,
    variables: { orderDepth: 1 },
    data: produce(queryResults, draft => {
      draft.orders[0].items.push(createItem)
    })
  })
}
</code>```

})

I am unable to get

```<code>  const { loading, data, refetch } = useQuery(GET_LATEST_ORDER, {
variables: { orderDepth: 1 }
</code>```

})

to show updated data after the mutation.

The apollo cache is updated correctly.  But data on the useQuery does not change.

答:
The issue ended up being the returned object from the mutation was not exactly the same.  It was missing an @client field.

While obvious in hindsight no where I searched described this as a reason except for a comment I saw mentioning perhaps missing the __typename.
This would have been obvious had apollo thrown an error.  However, no error was thrown, nor existed on the useQuery.

Body:
Using this mutation:

import produce from 'immer

const [createItem] = useMutation(CREATE_ITEM, {
update (client, { data: { createItem } }) {
  const queryResults = client.readQuery({
    query: GET_LATEST_ORDER,
    variables: { orderDepth: 1 }
  })

  client.writeQuery({
    query: GET_LATEST_ORDER,
    variables: { orderDepth: 1 },
    data: produce(queryResults, draft => {
      draft.orders[0].items.push(createItem)
    })
  })
}

})

I am unable to get

  const { loading, data, refetch } = useQuery(GET_LATEST_ORDER, {
variables: { orderDepth: 1 }

})

to show updated data after the mutation.

The apollo cache is updated correctly.  But data on the useQuery does not change.


问:
HTML Bootstrap Carousel (carousel-control)
About the issue that currently facing is that for Bootstrap Carousel (from w3school) , there is a problem for carousel-control.

Problem that i am facing is that when i have enter hyperlink for the image , the carousel-control are larger then the image itself (screenshot below).

Screenshot: https://prnt.sc/r4wh2f

Codes for my bootstrap carousel

```<code><div class="row">
<div class="col-12 col-md-12 banner-section">
<div class="container">
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
      <div class="item active">
                <a href="facebook.com"><picture>
            <source media="(max-width: 900px)" srcset="image/banner01small.jpg">
            <img src="image/banner01" alt="banner" style="z-index:1" class="img-fluid">
        </picture></a>
      </div>

      <div class="item">
                <a href="instagram.com"><picture>
            <source media="(max-width: 900px)" srcset="image/banner02small.jpg">
            <img src="image/banner02" alt="banner" style="z-index:1" class="img-fluid">
        </picture></a>
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>
</div>
</div>
</code>```

答:
Hope this help you. Demo

Just Added CSS below mentioned code

```<code>a.carousel-control {
    width: 30px;
    height: 30px;
    top: 47%;
}
</code>```

Body:
About the issue that currently facing is that for Bootstrap Carousel (from w3school) , there is a problem for carousel-control.

Problem that i am facing is that when i have enter hyperlink for the image , the carousel-control are larger then the image itself (screenshot below).

Screenshot: https://prnt.sc/r4wh2f

Codes for my bootstrap carousel

                <picture>
            <source media="(max-width: 900px)" srcset="image/banner01small.jpg">

        </picture>

                <picture>
            <source media="(max-width: 900px)" srcset="image/banner02small.jpg">

        </picture>

      Previous

      Next

Body:
Hope this help you. Demo

Just Added CSS below mentioned code

a.carousel-control {
    width: 30px;
    height: 30px;
    top: 47%;
}


问:
ddev Xdebug and step debugging not working with PhpStorm
I'm new to ddev, but not new to Ansible, Vagrant, etc, or setting up Xdebug, and I can't for the life of me get step debugging to work with PhpStorm and ddev. I've tried changing ports and did all the steps in this thread How do I get xdebug/step-debugging working with ddev? to no avail. What am I missing?

Here are my settings:

```<code>APIVersion: v1.13.0
name: ee-dev-clean
type: php
docroot: ""
php_version: "7.3"
webserver_type: nginx-fpm
router_http_port: "80"
router_https_port: "443"
xdebug_enabled: true
additional_hostnames: []
additional_fqdns: []
nfs_mount_enabled: false
provider: default
use_dns_when_possible: true
timezone: ""
</code>```

I'm setting my own 20-xdebug.ini file which is 100% accepted and showing correct values when I run phpinfo(). These are basically the same settings that do work in other Ansible/Vagrant based machines that I have running locally (all of them have been suspended while testing ddev).

```<code>[XDebug]
zend_extension=xdebug.so
; zend_extension="/usr/lib/php/20190902/xdebug.so"
xdebug.remote_host=host.docker.internal
xdebug.remote_enable=1
xdebug.remote_connect_back=1
xdebug.show_exception_trace=0
; xdebug.remote_port=11011
xdebug.idekey=PHPSTORM
xdebug.remote_log="/var/log/xdebug.log"
</code>```

The xdebug.log file has the following output after making a request and attempting to pick up a break point. I also have "stop at first line" enabled.

```<code>[1038] I: Remote address found, connecting to 172.18.0.1:9000.
[1037] I: Remote address found, connecting to 172.18.0.1:9000.
[1037] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1038] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1037] E: Could not connect to client. :-(
[1037] Log closed at 2020-02-19 19:56:05

[1038] E: Could not connect to client. :-(
[1038] Log closed at 2020-02-19 19:56:05

[1057] Log opened at 2020-02-19 19:56:50
[1057] I: Checking remote connect back address.
[1057] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[1057] I: Remote address found, connecting to 172.18.0.1:9000.
[1057] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1057] E: Could not connect to client. :-(
[1057] Log closed at 2020-02-19 19:56:50

[1037] Log opened at 2020-02-19 19:56:51
[1037] I: Checking remote connect back address.
[1037] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[1037] I: Remote address found, connecting to 172.18.0.1:9000.
[1038] Log opened at 2020-02-19 19:56:51
[1038] I: Checking remote connect back address.
[1038] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[1038] I: Remote address found, connecting to 172.18.0.1:9000.
[1037] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1038] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1037] E: Could not connect to client. :-(
[1037] Log closed at 2020-02-19 19:56:51

[1038] E: Could not connect to client. :-(
[1038] Log closed at 2020-02-19 19:56:51
</code>```

答:
Ok, it was the port. I had to set it up to use port 11011 instead of 9000. Removed the 20-xdebug.ini entire override and added an xdebug-port.ini file with just the following:

```<code>[XDebug]
xdebug.remote_port=11011
</code>```

Then changed the project settings in PhpStorm:

Also added the following server settings (though PhpStorm figured this out for me when it saw the incoming connection:

Body:
I'm new to ddev, but not new to Ansible, Vagrant, etc, or setting up Xdebug, and I can't for the life of me get step debugging to work with PhpStorm and ddev. I've tried changing ports and did all the steps in this thread How do I get xdebug/step-debugging working with ddev? to no avail. What am I missing?

Here are my settings:

APIVersion: v1.13.0
name: ee-dev-clean
type: php
docroot: ""
php_version: "7.3"
webserver_type: nginx-fpm
router_http_port: "80"
router_https_port: "443"
xdebug_enabled: true
additional_hostnames: []
additional_fqdns: []
nfs_mount_enabled: false
provider: default
use_dns_when_possible: true
timezone: ""

I'm setting my own 20-xdebug.ini file which is 100% accepted and showing correct values when I run phpinfo(). These are basically the same settings that do work in other Ansible/Vagrant based machines that I have running locally (all of them have been suspended while testing ddev).

[XDebug]
zend_extension=xdebug.so
; zend_extension="/usr/lib/php/20190902/xdebug.so"
xdebug.remote_host=host.docker.internal
xdebug.remote_enable=1
xdebug.remote_connect_back=1
xdebug.show_exception_trace=0
; xdebug.remote_port=11011
xdebug.idekey=PHPSTORM
xdebug.remote_log="/var/log/xdebug.log"

The xdebug.log file has the following output after making a request and attempting to pick up a break point. I also have "stop at first line" enabled.

[1038] I: Remote address found, connecting to 172.18.0.1:9000.
[1037] I: Remote address found, connecting to 172.18.0.1:9000.
[1037] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1038] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1037] E: Could not connect to client. :-(
[1037] Log closed at 2020-02-19 19:56:05

[1038] E: Could not connect to client. :-(
[1038] Log closed at 2020-02-19 19:56:05

[1057] Log opened at 2020-02-19 19:56:50
[1057] I: Checking remote connect back address.
[1057] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[1057] I: Remote address found, connecting to 172.18.0.1:9000.
[1057] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1057] E: Could not connect to client. :-(
[1057] Log closed at 2020-02-19 19:56:50

[1037] Log opened at 2020-02-19 19:56:51
[1037] I: Checking remote connect back address.
[1037] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[1037] I: Remote address found, connecting to 172.18.0.1:9000.
[1038] Log opened at 2020-02-19 19:56:51
[1038] I: Checking remote connect back address.
[1038] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[1038] I: Remote address found, connecting to 172.18.0.1:9000.
[1037] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1038] W: Creating socket for '172.18.0.1:9000', poll success, but error: Operation now in progress (29).
[1037] E: Could not connect to client. :-(
[1037] Log closed at 2020-02-19 19:56:51

[1038] E: Could not connect to client. :-(
[1038] Log closed at 2020-02-19 19:56:51

Body:
Ok, it was the port. I had to set it up to use port 11011 instead of 9000. Removed the 20-xdebug.ini entire override and added an xdebug-port.ini file with just the following:

[XDebug]
xdebug.remote_port=11011

Then changed the project settings in PhpStorm:

Also added the following server settings (though PhpStorm figured this out for me when it saw the incoming connection:


问:
Retrieve Value From DropdownList into controller
I am currently trying to populate a dropdownlist(or asp-net select, doesn't really matter, whichever works) so that I can grab whatever value they had selected, and do some manipulation in the controller.

The issue comes in to play when it comes to defining these values. These values can be hard coded because it's not pulling from anything and they will remain the same. However, I also need to reference these values via a model so I can do something like this

```<code>public IActionResult Example(ModelName model) {
var selectedValue = model.Id // Or model.Name

Do manipulation here...
}
</code>```

So the bottom line question is, where do I define these values, and how do I send the selected values back to a model so I can manipulate them in the controller.

答:
Here is a working demo like below:

1.Model:

```<code>public class TestModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Select Select { get; set; }
}
public class Select
{
    public int SelectId { get; set; }
    public string Name { get; set; }
}
</code>```

2.View:

```<code>@model TestModel
<div class="row">
    <div class="col-md-4">
        <form asp-action="Example">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Select.Name" class="control-label"></label>
                <select asp-for="Select.SelectId" asp-items="ViewBag.SList"></select>
                <span asp-validation-for="Select.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
</code>```

3.Controller:

```<code>public class HomeController : Controller
{
    public IActionResult Index()
    {
        List<Select> selectList = new List<Select>()
        {
            new Select(){  SelectId=1, Name="aaa"},
            new Select(){  SelectId=2, Name="bbb"},
            new Select(){  SelectId=3, Name="ccc"},
            new Select(){  SelectId=4, Name="ddd"},
        };
        ViewBag.SList = new SelectList(selectList, "SelectId", "Name");
        return View();
    }
    [HttpPost]
    public IActionResult Example(TestModel model)
    {
        var selectedValue = model.Select.SelectId;// Or model.Name
        //do your stuff...
    }
</code>```

Result:

Body:
I am currently trying to populate a dropdownlist(or asp-net select, doesn't really matter, whichever works) so that I can grab whatever value they had selected, and do some manipulation in the controller.

The issue comes in to play when it comes to defining these values. These values can be hard coded because it's not pulling from anything and they will remain the same. However, I also need to reference these values via a model so I can do something like this

public IActionResult Example(ModelName model) {
var selectedValue = model.Id // Or model.Name

Do manipulation here...
}

So the bottom line question is, where do I define these values, and how do I send the selected values back to a model so I can manipulate them in the controller.

Body:
Here is a working demo like below:

1.Model:

public class TestModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Select Select { get; set; }
}
public class Select
{
    public int SelectId { get; set; }
    public string Name { get; set; }
}

2.View:

@model TestModel
<div class="row">
    <div class="col-md-4">
        <form asp-action="Example">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Select.Name" class="control-label"></label>
                <select asp-for="Select.SelectId" asp-items="ViewBag.SList"></select>
                <span asp-validation-for="Select.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

3.Controller:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        List<Select> selectList = new List<Select>()
        {
            new Select(){  SelectId=1, Name="aaa"},
            new Select(){  SelectId=2, Name="bbb"},
            new Select(){  SelectId=3, Name="ccc"},
            new Select(){  SelectId=4, Name="ddd"},
        };
        ViewBag.SList = new SelectList(selectList, "SelectId", "Name");
        return View();
    }
    [HttpPost]
    public IActionResult Example(TestModel model)
    {
        var selectedValue = model.Select.SelectId;// Or model.Name
        //do your stuff...
    }

Result:


问:
Using the Consolibyte PHP SDK for QuickBooks, what is the correct syntax for a Query?
I've looked all over and cannot find this. What is the qbXML to query a customer (or invoice, or payment, or whatever) using the ListID? I'm currently sending something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
    <QBXMLMsgsRq onError="stopOnError">
        <CustomerQueryRq requestID="' + $requestID + '">
            <ListID>' + $qbDesktopID + '</ListID>
        </CustomerQueryRq>
    </QBXMLMsgsRq>
</QBXML>
</code>```

Where that qbDesktopID looks like 80000000-1234567890, and I'm receiving a somewhat generic error that says my XML isn't properly formatted.

答:
There are a few really important things to note here:

For troubleshooting, it's important that you look at the actual qbXML you're sending vs. your code. What does the actual qbXML you're sending to QuickBooks look like? You can find this in the quickbooks_log SQL table, and also in the Web Connector log (if you set it to VERBOSE logging).

Invoices and payments don't have ListID values, so be aware those queries will be different (they have TxnID values instead).

Anytime you get an error message, it's important that you post the actual error message. QuickBooks produces literally thousands of different error messages, so without knowing specifically what error you're getting it's really hard to assist you.

Anytime you get an error related to qbXML syntax, your first stop should be the XML Validator tool included with the QuickBooks SDK. It will literally tell you exactly which line and character is incorrect.

With all that said... I suspect that you're not actually sending what you think you're sending.

The PHP concatenation operator for strings is not +. It's .: https://www.php.net/manual/en/language.operators.string.php

Assuming what you posted above is a snippet of PHP, it evaluates to an empty string or possibly an integer (if $requestID is an integer) and not a valid XML string.

Are you sure you didn't mean:

```<code>$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
    <QBXMLMsgsRq onError="stopOnError">
        <CustomerQueryRq requestID="' . $requestID . '">
            <ListID>' . $qbDesktopID . '</ListID>
        </CustomerQueryRq>
    </QBXMLMsgsRq>
</QBXML>';
</code>```

(note the . instead of + for concatenation)

Body:
I've looked all over and cannot find this. What is the qbXML to query a customer (or invoice, or payment, or whatever) using the ListID? I'm currently sending something like this:

<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
    <QBXMLMsgsRq onError="stopOnError">
        <CustomerQueryRq requestID="' + $requestID + '">
            <ListID>' + $qbDesktopID + '</ListID>
        </CustomerQueryRq>
    </QBXMLMsgsRq>
</QBXML>

Where that qbDesktopID looks like 80000000-1234567890, and I'm receiving a somewhat generic error that says my XML isn't properly formatted.

Body:
There are a few really important things to note here:

For troubleshooting, it's important that you look at the actual qbXML you're sending vs. your code. What does the actual qbXML you're sending to QuickBooks look like? You can find this in the quickbooks_log SQL table, and also in the Web Connector log (if you set it to VERBOSE logging).

Invoices and payments don't have ListID values, so be aware those queries will be different (they have TxnID values instead).

Anytime you get an error message, it's important that you post the actual error message. QuickBooks produces literally thousands of different error messages, so without knowing specifically what error you're getting it's really hard to assist you.

Anytime you get an error related to qbXML syntax, your first stop should be the XML Validator tool included with the QuickBooks SDK. It will literally tell you exactly which line and character is incorrect.

With all that said... I suspect that you're not actually sending what you think you're sending.

The PHP concatenation operator for strings is not +. It's .: https://www.php.net/manual/en/language.operators.string.php

Assuming what you posted above is a snippet of PHP, it evaluates to an empty string or possibly an integer (if $requestID is an integer) and not a valid XML string.

Are you sure you didn't mean:

$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
    <QBXMLMsgsRq onError="stopOnError">
        <CustomerQueryRq requestID="' . $requestID . '">
            <ListID>' . $qbDesktopID . '</ListID>
        </CustomerQueryRq>
    </QBXMLMsgsRq>
</QBXML>';

(note the . instead of + for concatenation)


问:
Pass variables between step definitions in Cucumber groovy
I am wondering how we can pass variables between two step definitions files.

I found this How to share variables across multiple cucumber step definition files with groovy but their structure is different from mine, because I am not using classes in step definition.

The following is my two step definition files.

Feature File 1

```<code>Scenario: Consumer registration
    When I try to register with my details with "memberNo" mem no.
    Then I should be able to get success response
</code>```

stepDef1

```<code>When(~'^I try to register with my details with "([^"]*)" mem no.$') { String memdNo ->
   sMemdNo  = memNo + getRanNo()
   // more code here
}
</code>```

Feature File 2

```<code>Scenario: Event Generation
    When I activate my account
    Then I can see the file having "logName" event
</code>```

stepDef2

```<code>Then(~'^I can see the file having "([^"]*)" event$') { String logName ->
   eventFile = GetLogtData(logName , sMemdNo )
   // more code here
}
</code>```

So, as per the above I want to get the value of sMemdNo from stepDef1 and use it in stepDef2.

答:
To use variables between steps you can add the variable at the top of the steps file (groovy or java), and the variable used in one step will have the value available for other variable.
Example

Result

Body:
I am wondering how we can pass variables between two step definitions files.

I found this How to share variables across multiple cucumber step definition files with groovy but their structure is different from mine, because I am not using classes in step definition.

The following is my two step definition files.

Feature File 1

Scenario: Consumer registration
    When I try to register with my details with "memberNo" mem no.
    Then I should be able to get success response

stepDef1

When(~'^I try to register with my details with "([^"]*)" mem no.$') { String memdNo ->
   sMemdNo  = memNo + getRanNo()
   // more code here
}

Feature File 2

Scenario: Event Generation
    When I activate my account
    Then I can see the file having "logName" event

stepDef2

Then(~'^I can see the file having "([^"]*)" event$') { String logName ->
   eventFile = GetLogtData(logName , sMemdNo )
   // more code here
}

So, as per the above I want to get the value of sMemdNo from stepDef1 and use it in stepDef2.


问:
Implement get/set methods for Identity User custom property
I am using Identity and have extended the base IdentityUser with three custom properties.  Using .netCore 3.1.1 and identity 4

```<code>namespace FleetLogix.Intranet.Identity
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser<int>
    {
        [MaxLength(50)]
        [PersonalData]
        public string FirstName { get; set; }

        [MaxLength(50)]
        [PersonalData]
        public string LastName { get; set; }

        [MaxLength(5)]
        public string OrgCode { get; set; }

        public ApplicationUser() : base()
        {

        }

    }
}
</code>```

These were happily created in the [AspNetUsers] table.  4 initial users have been created, with all additional properties filled.

I have also created some extensions that let me get the values of these properties.  FirstName -> GivenName, LastName -> Surname and OrgCode is a CustomClaimTypes.OrgCode

```<code>namespace FleetLogix.Intranet.Identity
{
    /// <summary>
    /// Extends the <see cref="System.Security.Principal.IIdentity" /> object to add accessors for our custom properties.
    /// </summary>
    public static class IdentityExtensions
    {
        /// <summary>
        /// Gets the value of the custom user property FirstName
        /// </summary>
        /// <example>
        /// User.Identity.GetFirstName()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of LastName or an empty string</returns>
        public static string GetFirstName(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(ClaimTypes.GivenName);

            return claim?.Value ?? string.Empty;
        }

        /// <summary>
        /// Gets the value of the custom user property LastName
        /// </summary>
        /// <example>
        /// User.Identity.GetLastName()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of LastName or an empty string</returns>
        public static string GetLastName(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(ClaimTypes.Surname);

            return claim?.Value ?? string.Empty;
        }

        /// <summary>
        /// Gets the value of the custom user property OrgCode
        /// </summary>
        /// <example>
        /// User.Identity.GetOrgCode()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of OrgCode or an empty string</returns>
        public static string GetOrgCode(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(CustomClaimTypes.OrgCode);

            return claim?.Value ?? string.Empty;
        }
    }
}
</code>```

I am setting up a new site and want to modify _LoginPartial.cshtml.  I want to replace the display of the logged in username(an email address) with the logged in FirstName

```<code>@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
    <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
    </li>
   ...
}
</code>```

to this

```<code>@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
    <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.GetFirstName()!</a>
    </li>
   ...
}
</code>```

however, this results in empty text.  Why is this blank?

Clicking through into the Account/Manage/Index page I am presented with a form for modifying user details.  I have modified the InputModel to include two of the custom properties (FirstName, LastName).  The LoadAsync task has been modified to load values (using the extension methods) and add them to an `InputModel

```<code>private async Task LoadAsync(ApplicationUser user)
{

    var userName = await _userManager.GetUserNameAsync(user);
    var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
    var firstName =  user.FirstName;
    var lastName = user.LastName;
    var orgCode = user.OrgCode;

    Username = userName;

    OrgCode = orgCode;

    Input = new InputModel
    {
        PhoneNumber = phoneNumber,
        FirstName = firstName,
        LastName = lastName

    };
}
</code>```

Why are the custom properties visible on this page, but not on the previous?

Further in Account/Manage/Index is the update method OnPostAsync()

```<code>public async Task<IActionResult> OnPostAsync()
{
   var user = await _userManager.GetUserAsync(User);
   if (user == null)
   {
       return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
   }

   if (!ModelState.IsValid)
   {
       await LoadAsync(user);
       return Page();
   }

   var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
   if (Input.PhoneNumber != phoneNumber)
   {
       var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
       if (!setPhoneResult.Succeeded)
       {
           var userId = await _userManager.GetUserIdAsync(user);
           throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
       }
   }

   var firstName = user.FirstName; //.GetPhoneNumberAsync(user);
   if (Input.FirstName != firstName)
   {
       //var setFirstNameResult = await _userManager.SetFirstNameAsync(user, Input.FirstName);
       user.FirstName = Input.FirstName;
       //if (!setFirstNameResult.Succeeded)
       //{
       //    var userId = await _userManager.GetUserIdAsync(user);
       //    throw new InvalidOperationException($"Unexpected error occurred setting First Name for user with ID '{userId}'.");
       //}
   }

   var lastName = user.LastName;
   if (Input.LastName != lastName)
   {
       //var setLastNameResult = await _userManager.SetLastNameAsync(user, Input.LastName);
       user.LastName = Input.LastName;
       //if (!setLastNameResult.Succeeded)
       //{
       //    var userId = await _userManager.GetUserIdAsync(user);
       //    throw new InvalidOperationException($"Unexpected error occurred setting Last Name for user with ID '{userId}'.");
       //}
   }

   await _signInManager.RefreshSignInAsync(user);
   StatusMessage = "Your profile has been updated";
   return RedirectToPage();
}
</code>```

Without Set methods like SetPhoneNumberAsync() I tried using the property setter.  This didn't work.  How do I update Identity User Custom Property values?

I just want to be able to use custom User properties.  I need the FirstName & OrgCode property available as soon as they log in, which isn't currently the case.  The current extension methods don't always work.

In addition, I need to be able to edit these properties in case their are errors or changed requirements.

答:
You need to create scope of identity, just create your identity and add scoped

```<code>services.AddScoped<IUserIdentity, UserIdentity>();
</code>```

You need to implement middleware for map all your properties in identity.
Add to startup:

```<code>app.UseMiddleware<UserIdentityAccessor>();
</code>```

Implementation:

```<code>    public class UserIdentityAccessor
    {
        private readonly RequestDelegate _next;

        public UserIdentityAccessor(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, IUserIdentity userIdentity)
        {
            var user = (ClaimsIdentity) context.User.Identity;

            if (user.IsAuthenticated)
            {
                var first = user.FindFirst(ClaimsName.FirstName).Value; \\ get info from claims
                userIdentity.FirstName = first;                         \\ and add to identity
            }
            else
            {
                userIdentity.FirstName = null;
            }

            await _next(context);
        }
    }
</code>```

And now you can get identity wherever you want

Body:
I am using Identity and have extended the base IdentityUser with three custom properties.  Using .netCore 3.1.1 and identity 4

namespace FleetLogix.Intranet.Identity
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser<int>
    {
        [MaxLength(50)]
        [PersonalData]
        public string FirstName { get; set; }

        [MaxLength(50)]
        [PersonalData]
        public string LastName { get; set; }

        [MaxLength(5)]
        public string OrgCode { get; set; }

        public ApplicationUser() : base()
        {

        }

    }
}

These were happily created in the [AspNetUsers] table.  4 initial users have been created, with all additional properties filled.

I have also created some extensions that let me get the values of these properties.  FirstName -> GivenName, LastName -> Surname and OrgCode is a CustomClaimTypes.OrgCode

namespace FleetLogix.Intranet.Identity
{
    ///
    /// Extends the <see cref="System.Security.Principal.IIdentity" /> object to add accessors for our custom properties.
    ///
    public static class IdentityExtensions
    {
        ///
        /// Gets the value of the custom user property FirstName
        ///
        /// <example>
        /// User.Identity.GetFirstName()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of LastName or an empty string</returns>
        public static string GetFirstName(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(ClaimTypes.GivenName);

            return claim?.Value ?? string.Empty;
        }

        ///
        /// Gets the value of the custom user property LastName
        ///
        /// <example>
        /// User.Identity.GetLastName()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of LastName or an empty string</returns>
        public static string GetLastName(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(ClaimTypes.Surname);

            return claim?.Value ?? string.Empty;
        }

        ///
        /// Gets the value of the custom user property OrgCode
        ///
        /// <example>
        /// User.Identity.GetOrgCode()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of OrgCode or an empty string</returns>
        public static string GetOrgCode(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(CustomClaimTypes.OrgCode);

            return claim?.Value ?? string.Empty;
        }
    }
}

I am setting up a new site and want to modify _LoginPartial.cshtml.  I want to replace the display of the logged in username(an email address) with the logged in FirstName

@if (SignInManager.IsSignedIn(User))
{

    Hello @UserManager.GetUserName(User)!

   ...
}

to this

@if (SignInManager.IsSignedIn(User))
{

    Hello @User.Identity.GetFirstName()!

   ...
}

however, this results in empty text.  Why is this blank?

Clicking through into the Account/Manage/Index page I am presented with a form for modifying user details.  I have modified the InputModel to include two of the custom properties (FirstName, LastName).  The LoadAsync task has been modified to load values (using the extension methods) and add them to an `InputModel

private async Task LoadAsync(ApplicationUser user)
{

    var userName = await _userManager.GetUserNameAsync(user);
    var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
    var firstName =  user.FirstName;
    var lastName = user.LastName;
    var orgCode = user.OrgCode;

    Username = userName;

    OrgCode = orgCode;

    Input = new InputModel
    {
        PhoneNumber = phoneNumber,
        FirstName = firstName,
        LastName = lastName

    };
}

Why are the custom properties visible on this page, but not on the previous?

Further in Account/Manage/Index is the update method OnPostAsync()

public async Task<IActionResult> OnPostAsync()
{
   var user = await _userManager.GetUserAsync(User);
   if (user == null)
   {
       return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
   }

   if (!ModelState.IsValid)
   {
       await LoadAsync(user);
       return Page();
   }

   var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
   if (Input.PhoneNumber != phoneNumber)
   {
       var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
       if (!setPhoneResult.Succeeded)
       {
           var userId = await _userManager.GetUserIdAsync(user);
           throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
       }
   }

   var firstName = user.FirstName; //.GetPhoneNumberAsync(user);
   if (Input.FirstName != firstName)
   {
       //var setFirstNameResult = await _userManager.SetFirstNameAsync(user, Input.FirstName);
       user.FirstName = Input.FirstName;
       //if (!setFirstNameResult.Succeeded)
       //{
       //    var userId = await _userManager.GetUserIdAsync(user);
       //    throw new InvalidOperationException($"Unexpected error occurred setting First Name for user with ID '{userId}'.");
       //}
   }

   var lastName = user.LastName;
   if (Input.LastName != lastName)
   {
       //var setLastNameResult = await _userManager.SetLastNameAsync(user, Input.LastName);
       user.LastName = Input.LastName;
       //if (!setLastNameResult.Succeeded)
       //{
       //    var userId = await _userManager.GetUserIdAsync(user);
       //    throw new InvalidOperationException($"Unexpected error occurred setting Last Name for user with ID '{userId}'.");
       //}
   }

   await _signInManager.RefreshSignInAsync(user);
   StatusMessage = "Your profile has been updated";
   return RedirectToPage();
}

Without Set methods like SetPhoneNumberAsync() I tried using the property setter.  This didn't work.  How do I update Identity User Custom Property values?

I just want to be able to use custom User properties.  I need the FirstName & OrgCode property available as soon as they log in, which isn't currently the case.  The current extension methods don't always work.

In addition, I need to be able to edit these properties in case their are errors or changed requirements.

Body:
You need to create scope of identity, just create your identity and add scoped

services.AddScoped<IUserIdentity, UserIdentity>();

You need to implement middleware for map all your properties in identity.
Add to startup:

app.UseMiddleware<UserIdentityAccessor>();

Implementation:

    public class UserIdentityAccessor
    {
        private readonly RequestDelegate _next;

        public UserIdentityAccessor(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, IUserIdentity userIdentity)
        {
            var user = (ClaimsIdentity) context.User.Identity;

            if (user.IsAuthenticated)
            {
                var first = user.FindFirst(ClaimsName.FirstName).Value; \\ get info from claims
                userIdentity.FirstName = first;                         \\ and add to identity
            }
            else
            {
                userIdentity.FirstName = null;
            }

            await _next(context);
        }
    }

And now you can get identity wherever you want


问:
JavaScript nested for loop change tags
I want to change that texts
why strong tags text not replace with small tags text.

var small = $("small");
var strong = $("strong");
var x, i;
for (x = 0; x < small.length; x++) {
  for (i = 0; i < strong.length; i++) {
    strong.text(small.text());
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<small>small1</small>
<small>small2</small>
<strong>strong1</strong>
<strong>strong2</strong></code>```

答:
If you want to be copying text between corresponding elements, you shouldn't use nested loops. Just use one loop, and use the index to access the other element.

var small = $("small");
var strong = $("strong");
small.each(function(i) {
  strong.eq(i).text($(this).text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<small>small1</small>
<small>small2</small>
<strong>strong1</strong>
<strong>strong2</strong></code>```

Title: JavaScript nested for loop change tags

Body:
I want to change that texts
why strong tags text not replace with small tags text.

var small = $("small");
var strong = $("strong");
var x, i;
for (x = 0; x < small.length; x++) {
  for (i = 0; i < strong.length; i++) {
    strong.text(small.text());
  }
}

small1
small2
strong1
strong2

Body:
If you want to be copying text between corresponding elements, you shouldn't use nested loops. Just use one loop, and use the index to access the other element.

var small = $("small");
var strong = $("strong");
small.each(function(i) {
  strong.eq(i).text($(this).text());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<small>small1</small>
<small>small2</small>
<strong>strong1</strong>
<strong>strong2</strong>


问:
Electron with Vue disable auto reload
I install Electron with Vue using this tutorial.

I looking for answer how I can disable auto reload ?
I start my application using npm run dev, when I change somethink in code Electron run auto reload (refreshes and compiles the application again
). I would like to refresh the application myself after writing a part of the code.
I don't use Webpack.

Yes, I know I can disable auto save in Visual Studio Code, but this is not a solution.

答:
Disable on Main and Renderer processes

Remove the call of startElectron() in dev-runner.js > startMain().

```<code>function startMain () {
  return new Promise((resolve, reject) => {
    mainConfig.entry.main = [path.join(__dirname, '../src/main/index.dev.js')].concat(mainConfig.entry.main)
    mainConfig.mode = 'development'
    const compiler = webpack(mainConfig)

    compiler.hooks.watchRun.tapAsync('watch-run', (compilation, done) => {
      //Remove these lines and ...
      // logStats('Main', chalk.white.bold('compiling...'))
      // hotMiddleware.publish({ action: 'compiling' })
      done()
    })

    compiler.watch({}, (err, stats) => {
      if (err) {
        console.log(err)
        return
      }

      //... these lines.
      // logStats('Main', stats)
      //
      // if (electronProcess && electronProcess.kill) {
      //   manualRestart = true
      //   process.kill(electronProcess.pid)
      //   electronProcess = null
      //   startElectron()
      //
      //   setTimeout(() => {
      //     manualRestart = false
      //   }, 5000)
      // }

      resolve()
    })
  })
}
</code>```

Disable only on Renderer process

Delete import line below from src/main/index.js.

```<code>import '../renderer/store';
</code>```

This line is required by vuex-electron which makes vuex to run on main process. If you are not planning to use createPersistedState() or createSharedMutations(), you can delete this.

Title: Electron with Vue disable auto reload

Body:
Disable on Main and Renderer processes

Remove the call of startElectron() in dev-runner.js > startMain().

function startMain () {
  return new Promise((resolve, reject) => {
    mainConfig.entry.main = [path.join(__dirname, '../src/main/index.dev.js')].concat(mainConfig.entry.main)
    mainConfig.mode = 'development'
    const compiler = webpack(mainConfig)

    compiler.hooks.watchRun.tapAsync('watch-run', (compilation, done) => {
      //Remove these lines and ...
      // logStats('Main', chalk.white.bold('compiling...'))
      // hotMiddleware.publish({ action: 'compiling' })
      done()
    })

    compiler.watch({}, (err, stats) => {
      if (err) {
        console.log(err)
        return
      }

      //... these lines.
      // logStats('Main', stats)
      //
      // if (electronProcess && electronProcess.kill) {
      //   manualRestart = true
      //   process.kill(electronProcess.pid)
      //   electronProcess = null
      //   startElectron()
      //
      //   setTimeout(() => {
      //     manualRestart = false
      //   }, 5000)
      // }

      resolve()
    })
  })
}

Disable only on Renderer process

Delete import line below from src/main/index.js.

import '../renderer/store';

This line is required by vuex-electron which makes vuex to run on main process. If you are not planning to use createPersistedState() or createSharedMutations(), you can delete this.


问:
IE11 doesn't accept font-weights that aren't multiples of 100
I have an app that takes in font weights such as 380 and 350 for branding purposes and these fonts work perfectly fine in Chrome and Firefox. However, when I go onto IE11, the font weights are much more bolded, seemingly adopting the font weights of other text that uses a font weight that is a multiple of 100. I went into the console and changed these font weights to 400 and it does change to a lighter text but is there any way I could get it to be exactly 350/380? I couldn't find anything useful online about this. </p>

答:
I have created a sample using the font-weight with different value, it seems that this is the IE browser default behavior, the font weight in IE browser is a little bolder than Chrome or Edge browser's font weight. The screenshot like this.

The font-weight value is defined discretely (using the whole multiple of 100). The value is real, and the value of an integer multiple that is not 100 is rounded to the full multiple of 100, and when you encounter a full multiple of 100, you will convert up, such as 150, to 200.

So, in my opinion, I suggest you directly change the font-weight value to 400 (You could also check previous screenshot, it seems that after rendering, they are similar).