问:
Powershell setting EnvironmentVariable works in ISE but not Console
I have an odd Powershell behavior i wish to understand.

If i set a permanent Environment Variable and start a process like the following

```<code>[Environment]::SetEnvironmentVariable('FOO','BAR','User')
Start-Process notepad
</code>```

This works as expected in ISE Editor and if i type it after one other in the Console. However if i run it as a .\script.ps1 Script from the Console the Start-Process will ignore the new or the changed Environment Variable. Even the Environment Variable is properly set before Start-Process is executed. I tested this by adding Sleep and checking the Environment Variable Dialogue manually. If the script is run a second time the Process will read the Environment Variable as expected since it has been changed before already.

Why is the Console behavior not the same as in ISE in this case?

I already tried if this has to do with specific Assemblies that are loaded in ISE and not the Console but it does not seam so.
I also tried to run as STA but it did not work either.

答:
Note: This answer is specific to Windows, because System.Environment.SetEnvironmentVariable only supports modifying persistent environment-variable definitions (via target scopes User and Machine) there. The fundamentals of how PowerShell determines a child process' environment apply on Unix-like platforms too, however.

[Environment]::SetEnvironmentVariable() with a target-scope System.EnvironmentVariableTarget argument of User or Machine only updates the persistent environment-variable definitions in the registry - it doesn't also update the current process's in-memory variables.

By contrast, target Process updates only the current process' variables non-persistently.

As such, [Environment]::SetEnvironmentVariable('FOO','BAR','Process') is the equivalent of $env:FOO = 'BAR'

Start-Process by default uses the current process's environment variables[1] and therefore doesn't see variables (yet) that were created or updated by targeting the User or Machine scopes in the same process.[2]

Start-Process's -UseNewEnvironment parameter is in principle designed to do what you want: it is meant to start the new process with environment-variable values read from the registry, ignoring the calling process' values - however, this feature is broken as of PowerShell [Core] v7.0 - see this GitHub issue.

The workaround is to also define the new variable in the current process:

```<code># Update both the registry and the current process.
foreach ($targetScope in 'User', 'Process') {
  [Environment]::SetEnvironmentVariable('FOO', 'BAR', $targetScope)
}

# Start a new process with the new value in effect.
Start-Process -NoNewWindow -Wait powershell '-c \"`$env:FOO is: $env:FOO\"'
</code>```

Note that - unlike what -UseNewEnvironment should do - this makes the new process inherit all process-only (in-memory) environment variables / values too.

[1] A process is given a block of environment variables on startup, often a copy of the parent process's block (as PowerShell itself does by default when creating child processes). That startup block may or may not reflect the then-current registry definitions. In-process modifications of the environment block are lost when the process terminates, unless they are explicitly persisted, such as with [Environment]::SetEnvironmentVariable()  and target scopes User or Machine. As all programs that modify the persistently defined environment variables should do, [Environment]::SetEnvironmentVariable() broadcasts Windows message WM_SETTINGCHANGE as a notification of the change, but few programs are designed to listen to it and therefore few update their in-process environment variables in response (which isn't appropriate for all programs).

[2] However, if you start the new process as an administrator with -Verb RunAs (Windows-only) using the current user's credentials, the new process will see the new/updated definitions, because it then does not use the current process' environment variables and instead reads the then-current definitions from the registry.

Body:
I have an odd Powershell behavior i wish to understand.

If i set a permanent Environment Variable and start a process like the following

[Environment]::SetEnvironmentVariable('FOO','BAR','User')
Start-Process notepad

This works as expected in ISE Editor and if i type it after one other in the Console. However if i run it as a .\script.ps1 Script from the Console the Start-Process will ignore the new or the changed Environment Variable. Even the Environment Variable is properly set before Start-Process is executed. I tested this by adding Sleep and checking the Environment Variable Dialogue manually. If the script is run a second time the Process will read the Environment Variable as expected since it has been changed before already.

Why is the Console behavior not the same as in ISE in this case?

I already tried if this has to do with specific Assemblies that are loaded in ISE and not the Console but it does not seam so.
I also tried to run as STA but it did not work either.

Body:
Note: This answer is specific to Windows, because System.Environment.SetEnvironmentVariable only supports modifying persistent environment-variable definitions (via target scopes User and Machine) there. The fundamentals of how PowerShell determines a child process' environment apply on Unix-like platforms too, however.

[Environment]::SetEnvironmentVariable() with a target-scope System.EnvironmentVariableTarget argument of User or Machine only updates the persistent environment-variable definitions in the registry - it doesn't also update the current process's in-memory variables.

By contrast, target Process updates only the current process' variables non-persistently.

As such, [Environment]::SetEnvironmentVariable('FOO','BAR','Process') is the equivalent of $env:FOO = 'BAR'

Start-Process by default uses the current process's environment variables[1] and therefore doesn't see variables (yet) that were created or updated by targeting the User or Machine scopes in the same process.[2]

Start-Process's -UseNewEnvironment parameter is in principle designed to do what you want: it is meant to start the new process with environment-variable values read from the registry, ignoring the calling process' values - however, this feature is broken as of PowerShell [Core] v7.0 - see this GitHub issue.

The workaround is to also define the new variable in the current process:

# Update both the registry and the current process.
foreach ($targetScope in 'User', 'Process') {
  [Environment]::SetEnvironmentVariable('FOO', 'BAR', $targetScope)
}

# Start a new process with the new value in effect.
Start-Process -NoNewWindow -Wait powershell '-c \"`$env:FOO is: $env:FOO\"'

Note that - unlike what -UseNewEnvironment should do - this makes the new process inherit all process-only (in-memory) environment variables / values too.

[1] A process is given a block of environment variables on startup, often a copy of the parent process's block (as PowerShell itself does by default when creating child processes). That startup block may or may not reflect the then-current registry definitions. In-process modifications of the environment block are lost when the process terminates, unless they are explicitly persisted, such as with [Environment]::SetEnvironmentVariable()  and target scopes User or Machine. As all programs that modify the persistently defined environment variables should do, [Environment]::SetEnvironmentVariable() broadcasts Windows message WM_SETTINGCHANGE as a notification of the change, but few programs are designed to listen to it and therefore few update their in-process environment variables in response (which isn't appropriate for all programs).

[2] However, if you start the new process as an administrator with -Verb RunAs (Windows-only) using the current user's credentials, the new process will see the new/updated definitions, because it then does not use the current process' environment variables and instead reads the then-current definitions from the registry.


来源: stackexchange

问:
Git commit opens blank text file, for what?
In all the Git tutorials I've read they say that you can do:

```<code>git init
git add .
git commit
</code>```

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

答:
When doing revision control, you should always explain what the changed you made are. Usually the first time you're have a comment such as "Initial Commit."

However in the long run you want to make a good comment for each commit. You will want something of the form:

Added experimental feature x.

X will increase the performance of
  feature Y in condition Z. Should you
  need X activate it with the -x or
  --feature-eks switches. This addresses feature request #1138.

OwnerDisplayName: Alex

LastEditorDisplayName: Baishampayan Ghose

ContentLicense: CC BY-SA 3.0

Body:
In all the Git tutorials I've read they say that you can do:

git init
git add .
git commit

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

OwnerDisplayName: Flame

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Flame


问:
Changing the AcceptButton depending on active control
I have a working WinForm that handles the search functionality in my customer database. It contains the following controls:

A textBox where you type your search string (A)

A "search" button (B)

A DataGridView (C) that returns the result of the search

An "OK" button (D) and a "Cancel" button (E)

What I am trying to accieve next is this:

When A is active the AcceptButton (enter) should be linked to B

When B or enter is pressed C should become active

When C is active the AcceptButton should be linked to D

I realise this is a somewhat big question so don't hesitate to answer just one of the bullet marks if you know the answer.

EDIT: I have solved the implementation of requirement 1 and 3 above, but I am still looking for an answer to the second one. To clarify, when the search is initiated (meaning i have pressed enter on the keyboard or the search button with the mouse) I want focus to shift to the first line in the DataGridView.

答:
When you get the text changed event for textBox set the AcceptButton to be "Search":

```<code>    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        this.AcceptButton = SearchButton;
    }
</code>```

There will probably want to be more code in here, checking the length of the string etc.

Then once you've done the search and filled in the DataGridView you can then set the AcceptButton to be "OK".

```<code>    private void dataGridView1_DataMemberChanged(object sender, EventArgs e)
    {
        this.AcceptButton = OKButton;
    }
</code>```

Though you probably wouldn't want to use this event.

"Cancel" is always the CancelButton.

EDIT: OK for part 2 you want the following code:

```<code>    private void SearchButton_Click(object sender, EventArgs e)
    {
        dataGridView1.Focus();
    }
</code>```

This will make it active as soon as the search button is pressed, but you probably want to do it when the DataGridView has been populated - just in case the search returned no results.

OwnerDisplayName: Sakkle

LastEditorDisplayName: Sakkle

Body:
When you get the text changed event for textBox set the AcceptButton to be "Search":

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        this.AcceptButton = SearchButton;
    }

There will probably want to be more code in here, checking the length of the string etc.

Then once you've done the search and filled in the DataGridView you can then set the AcceptButton to be "OK".

    private void dataGridView1_DataMemberChanged(object sender, EventArgs e)
    {
        this.AcceptButton = OKButton;
    }

Though you probably wouldn't want to use this event.

"Cancel" is always the CancelButton.

EDIT: OK for part 2 you want the following code:

    private void SearchButton_Click(object sender, EventArgs e)
    {
        dataGridView1.Focus();
    }

This will make it active as soon as the search button is pressed, but you probably want to do it when the DataGridView has been populated - just in case the search returned no results.

OwnerDisplayName: ChrisF

LastEditorDisplayName: ChrisF


问:
How to calculate a list of angles between two line vectors in a series of specimens in R?
I am doing work a geometric morphometric dataset of biological specimens with two dimensional Cartesian coordinates (i.e., landmarks). Part of my interest with this dataset is to produce a data frame of distances between important landmarks and angles between landmark vectors with homologous coordinates across all specimens for further comparison. Distances between points have not been a problem, but I have been running into problems when I have tried to calculate angles in each of my specimens.

I am trying to find a way to calculate the angle between line vectors representing the same angle on a series of specimens at once (the vectors describe a feature with biological significance that is present in all specimens across my dataset). The R package I use to manipulate the morphometric data outputs the landmarks as a three-dimensional object of class array() where rows are landmarks, columns are the dimensions of the coordinate, and the third dimension is the specimen. Here are the landmark coordinates for the three specimens in the sample data presented here.

```<code>, , Specimen1

         X         Y
1  -0.2411  0.060183
2  -0.0677 -0.029954
3   0.1147  0.012111
4   0.0085  0.000462

, , Specimen2

          X       Y
1  -0.22509  0.0764
2  -0.09437 -0.0202
3   0.09135 -0.0182
4   0.00367 -0.0045

, , Specimen3

         X        Y
1  -0.2223  0.06122
2  -0.1001 -0.02366
3   0.0553  0.00577
4  -0.0617 -0.01557
</code>```

Below is a readable array that replicates the data I get as output for the first three specimens.

```<code>data<-array(data=c(-0.2411,-0.0677,0.1147,0.0085,0.060183,-0.029954,0.012111,0.000462,-0.22509,-0.09437,0.09135,0.00367,0.0764,-0.0202,-0.0182,-0.0045,-0.2223,-0.1001,0.0553,-0.0617,0.06122,-0.02366,0.00577,-0.01557),c(4,2,3))
</code>```

I am interested in finding the angle formed by the lines between points 1 and 2 and points 3 and 4. To do this I calculate the vector of these two lines by subtracting the coordinates of one point from the other. When I do that I get a 2*N matrix for each vector where rows correspond to vectors in the X and Y axis and columns correspond to specimen.

I want to find the angle between these two vectors for specimen 1 (column 1 on both matrices), 2, 3, and so on. Ideally, I would like to get the output into a format where R reports the angle for each indivdual specimen, like so:

```<code>     Angle1
[,1] 146
[,2] 152
[,3] 135
</code>```

And then somehow add it into a data frame so it looks like this:

```<code>          Distance Angle1 Angle2
Specimen1 100      146    100
Specimen2 100      152    100
Specimen3 100      135    100
</code>```

The distances and values for Angle2 are just filler numbers to show the format I am trying to achieve.

I have tried using the angle() function in the mathlib package and the angle.calc() function in the Morpho package. Here is the code I used to calculate the angle using the angle() function.

```<code>vector1<-data[1,,]-data[2,,]
vector2<-data[3,,]-data[4,,]
angle(as.vector(vector1),as.vector(vector2),degree=TRUE)
</code>```

These functions will calculate what seems to be the accurate angle however they will only do it for the first specimen or a single specimen if otherwise specified, and do not produce a list of angles for all specimens. I have also checked previous questions on Stack Overflow but none of the answers given appear to be applicable to a dataset containing multiple specimens  with each column on both matrices representing a distinct specimen (and when I apply them at best they seem to have the same problem where they only return the angle for the first specimen). There are only three specimens here, I have a large number of specimens and multiple angles per specimen in the actual dataset and it is not possible to measure every angle individually for each specimen.

Is there any way to write a formula to produce a list containing the respective angle for each of these specimens?

答:
First off, it's a bit confusing to give a 2x3 matrix the name vector1. That aside, you can use matlib::angle to calculate angles.

```<code>library(matlib)
phi <- setNames(mapply(
    function(x1, x2) angle(x1, x2),
    as.data.frame(vector1), as.data.frame(vector2)),
    paste0("Specimen", 1:ncol(vector1)))
phi
#Specimen1 Specimen2 Specimen3
# 146.2674  152.4439  134.8753
</code>```

Explanation: Use mapply to simultaneously iterate over the columns of vector1 and vector2, which have been converted to data.frames. Use stack to convert the named vector into a data.frame:

```<code>stack(phi)
#    values       ind
#1 146.2674 Specimen1
#2 152.4439 Specimen2
#3 134.8753 Specimen3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am doing work a geometric morphometric dataset of biological specimens with two dimensional Cartesian coordinates (i.e., landmarks). Part of my interest with this dataset is to produce a data frame of distances between important landmarks and angles between landmark vectors with homologous coordinates across all specimens for further comparison. Distances between points have not been a problem, but I have been running into problems when I have tried to calculate angles in each of my specimens.

I am trying to find a way to calculate the angle between line vectors representing the same angle on a series of specimens at once (the vectors describe a feature with biological significance that is present in all specimens across my dataset). The R package I use to manipulate the morphometric data outputs the landmarks as a three-dimensional object of class array() where rows are landmarks, columns are the dimensions of the coordinate, and the third dimension is the specimen. Here are the landmark coordinates for the three specimens in the sample data presented here.

, , Specimen1

         X         Y
1  -0.2411  0.060183
2  -0.0677 -0.029954
3   0.1147  0.012111
4   0.0085  0.000462

, , Specimen2

          X       Y
1  -0.22509  0.0764
2  -0.09437 -0.0202
3   0.09135 -0.0182
4   0.00367 -0.0045

, , Specimen3

         X        Y
1  -0.2223  0.06122
2  -0.1001 -0.02366
3   0.0553  0.00577
4  -0.0617 -0.01557

Below is a readable array that replicates the data I get as output for the first three specimens.

data<-array(data=c(-0.2411,-0.0677,0.1147,0.0085,0.060183,-0.029954,0.012111,0.000462,-0.22509,-0.09437,0.09135,0.00367,0.0764,-0.0202,-0.0182,-0.0045,-0.2223,-0.1001,0.0553,-0.0617,0.06122,-0.02366,0.00577,-0.01557),c(4,2,3))

I am interested in finding the angle formed by the lines between points 1 and 2 and points 3 and 4. To do this I calculate the vector of these two lines by subtracting the coordinates of one point from the other. When I do that I get a 2*N matrix for each vector where rows correspond to vectors in the X and Y axis and columns correspond to specimen.

I want to find the angle between these two vectors for specimen 1 (column 1 on both matrices), 2, 3, and so on. Ideally, I would like to get the output into a format where R reports the angle for each indivdual specimen, like so:

     Angle1
[,1] 146
[,2] 152
[,3] 135

And then somehow add it into a data frame so it looks like this:

          Distance Angle1 Angle2
Specimen1 100      146    100
Specimen2 100      152    100
Specimen3 100      135    100

The distances and values for Angle2 are just filler numbers to show the format I am trying to achieve.

I have tried using the angle() function in the mathlib package and the angle.calc() function in the Morpho package. Here is the code I used to calculate the angle using the angle() function.

vector1<-data[1,,]-data[2,,]
vector2<-data[3,,]-data[4,,]
angle(as.vector(vector1),as.vector(vector2),degree=TRUE)

These functions will calculate what seems to be the accurate angle however they will only do it for the first specimen or a single specimen if otherwise specified, and do not produce a list of angles for all specimens. I have also checked previous questions on Stack Overflow but none of the answers given appear to be applicable to a dataset containing multiple specimens  with each column on both matrices representing a distinct specimen (and when I apply them at best they seem to have the same problem where they only return the angle for the first specimen). There are only three specimens here, I have a large number of specimens and multiple angles per specimen in the actual dataset and it is not possible to measure every angle individually for each specimen.

Is there any way to write a formula to produce a list containing the respective angle for each of these specimens?

Body:
First off, it's a bit confusing to give a 2x3 matrix the name vector1. That aside, you can use matlib::angle to calculate angles.

library(matlib)
phi <- setNames(mapply(
    function(x1, x2) angle(x1, x2),
    as.data.frame(vector1), as.data.frame(vector2)),
    paste0("Specimen", 1:ncol(vector1)))
phi
#Specimen1 Specimen2 Specimen3
# 146.2674  152.4439  134.8753

Explanation: Use mapply to simultaneously iterate over the columns of vector1 and vector2, which have been converted to data.frames. Use stack to convert the named vector into a data.frame:

stack(phi)
#    values       ind
#1 146.2674 Specimen1
#2 152.4439 Specimen2
#3 134.8753 Specimen3


问:
Insert multiple python substrings by index 'at same time'
Suppose I have a string

```<code>a = 'The dog in the street.' (so len(a)=8).
     01234567  (just adding indices for extra illustration)
</code>```

Now I want to change that string to include some arbitrary words in arbitrary places, say, from the (arbitrarily sized) dict:

```<code>d = {
        'w1': {'begin':'0', 'end':'3', 'w':'BIG'}
        'w2': {'being':'4', 'end':'7', 'w':'BARKED
    }
</code>```

where wx contains info about a word to insert, with the fields meaning:

being: the start index of the word we want to insert after (inclusive)

end: the end index of the word we want to insert after (exclusive)

w: the word to insert

So 'applying' the dict d to string a, we would get:

```<code>a = 'TheBIGdogBARKEDin the street.'
     0123456789...
</code>```

Note that, though I have ordered the dictionary values here so that the words to be inserted are in left-to-right order, this is not always the case.

I was initially trying to to do this with something like:

```<code>for word in d:
    insertion_loc = word['end']
    a = "{}{}{}".format(a[:insertion_loc], word['w'], a[insertion_loc:])
</code>```

But when doing this, each iteration changes the total length of the string, so the begin and end indices no longer are applicable for the next word in the dict that wants to be inserted into the string. The only other way the immediately comes to mind is calculating new offsets for insertion based on the previously inserted substring(s) length(s) and whether the current string to be inserted is going to be inserted before or after the previously inserted substrings' locations (which seems like it would look a bit ugly).

Is there another way to do this? Thanks.

答: You can insert from the end towards the front instead, this way you don't have to take into account the increasing indexes</p>

Body:
Suppose I have a string

a = 'The dog in the street.' (so len(a)=8).
     01234567  (just adding indices for extra illustration)

Now I want to change that string to include some arbitrary words in arbitrary places, say, from the (arbitrarily sized) dict:

d = {
        'w1': {'begin':'0', 'end':'3', 'w':'BIG'}
        'w2': {'being':'4', 'end':'7', 'w':'BARKED
    }

where wx contains info about a word to insert, with the fields meaning:

being: the start index of the word we want to insert after (inclusive)

end: the end index of the word we want to insert after (exclusive)

w: the word to insert

So 'applying' the dict d to string a, we would get:

a = 'TheBIGdogBARKEDin the street.'
     0123456789...

Note that, though I have ordered the dictionary values here so that the words to be inserted are in left-to-right order, this is not always the case.

I was initially trying to to do this with something like:

for word in d:
    insertion_loc = word['end']
    a = "{}{}{}".format(a[:insertion_loc], word['w'], a[insertion_loc:])

But when doing this, each iteration changes the total length of the string, so the begin and end indices no longer are applicable for the next word in the dict that wants to be inserted into the string. The only other way the immediately comes to mind is calculating new offsets for insertion based on the previously inserted substring(s) length(s) and whether the current string to be inserted is going to be inserted before or after the previously inserted substrings' locations (which seems like it would look a bit ugly).

Is there another way to do this? Thanks.


问:
Things to be aware of when using a container as a parent instead of MaterialApp/Scaffold
Say I'm building an app that doesn't need Material design elements and use a container as a parent.

Are there things that need to be set up manually (layout-wise) that's unnecessary when using MaterialApp/Scaffold?

Following are few unexpected behaviors I noticed when using a container as a parent:
• Yellow lines in Text widgets (These lines disappear when using Scaffold instead)
• ClipRRect widget takes up the full screen even when I set constraints

答:
Material class is a main component of your UI. Using a Material Widget as parent doesn't mean you are forced to use Material Design for your entire app, you can do your own custom Widgets, UI, etc.

As part of the official documentation:

```<code>The Material widget is responsible for:

Clipping: If clipBehavior is not Clip.none, Material clips its widget sub-tree to the shape specified by shape, type, and borderRadius. By default, clipBehavior is Clip.none for performance considerations.
Elevation: Material elevates its widget sub-tree on the Z axis by elevation pixels, and draws the appropriate shadow.
Ink effects: Material shows ink effects implemented by InkFeatures like InkSplash and InkHighlight below its children.
</code>```

It is also responsible of providing default styles for your Texts (that's why you're seeing the yellow underline).

Still, remember that you're making apps for mobile clients, therefore, you should be using some of the best practices that MaterialApp and CupertinoApp bring out of the box, even if you decide to take your own path inside the app, using your own custom Widgets, etc

Body:
Material class is a main component of your UI. Using a Material Widget as parent doesn't mean you are forced to use Material Design for your entire app, you can do your own custom Widgets, UI, etc.

As part of the official documentation:

The Material widget is responsible for:

Clipping: If clipBehavior is not Clip.none, Material clips its widget sub-tree to the shape specified by shape, type, and borderRadius. By default, clipBehavior is Clip.none for performance considerations.
Elevation: Material elevates its widget sub-tree on the Z axis by elevation pixels, and draws the appropriate shadow.
Ink effects: Material shows ink effects implemented by InkFeatures like InkSplash and InkHighlight below its children.

It is also responsible of providing default styles for your Texts (that's why you're seeing the yellow underline).

Still, remember that you're making apps for mobile clients, therefore, you should be using some of the best practices that MaterialApp and CupertinoApp bring out of the box, even if you decide to take your own path inside the app, using your own custom Widgets, etc


问:
Dealing with null-able objects in ion-input
I'm trying to generate an editable table based on the result of an API I'm calling, which can look like this(json below). The reason why some data are null is because I'm calling a text recognition API so it will only show what has been detected from an image.

Json result:

```<code>{
    "restaurant": null,
    "details": [
        {
            "text": null,
            "price": {
                "unitPrice": 5.0,
                "coordinateX": 389
            }
        },
        {
            "text": {
                "text": "Americano",
                "coordinateX": 311
            },
            "price": null
        },
        {
            "text": {
                "text": "Latte",
                "coordinateX": 130
            },
            "price": {
                "unitPrice": 43.24,
                "coordinateX": 205,
            }
        }
    ]
}
</code>```

Upon getting the result from the API, I then map it to an object ImageResult:

Object:

```<code>export class ImageResult {
    constructor(
        public Restaurant: string,
        public CapturedDetails: Details[]
    ) {}
  }
</code>```

Call:

```<code>this.textCaptureService.GetText(formData).subscribe(data => {
        this.result = data;
      });
</code>```

My issue is that I'm getting an error of cannot read property ___ of null when parts of the object are null in the ion-input tags. How do I deal with Objects that can have null properties. E.g. if null, then display blank or empty string

```<code><ion-input [disabled]="false" [(ngModel)]="result.Restaurant" autofocus="true"> </ion-input>
<ion-row *ngFor="let item of items.Details">
      <ion-col></ion-col>
      <ion-col size="3" class="prices-table-name">
        <ion-input [disabled]="!true" [(ngModel)]="result.Text.Text" (press)="setEditable(item.Text.Text)"> </ion-input>
      </ion-col>
      <ion-col size="3" class="prices-table-value">
        <ion-input [disabled]="!true" [(ngModel)]="result.Price.UnitPrice" (press)="setEditable(item.Price.UnitPrice)"> </ion-input>
      </ion-col>
      <ion-col></ion-col>
    </ion-row>
</code>```

答:
Use *ngIf to check whether result is null or not.

<ion-input *ngIf="result !== null" [disabled]="false" [(ngModel)]="result.Restaurant" autofocus="true"> </ion-input>

```

Body:
I'm trying to generate an editable table based on the result of an API I'm calling, which can look like this(json below). The reason why some data are null is because I'm calling a text recognition API so it will only show what has been detected from an image.

Json result:

{
    "restaurant": null,
    "details": [
        {
            "text": null,
            "price": {
                "unitPrice": 5.0,
                "coordinateX": 389
            }
        },
        {
            "text": {
                "text": "Americano",
                "coordinateX": 311
            },
            "price": null
        },
        {
            "text": {
                "text": "Latte",
                "coordinateX": 130
            },
            "price": {
                "unitPrice": 43.24,
                "coordinateX": 205,
            }
        }
    ]
}

Upon getting the result from the API, I then map it to an object ImageResult:

Object:

export class ImageResult {
    constructor(
        public Restaurant: string,
        public CapturedDetails: Details[]
    ) {}
  }

Call:

this.textCaptureService.GetText(formData).subscribe(data => {
        this.result = data;
      });

My issue is that I'm getting an error of cannot read property ___ of null when parts of the object are null in the ion-input tags. How do I deal with Objects that can have null properties. E.g. if null, then display blank or empty string

<ion-input [disabled]="false" [(ngModel)]="result.Restaurant" autofocus="true"> </ion-input>
<ion-row *ngFor="let item of items.Details">
      <ion-col></ion-col>
      <ion-col size="3" class="prices-table-name">
        <ion-input [disabled]="!true" [(ngModel)]="result.Text.Text" (press)="setEditable(item.Text.Text)"> </ion-input>
      </ion-col>
      <ion-col size="3" class="prices-table-value">
        <ion-input [disabled]="!true" [(ngModel)]="result.Price.UnitPrice" (press)="setEditable(item.Price.UnitPrice)"> </ion-input>
      </ion-col>
      <ion-col></ion-col>
    </ion-row>


问:
Restart App Pool from ASP.NET via WMI Problems
I've been trying to create a C# ASP.NET page which sits on a Windows Server 2003 IIS 6 server and when called (remotely), restarts/recycles a specific application pool on the server.

I've not been having much luck, does anyone know where I'm going wrong? I've tried many combinations and tried running direct from server but to no-avail.

When I don't pass the credentials over I get the error...

Access is denied

...and when I do pass them I get the error...

User credentials cannot be used for local connections

I've also tried elevating permissions with the anon account just to test but again it wouldn't work.  Is this possible what I'm trying to achieve?

try
{
    ManagementScope scope = new ManagementScope("root\\MicrosoftIISv2");
    scope.Path.Server = "servername";
    scope.Path.Path = "\\\\servername\\root\\MicrosoftIISv2";
    scope.Path.NamespacePath = "root\\MicrosoftIISv2";
    scope.Options.Username = "domain\\user";
    scope.Options.Password = "password";
    scope.Options.Authentication = AuthenticationLevel.Default;
    scope.Options.Impersonation = ImpersonationLevel.Impersonate;
    scope.Options.EnablePrivileges = true;
    scope.Connect();

    ManagementObject appPool = new ManagementObject(scope, new ManagementPath("IIsApplicationPool.Name='W3SVC/AppPools/AppPoolName'"), null);
    appPool.InvokeMethod("Recycle", null, null);
}
catch (System.Exception ex)
{
}
```

答:
It is not possible to specify alternate credentials when connecting to the local WMI service.

Internally, the ManagementScope.Connect() method uses the ConnectServerWmi function, which is a wrapper around the IWbemLocator::ConnectServer method.  That documentation states...

Do not specify strUser, strPassword, or strAuthority when making a connection to a local namespace. For more information, see Connecting to WMI on a Remote Computer.

If you follow that link you'll find it says...

If you were trying to access a different account, you would need to supply additional credentials. (Note that trying to access WMI locally with credentials different than your current account is not permitted.)

So, there is simply no way to do this through the WMI API.  A workaround I had success with is to use impersonation, as in the accepted answer.  The documentation for the WindowsIdentity.Impersonate() method provides a good, robust example of this.


问:
can not find module "@angular/material"
I'm using Angular 2. When I'm trying to import "@angular/material" i'm getting error for this. I'm importing packages like:

```<code>import {MdDialog} from "@angular/material";
import {MdDialogRef} from "@angular/material";
</code>```

My tsconfig.json file like:

```<code>{
 "compilerOptions": {
"baseUrl": "",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"mapRoot": "./",
"module": "es6",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
  "../node_modules/@types"
]
}
}
</code>```

My package.json code:

```<code>{
 "name": "rmc-temporary",
 "version": "0.0.0",
 "license": "MIT",
 "angular-cli": {},
 "scripts": {
   "start": "ng serve",
   "lint": "tslint \"src/**/*.ts\"",
   "test": "ng test",
   "pree2e": "webdriver-manager update",
   "e2e": "protractor"
 },
 "private": true,
 "dependencies": {
 "@angular/common": "2.2.1",
 "@angular/compiler": "2.2.1",
 "@angular/core": "2.2.1",
 "@angular/forms": "2.2.1",
 "@angular/http": "2.2.1",
 "@angular/platform-browser": "2.2.1",
 "@angular/platform-browser-dynamic": "2.2.1",
 "@angular/router": "3.2.1",
 "core-js": "^2.4.1",
 "rxjs": "5.0.0-beta.12",
 "ts-helpers": "^1.1.1",
 "zone.js": "^0.6.23"
},
"devDependencies": {
 "@angular/compiler-cli": "2.2.1",
 "@types/jasmine": "2.5.38",
 "@types/node": "^6.0.42",
 "angular-cli": "1.0.0-beta.21",
 "codelyzer": "~1.0.0-beta.3",
 "jasmine-core": "2.5.2",
 "jasmine-spec-reporter": "2.5.0",
 "karma": "1.2.0",
 "karma-chrome-launcher": "^2.0.0",
 "karma-cli": "^1.0.1",
 "karma-jasmine": "^1.0.2",
 "karma-remap-istanbul": "^0.2.1",
 "protractor": "4.0.9",
 "ts-node": "1.2.1",
 "tslint": "3.13.0",
 "typescript": "~2.0.3",
 "webdriver-manager": "10.2.5"
}
}
</code>```

答:
Found this post: "Breaking changes" in angular 9. All modules must be imported separately. Also a fine module available there, thanks to @jeff-gilliland:
https://stackoverflow.com/a/60111086/824622</p>

Title: can not find module "@angular/material"

Body:
I'm using Angular 2. When I'm trying to import "@angular/material" i'm getting error for this. I'm importing packages like:

import {MdDialog} from "@angular/material";
import {MdDialogRef} from "@angular/material";

My tsconfig.json file like:

{
 "compilerOptions": {
"baseUrl": "",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"mapRoot": "./",
"module": "es6",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
  "../node_modules/@types"
]
}
}

My package.json code:

{
 "name": "rmc-temporary",
 "version": "0.0.0",
 "license": "MIT",
 "angular-cli": {},
 "scripts": {
   "start": "ng serve",
   "lint": "tslint \"src/**/*.ts\"",
   "test": "ng test",
   "pree2e": "webdriver-manager update",
   "e2e": "protractor"
 },
 "private": true,
 "dependencies": {
 "@angular/common": "2.2.1",
 "@angular/compiler": "2.2.1",
 "@angular/core": "2.2.1",
 "@angular/forms": "2.2.1",
 "@angular/http": "2.2.1",
 "@angular/platform-browser": "2.2.1",
 "@angular/platform-browser-dynamic": "2.2.1",
 "@angular/router": "3.2.1",
 "core-js": "^2.4.1",
 "rxjs": "5.0.0-beta.12",
 "ts-helpers": "^1.1.1",
 "zone.js": "^0.6.23"
},
"devDependencies": {
 "@angular/compiler-cli": "2.2.1",
 "@types/jasmine": "2.5.38",
 "@types/node": "^6.0.42",
 "angular-cli": "1.0.0-beta.21",
 "codelyzer": "~1.0.0-beta.3",
 "jasmine-core": "2.5.2",
 "jasmine-spec-reporter": "2.5.0",
 "karma": "1.2.0",
 "karma-chrome-launcher": "^2.0.0",
 "karma-cli": "^1.0.1",
 "karma-jasmine": "^1.0.2",
 "karma-remap-istanbul": "^0.2.1",
 "protractor": "4.0.9",
 "ts-node": "1.2.1",
 "tslint": "3.13.0",
 "typescript": "~2.0.3",
 "webdriver-manager": "10.2.5"
}
}


问:
Why Safari does not save Cookie in response to storage?
I have nodeJS website that sends cookie back to browser in response.
I am testing in local network development environment where the website is started at 192.168.1.12.
At the following is the screenshot of Safari console where I can see the cookie is in the response

However, in Safari's cookie storage tab the cookie is not presented

So my question is: Why Safari does not take the cookie returned in the response?

答: The problem is Safari cached data. After clearing Safari browser historical data, the problem is resolved and cookie is saved into storage after refreshing the page.</p>


问:
How to deploy a C# (ClickOnce?) project that is a wrapper on a command line .exe
I have a C# project which is basically a GUI used to call other executable(s) with command line arguments. (The command line exe was actually built with cygwin and uses the cugwin DLL).

So the directory structure that needs to exist once the app is deployed (via setup.exe or whatever) is this:

```<code>install dir --->   MyApp.exe
                   MyApp.config
                   (dir) bin   ---> cmd1.exe
                                    cmd2.exe
                                    cygwin.dll
</code>```

Now this ought to be simple, but whatever I try, I cannot get the bin directory and its contents to be copied when I install on a second machine with setup.exe. I tried:
  - adding them as resources
  - setting "Build Action" to Content
  - setting "Copy To Output Directory" to Always

But the bin directory was never copied across when I did this. I have tried searching here and elsewhere but I am still at a loss.

Should this be a "ClickOnce" project? (what does this even mean - are there also ClickTwice and ClickUntilYouCanClickNoMore projects - ok, excuse me ...)

Also do I get setup.exe to put this app somewhere sane like C://Program Files/MyOrg/Myapp  - instead of being buried somewhere in the user's profile?

(Using VS 2019.)

答:
To package the specified file into ClickOnce, you just need to add it to Application Files....

The following is the folder structure.

And then confirm it has been added into Application Files....

Last step, publish it. And you can access the image like this.

```<code>private void button1_Click(object sender, EventArgs e)
{
    pictureBox1.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"/img/a.jpg");
}
</code>```

As to put this app somewhere sane, I am afraid the answer is no.

ClickOnce's installation path cannot be changed. You can find it at C:\Users\username\AppData\Local\Apps\2.0.

Body:
I have a C# project which is basically a GUI used to call other executable(s) with command line arguments. (The command line exe was actually built with cygwin and uses the cugwin DLL).

So the directory structure that needs to exist once the app is deployed (via setup.exe or whatever) is this:

install dir --->   MyApp.exe
                   MyApp.config
                   (dir) bin   ---> cmd1.exe
                                    cmd2.exe
                                    cygwin.dll

Now this ought to be simple, but whatever I try, I cannot get the bin directory and its contents to be copied when I install on a second machine with setup.exe. I tried:
  - adding them as resources
  - setting "Build Action" to Content
  - setting "Copy To Output Directory" to Always

But the bin directory was never copied across when I did this. I have tried searching here and elsewhere but I am still at a loss.

Should this be a "ClickOnce" project? (what does this even mean - are there also ClickTwice and ClickUntilYouCanClickNoMore projects - ok, excuse me ...)

Also do I get setup.exe to put this app somewhere sane like C://Program Files/MyOrg/Myapp  - instead of being buried somewhere in the user's profile?

(Using VS 2019.)

Body:
To package the specified file into ClickOnce, you just need to add it to Application Files....

The following is the folder structure.

And then confirm it has been added into Application Files....

Last step, publish it. And you can access the image like this.

private void button1_Click(object sender, EventArgs e)
{
    pictureBox1.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"/img/a.jpg");
}

As to put this app somewhere sane, I am afraid the answer is no.

ClickOnce's installation path cannot be changed. You can find it at C:\Users\username\AppData\Local\Apps\2.0.


问:
How do I sum 2 specific column rows in a DataFrame if some of the values are NaN?
I'd like to create a new column, Inches_z. If there are values in both Inches_x and Inches_y, I want to sum the values in those 2 specific columns and return it as the result for Inches_z in the same row. If one NaN value exists, I'd like to return the row value that's not the NaN value. If both values are NaN, I'd like the resulting value to also be NaN. How do I do this?

I have:

```<code>Name    | Inches_x | Feet | Inches_y
------------------------------------
'Silvers'|    7    |   1   |     2
'Jones'  |    7    |   2   |     7
'Jackson'|    4    |  NaN  |    NaN
'Merole' |   NaN   |   2   |     8
'Kanoff' |   NaN   |   5   |    NaN
'Walker' |   NaN   |   8   |     0
'Smith'  |    8    |   0   |     3
</code>```

I want:

```<code>Name    | Inches_x | Feet | Inches_y | Inches_z
-----------------------------------------------
'Silvers'|    7    |   1   |     2   |    9
'Jones'  |    7    |   2   |     7   |    14
'Jackson'|    4    |  NaN  |    NaN  |    4
'Merole' |   NaN   |   2   |     8   |    8
'Kanoff' |   NaN   |   5   |    NaN  |   NaN
'Walker' |   NaN   |   8   |     0   |    0
'Smith'  |    8    |   0   |     3   |    11
</code>```

答:
Sum and fillna with the two columns</p>

```<code>df['z'] = (df['Inches_x'] + df['Inches_y']).fillna(df['Inches_x']).fillna(df['Inches_y'])`
</code>```

```<code>        Name  Inches_x  Feet  Inches_y     z
0  'Silvers'       7.0   1.0       2.0   9.0
1    'Jones'       7.0   2.0       7.0  14.0
2  'Jackson'       4.0   NaN       NaN   4.0
3   'Merole'       NaN   2.0       8.0   8.0
4   'Kanoff'       NaN   5.0       NaN   NaN
5   'Walker'       1.0   8.0       0.0   1.0
6    'Smith'       8.0   0.0       3.0  11.0
</code>```

Body:
I'd like to create a new column, Inches_z. If there are values in both Inches_x and Inches_y, I want to sum the values in those 2 specific columns and return it as the result for Inches_z in the same row. If one NaN value exists, I'd like to return the row value that's not the NaN value. If both values are NaN, I'd like the resulting value to also be NaN. How do I do this?

I have:

Name    | Inches_x | Feet | Inches_y
------------------------------------
'Silvers'|    7    |   1   |     2
'Jones'  |    7    |   2   |     7
'Jackson'|    4    |  NaN  |    NaN
'Merole' |   NaN   |   2   |     8
'Kanoff' |   NaN   |   5   |    NaN
'Walker' |   NaN   |   8   |     0
'Smith'  |    8    |   0   |     3

I want:

Name    | Inches_x | Feet | Inches_y | Inches_z
-----------------------------------------------
'Silvers'|    7    |   1   |     2   |    9
'Jones'  |    7    |   2   |     7   |    14
'Jackson'|    4    |  NaN  |    NaN  |    4
'Merole' |   NaN   |   2   |     8   |    8
'Kanoff' |   NaN   |   5   |    NaN  |   NaN
'Walker' |   NaN   |   8   |     0   |    0
'Smith'  |    8    |   0   |     3   |    11

Body:
Sum and fillna with the two columns

df['z'] = (df['Inches_x'] + df['Inches_y']).fillna(df['Inches_x']).fillna(df['Inches_y'])`

        Name  Inches_x  Feet  Inches_y     z
0  'Silvers'       7.0   1.0       2.0   9.0
1    'Jones'       7.0   2.0       7.0  14.0
2  'Jackson'       4.0   NaN       NaN   4.0
3   'Merole'       NaN   2.0       8.0   8.0
4   'Kanoff'       NaN   5.0       NaN   NaN
5   'Walker'       1.0   8.0       0.0   1.0
6    'Smith'       8.0   0.0       3.0  11.0


问:
how to add tipbox when mouse hover on the text
http://bowser.effectgames.com/~jhuckaby/zeroclipboard/multiple.html

is there a way to add a tipbox  when the mouse hover on the copied text.the tip box say"the text has been copied" thank you.

HTML:code

```<code><body>
<div>
 <div class="example" "></div><div>copied text</div>
 <div class="example" "></div><div>copied text</div>
<div class="example" "></div><div>copied text</div>
<div class="example" "></div><div>copied text</div>
</div>
</body>
</code>```

答:
yeah it is:

```<code>clip.addEventListener('complete', run_my_tipbox);
</code>```

this will call the function run_my_tipbox when the text has been copied to the clipboard :)

so you will do something like that:

```<code>    <script language="JavaScript">
    var clip = null;

    function run_my_tipbox(){ alert('Text has been copied to the clipboard!'); }

    function init() {
        clip = new ZeroClipboard.Client();
        clip.setHandCursor( true );

        clip.addEventListener('load', my_load);
        clip.addEventListener('mouseOver', my_mouse_over);
        clip.addEventListener('complete', run_my_tipbox);

        clip.glue( 'd_clip_button' );
    }

</script>
</code>```

hopefully this makes it a bit more clear ;)

Body:
http://bowser.effectgames.com/~jhuckaby/zeroclipboard/multiple.html

is there a way to add a tipbox  when the mouse hover on the copied text.the tip box say"the text has been copied" thank you.

HTML:code

copied text

copied text

copied text

copied text

Body:
yeah it is:

clip.addEventListener('complete', run_my_tipbox);

this will call the function run_my_tipbox when the text has been copied to the clipboard :)

so you will do something like that:

    <script language="JavaScript">
    var clip = null;

    function run_my_tipbox(){ alert('Text has been copied to the clipboard!'); }

    function init() {
        clip = new ZeroClipboard.Client();
        clip.setHandCursor( true );

        clip.addEventListener('load', my_load);
        clip.addEventListener('mouseOver', my_mouse_over);
        clip.addEventListener('complete', run_my_tipbox);

        clip.glue( 'd_clip_button' );
    }

</script>

hopefully this makes it a bit more clear ;)


问:
How to flip Camera used by ZXing in Xamaring Forms
As part of the app i'm developing i want the ability to change between using the front or back camera, but from my searches and attempts i haven't been able to get it to work using the front camera.

The scanner view doing the scanning is the one from ZXing.Net.Mobile.Forms called ZXingScannerView, defined in my xaml like so, together with the button that should do the flipping of the camera.

<elements:AdvancedTabbedPage
...
xmlns:elements="clr-namespace:Wolf.Utility.Main.Xamarin.Elements;assembly=Wolf.Utility.Main"
xmlns:forms="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms">
...

<ContentPage>
   <ContentPage.ToolbarItems>
       <ToolbarItem Text="{x:Static resources:AppResources.CameraFlipText}" x:Name="CameraFlipButton" Clicked="CameraFlipButton_OnClicked"/>
   </ContentPage.ToolbarItems>
   <ContentPage.Content>
...
       <forms:ZXingScannerView x:Name="ScannerView" HeightRequest="200" IsAnalyzing="False" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" IsVisible="False" IsScanning="True"/>
...
   </ContentPage.Content>
</ContentPage>
```

<p>The Button can be seen in the top right of the following image, while the Scanner View is only visible while scanning is On, which it is not on the image.</p>

<p>Image of the Page where Scannning is happening</p>

<p>Clicking the button should toggle between using the front and back camera, with the front one as the default. Clicking the button however, doesn't seem to do anything, other then write to my Log. Code for the Clicked event of the button can be seen below.</p>

<pre class="lang-cs prettyprint-override"><code>...
private void CameraFlipButton_OnClicked(object sender, EventArgs e)
        {
            Logging.Log(LogType.Information, "Flipping Camera...");

            Config.DefaultOptions.UseFrontCameraIfAvailable = !Config.DefaultOptions.UseFrontCameraIfAvailable;
            Config.CustomOptions.UseFrontCameraIfAvailable = !Config.CustomOptions.UseFrontCameraIfAvailable;

            if (!ScanningToggle.IsToggled) return;

            Logging.Log(LogType.Information, "Restarting Scanning...");
            ScanningToggle.IsToggled = false;
            ScanningToggle.IsToggled = true;
        }
</code>```

The options mentioned in the above code is defined as so, in my Config class. Additional values in the one called CustomOptions are set in my Init method of my Config class, but those are irrelevant to this question.

public class Config
{
...
public static MobileBarcodeScanningOptions CustomOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
public static MobileBarcodeScanningOptions DefaultOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
...
}
```

The options that my scanner will use, is always picked between these two, depending on a few user inputs in the settings.

Attempting to get it to work i have also tried to...

Invert the value UseFrontCameraIfAvailable, while scanning is running

Invert the value UseFrontCameraIfAvailable on the options used to start the scan with and then restarting the scan - The code shown above.

Change IsScanning of the ZXingScannerView from true to false, while restarting the scanning with changed options, but this just resulted in the camera freezing.

Found this one as i was about to submit the question. I'm going to attempt to follow that one tomorrow, but would still very much like input on mine.

Fell free to ask questions, or ask for additional code if i have left something out, that you think could help.

答:
I don't think it can switch the front and back cameras when it has started scanning with Zxing,so the option has to be chosen and set beforehand</p>

```<code> var options = new MobileBarcodeScanningOptions
 {
     AutoRotate = true,
     UseNativeScanning = true,
     TryHarder = true,
     TryInverted = true,
     UseFrontCameraIfAvailable  = true
 };

 var scannedCode = await _scanner.Scan(options);
</code>```

Body:
As part of the app i'm developing i want the ability to change between using the front or back camera, but from my searches and attempts i haven't been able to get it to work using the front camera.

The scanner view doing the scanning is the one from ZXing.Net.Mobile.Forms called ZXingScannerView, defined in my xaml like so, together with the button that should do the flipping of the camera.

<elements:AdvancedTabbedPage
...
xmlns:elements="clr-namespace:Wolf.Utility.Main.Xamarin.Elements;assembly=Wolf.Utility.Main"
xmlns:forms="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms">
...

<ContentPage>
   <ContentPage.ToolbarItems>
       <ToolbarItem Text="{x:Static resources:AppResources.CameraFlipText}" x:Name="CameraFlipButton" Clicked="CameraFlipButton_OnClicked"/>
   </ContentPage.ToolbarItems>
   <ContentPage.Content>
...
       <forms:ZXingScannerView x:Name="ScannerView" HeightRequest="200" IsAnalyzing="False" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" IsVisible="False" IsScanning="True"/>
...
   </ContentPage.Content>
</ContentPage>

The Button can be seen in the top right of the following image, while the Scanner View is only visible while scanning is On, which it is not on the image.

Image of the Page where Scannning is happening

Clicking the button should toggle between using the front and back camera, with the front one as the default. Clicking the button however, doesn't seem to do anything, other then write to my Log. Code for the Clicked event of the button can be seen below.

...
private void CameraFlipButton_OnClicked(object sender, EventArgs e)
        {
            Logging.Log(LogType.Information, "Flipping Camera...");

            Config.DefaultOptions.UseFrontCameraIfAvailable = !Config.DefaultOptions.UseFrontCameraIfAvailable;
            Config.CustomOptions.UseFrontCameraIfAvailable = !Config.CustomOptions.UseFrontCameraIfAvailable;

            if (!ScanningToggle.IsToggled) return;

            Logging.Log(LogType.Information, "Restarting Scanning...");
            ScanningToggle.IsToggled = false;
            ScanningToggle.IsToggled = true;
        }

The options mentioned in the above code is defined as so, in my Config class. Additional values in the one called CustomOptions are set in my Init method of my Config class, but those are irrelevant to this question.

public class Config
{
...
public static MobileBarcodeScanningOptions CustomOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
public static MobileBarcodeScanningOptions DefaultOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
...
}

The options that my scanner will use, is always picked between these two, depending on a few user inputs in the settings.

Attempting to get it to work i have also tried to...

Invert the value UseFrontCameraIfAvailable, while scanning is running

Invert the value UseFrontCameraIfAvailable on the options used to start the scan with and then restarting the scan - The code shown above.

Change IsScanning of the ZXingScannerView from true to false, while restarting the scanning with changed options, but this just resulted in the camera freezing.

Found this one as i was about to submit the question. I'm going to attempt to follow that one tomorrow, but would still very much like input on mine.

Fell free to ask questions, or ask for additional code if i have left something out, that you think could help.

Body:
I don't think it can switch the front and back cameras when it has started scanning with Zxing,so the option has to be chosen and set beforehand

 var options = new MobileBarcodeScanningOptions
 {
     AutoRotate = true,
     UseNativeScanning = true,
     TryHarder = true,
     TryInverted = true,
     UseFrontCameraIfAvailable  = true
 };

 var scannedCode = await _scanner.Scan(options);


问:
Not all log levels are being logged in Application Insights
I have an application set up to use Application Insights, and I'm trying to manually log some custom information. Here's my controller:

```<code>public class MyController : Controller
{
    private ILogger<MyController> Logger { get; set; }

    public MyController(ILogger<MyController> logger)
    {
        Logger = logger;
    }

    public IActionResult Index()
    {
        Logger.LogCritical("Test critical");
        Logger.LogError("Test error");
        Logger.LogWarning("Test warning");
        Logger.LogInformation("Test information");
        Logger.LogDebug("Test debug");
        Logger.LogTrace("Test trace");

        ...
    }
</code>```

I have this in my Startup.cs:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning);
    ...
</code>```

}

And this in my Program.cs:

```<code>public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseApplicationInsights()
            .UseStartup<Startup>()
            .Build();
</code>```

And in my appsettings.json:

```<code>"Logging": {
  "IncludeScopes": false,
  "ApplicationInsights": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "LogLevel": {
    "Default": "Warning"
  }
}
</code>```

When I look in Application Insights in my Azure portal, the only things logged are:

So it's skipping a few for some reason, and only logging Critical, Warning, and Error. I'd mainly like to use LogInformation.

Is there something I need to change in my Logging settings or maybe in the Startup file?

答:
If you want to collect all telemetry data, you should not specify Warning logLevel in appsettings.json. The Warning log level will only collect the Warning / Error / Critical data, but abandon the Trace / Debug / Information data.

For more details, please refer to this doc and this doc.

Please specify the log level of application insights as Trace in appsettings.json, like below:

```<code>"Logging": {
  "IncludeScopes": false,
  "ApplicationInsights": {
    "LogLevel": {
      "Default": "Trace"
    }
  },
  "LogLevel": {
    "Default": "Warning"
  }
}
</code>```

Body:
I have an application set up to use Application Insights, and I'm trying to manually log some custom information. Here's my controller:

public class MyController : Controller
{
    private ILogger<MyController> Logger { get; set; }

    public MyController(ILogger<MyController> logger)
    {
        Logger = logger;
    }

    public IActionResult Index()
    {
        Logger.LogCritical("Test critical");
        Logger.LogError("Test error");
        Logger.LogWarning("Test warning");
        Logger.LogInformation("Test information");
        Logger.LogDebug("Test debug");
        Logger.LogTrace("Test trace");

        ...
    }

I have this in my Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning);
    ...

}

And this in my Program.cs:

public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseApplicationInsights()
            .UseStartup<Startup>()
            .Build();

And in my appsettings.json:

"Logging": {
  "IncludeScopes": false,
  "ApplicationInsights": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "LogLevel": {
    "Default": "Warning"
  }
}

When I look in Application Insights in my Azure portal, the only things logged are:

So it's skipping a few for some reason, and only logging Critical, Warning, and Error. I'd mainly like to use LogInformation.

Is there something I need to change in my Logging settings or maybe in the Startup file?

Body:
If you want to collect all telemetry data, you should not specify Warning logLevel in appsettings.json. The Warning log level will only collect the Warning / Error / Critical data, but abandon the Trace / Debug / Information data.

For more details, please refer to this doc and this doc.

Please specify the log level of application insights as Trace in appsettings.json, like below:

"Logging": {
  "IncludeScopes": false,
  "ApplicationInsights": {
    "LogLevel": {
      "Default": "Trace"
    }
  },
  "LogLevel": {
    "Default": "Warning"
  }
}


问:
How to configure atom-beautify package to format with babel/jsx javascript files?
I searched for a package to auto-indent and beautify my React/babel code. I just tried atom-beautify which seems to have good feeback on Atom.

But the result on an usual babel file is not good enough: "HTML tag" doesn't indent as wanted. Has anyone tried to use atom-beautify with babel?

答:
I use miniprettier, it's listed on Prettier official site as a recommended package.

It's like prettier-atom but without all the dependencies. I love it! It works very well on JSX. I use atom-beautify for other filetypes (e.g. JSON, pure HTML, JS).


问:
How to see reachability of a specific JS object
I have a WebAssembly instance which creates a WebGL2 context. Ideally, when exiting the part of the page showing the context, I'd like to destroy the context and let the module and the textures, etc. be garbage collected. Problem is, I can't track down what is retaining a reference to the WebAssembly object.

How do I identify all places (properties, closures) with a reference to this object? (Chrome devtools or other readily available tools)

答:
I'm not sure if this is an answer to your question or not but ... in your details you wrote

I'd like to destroy the context and let the module and the textures, etc. be garbage collected.

Letting textures etc be garbage collected is the wrong way to clean up WebGL resources. See Are WebGL objects garbage collected?

If you know when WebAssembly is done you could track the resources from JavaScript by augmenting the context. Example

```<code>const allWebGL2ContextsResources = new Map();

HTMLCanvasElement.prototype.getContext = function(origFn) {
  return function(type, attribs) {
    const ctx = origFn.call(this, type, attribs);
    if (type === 'webgl2') {
      if (!allWebGL2ContextsResources.has(ctx)) {
        allWebGL2ContextsResources.set(ctx, new Set());
      }
    }
    return ctx;
  };
}(HTMLCanvasElement.prototype.getContext);

const types = ['Buffer', 'Texture', 'Renderbuffer', 'Framebuffer', 'Shader', 'Program', 'Sampler', 'TransformFeedback'];
for (const type of types) {
  const createName = `create${type}`;
  const deleteName = `delete${type}`;

  WebGL2RenderingContext.prototype[createType] = function(origFn) {
    return function(...args) {
      const obj = orignFn.call(this, ...args);
      allWebGL2ContextsResources.get(this).add(obj);
      return obj;
    };
  }(WebGL2RenderingContext.prototype[createType]);

  WebGL2RenderingContext.prototype[deleteType] = function(origFn) {
    return function(obj) {
      const obj = origFn.call(this, obj);
      allWebGL2ContextsResources(this).delete(obj);
    };
  }(WebGL2RenderingContext.prototype[deleteType]);
}
</code>```

Given that, when you start the WebAssembly code a new WebGL2 context will get added to allWebGL2Contexts so you could diff with a copy before to find the context that was added. Or change the code to emit an event or call a callback or whatever you need to discover the context.

When you're done with the WebAssembly code you could then go through the resources and delete them. Example

```<code>for (const obj of allWebGL2ContextsResources.get(someContext).entries()) {
  for (const type of types) {
    const Type = `WebGL${type}`;
    if (obj instanceof window[Type]) {
      someContext[`delete${type}`](obj);
      continue;
    }
  }
}
allWebGL2ContextsResources.delete(someContext);
</code>```

Or you could lose the context. See How do I clean up and unload a WebGL canvas context from GPU after use?

Assuming you're using emscripten then another option is that emscripten already tracks resources so you could modify the emscripten WebGL2 library to expose the context and the tracking or add some cleanup function to free everything that's tracked or lose the context.

Body:
I'm not sure if this is an answer to your question or not but ... in your details you wrote

I'd like to destroy the context and let the module and the textures, etc. be garbage collected.

Letting textures etc be garbage collected is the wrong way to clean up WebGL resources. See Are WebGL objects garbage collected?

If you know when WebAssembly is done you could track the resources from JavaScript by augmenting the context. Example

const allWebGL2ContextsResources = new Map();

HTMLCanvasElement.prototype.getContext = function(origFn) {
  return function(type, attribs) {
    const ctx = origFn.call(this, type, attribs);
    if (type === 'webgl2') {
      if (!allWebGL2ContextsResources.has(ctx)) {
        allWebGL2ContextsResources.set(ctx, new Set());
      }
    }
    return ctx;
  };
}(HTMLCanvasElement.prototype.getContext);

const types = ['Buffer', 'Texture', 'Renderbuffer', 'Framebuffer', 'Shader', 'Program', 'Sampler', 'TransformFeedback'];
for (const type of types) {
  const createName = `create${type}`;
  const deleteName = `delete${type}`;

  WebGL2RenderingContext.prototype[createType] = function(origFn) {
    return function(...args) {
      const obj = orignFn.call(this, ...args);
      allWebGL2ContextsResources.get(this).add(obj);
      return obj;
    };
  }(WebGL2RenderingContext.prototype[createType]);

  WebGL2RenderingContext.prototype[deleteType] = function(origFn) {
    return function(obj) {
      const obj = origFn.call(this, obj);
      allWebGL2ContextsResources(this).delete(obj);
    };
  }(WebGL2RenderingContext.prototype[deleteType]);
}

Given that, when you start the WebAssembly code a new WebGL2 context will get added to allWebGL2Contexts so you could diff with a copy before to find the context that was added. Or change the code to emit an event or call a callback or whatever you need to discover the context.

When you're done with the WebAssembly code you could then go through the resources and delete them. Example

for (const obj of allWebGL2ContextsResources.get(someContext).entries()) {
  for (const type of types) {
    const Type = `WebGL${type}`;
    if (obj instanceof window[Type]) {
      someContext[`delete${type}`](obj);
      continue;
    }
  }
}
allWebGL2ContextsResources.delete(someContext);

Or you could lose the context. See How do I clean up and unload a WebGL canvas context from GPU after use?

Assuming you're using emscripten then another option is that emscripten already tracks resources so you could modify the emscripten WebGL2 library to expose the context and the tracking or add some cleanup function to free everything that's tracked or lose the context.


问:
Difference between x[:1] and x[0]
I am working with tensorflow and numpy, and came across an issue where running a probability_model() on a single test example. My array, x_test is a 2d array.

```<code>probability_model(x_test[:1])
</code>```

works properly, however

```<code>probability_model(x_test[0])
</code>```

returns WARNING:tensorflow:Model was constructed with shape Tensor("sequential_input:0", shape=(None, 28, 28), dtype=float32) for input (None, 28, 28), but it was re-called on a Tensor with incompatible shape (28, 28).

I thought that x_test[0] and x_test[:1] would return the same 1D array, however it appears one results in a (None, 28, 28) dimensioned array, and the other results in a (28,28) array. So my question is not about tensorflow (I was just using it to show my error), do these expressions in fact result in different arrays, and if so what is the difference, because when analyzing their outputs they appear the same. Finally, is there an expression I can use to convert x_test[0] to the (None, 28, 28) size I need to call my function?

Thanks

答:
A simple test shows that arr[0] returns the object in location in 0, and arr[:1] returns the list cut out at index 1 (so just the first object).

a = [1, 2, 3]
print(a[0], a[:1])
```

<p>Outputs:</p>

```1 [1]
```

Title: Difference between x[:1] and x[0]

Body:
I am working with tensorflow and numpy, and came across an issue where running a probability_model() on a single test example. My array, x_test is a 2d array.

probability_model(x_test[:1])

works properly, however

probability_model(x_test[0])

returns WARNING:tensorflow:Model was constructed with shape Tensor("sequential_input:0", shape=(None, 28, 28), dtype=float32) for input (None, 28, 28), but it was re-called on a Tensor with incompatible shape (28, 28).

I thought that x_test[0] and x_test[:1] would return the same 1D array, however it appears one results in a (None, 28, 28) dimensioned array, and the other results in a (28,28) array. So my question is not about tensorflow (I was just using it to show my error), do these expressions in fact result in different arrays, and if so what is the difference, because when analyzing their outputs they appear the same. Finally, is there an expression I can use to convert x_test[0] to the (None, 28, 28) size I need to call my function?

Thanks

Body:
A simple test shows that arr[0] returns the object in location in 0, and arr[:1] returns the list cut out at index 1 (so just the first object).

a = [1, 2, 3]
print(a[0], a[:1])

Outputs:

1 [1]


问:
Create webapp war releases 'the maven way'
my webapp consists in mainly two artifacts, java-server.jar and js-client.war. Both are aggregated/overlayed and get additional property files for the target environment. Finally, i get the war file.

Some war files are deployed using tomcat:deploy some by a script but that shouldn't matter at this point.

There are several things I don't like with my approach:

server and client are released with the maven-release-plugin, the final webapp is not.

Just by having the final war file I cannot determine for which server it was built.

I usually need several client/server combinations at once: While I build the beta server with the stable versions, the nightly build server shall operate on the latest snapshots.

How do you maintain, release and deploy (to maven repo) stable/beta webapps? How do you maintain target-server specific configuration settings? How do you keep different versions? Do you have a lot of branches?

Thanks, Jan

答:
I can recommend using a build server like hudson. It has maven and rcs support.
You can specify for instance what branch of your source code to build and what maven targets to execute.

We also use hudson to deploy builds to our web servers.


答: This occurs when away.__call__(x) is passed a value x which lies outside of the convex hull - essentially, when x lies outside of the region of interpolation.

Title: Unusual nans Returned by scipy LinearNDInterpolator

Body:
I'm trying to interpolate the following data with python (3.8.1) using the aforementioned scipy function (official documentation here; source code here). The official documentation is incredibly sparse, so I'm hopeful that someone else out there will have some experience using the function and may know the source of this issue. Specifically, I run the following four lines of code:

    predictor = [[-1.7134013337139833, 0.9582376963057636, -0.21528572746395735], [3.25933089248862, -0.7087236333980123, 0.012808817274351122], [-0.5596739049487544, -1.8723369742231246, 0.03114189522349198], [0.23080764211370225, 1.0639221305852422, -0.602148693975945], [-0.9879484423429669, -0.16678510825693527, 0.5570132252912631], [0.0029439785978213986, -0.10016927713200409, -0.18197412051828055], [0.3530872261969887, 0.6347161018351574, 0.7285361235605389], [-1.122894723267098, 0.22837861478723648, -0.9022469946784363], [-0.02862856314533664, 0.014623415207400122, 3.078346263312741], [-1.3367570531570616, -0.3218239542354167, 0.489878302042675]]
    respose = [0.020235605909933625, 1.4729016163456679e-05, 0.021931080605237303, 0.21271851410989498, 0.26870984350693583, 0.9577608837143238, 0.3470452852299319, 0.11918254249689647, 7.657429164576589e-05, 0.1187813551565562]
    from scipy.interpolate import LinearNDInterpolator
    away = LinearNDInterpolator(predictor, response)

Now, if I write away.__call__([0,0,0])[0] then python returns 0.8208492283847619,
which is the desired outcome and is a sensible value based on the given test data. Similarly, away.__call__([0,0,1])[0] returns 0.22018657078617598 which is also a sensible value.
However, away.__call__([0,1,1])[0] returns nan. What changed? Does anyone happen to know?

Thank you.


问:
Read each url and save it to seperate pdf Python
I have list of urls and I would want to convert the list of urls to different pdfs for each url . There are about 273 urls in a file

my code is as follows

```<code>urls= ['https://www.amazon.com/','https://www.google.com/']

import pdfkit
path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)

for i in urls:
    pdfkit.from_url(i, "out.pdf", configuration=config)
</code>```

How can I write it to different pdfs? Thanks in advance.

I want my output to be out1.pdf, out2.pdf..out273.pdf

答:
try this.</p>

```<code>for i in range(len(urls)):
    pdfkit.from_url(urls[i], f"out{i}.pdf", configuration=config)
</code>```

Body:
I have list of urls and I would want to convert the list of urls to different pdfs for each url . There are about 273 urls in a file

my code is as follows

urls= ['https://www.amazon.com/','https://www.google.com/']

import pdfkit
path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)

for i in urls:
    pdfkit.from_url(i, "out.pdf", configuration=config)

How can I write it to different pdfs? Thanks in advance.

I want my output to be out1.pdf, out2.pdf..out273.pdf

Body:
try this.

for i in range(len(urls)):
    pdfkit.from_url(urls[i], f"out{i}.pdf", configuration=config)


问:
WINDOW function alternative in HAVING Clause
I'm trying to get the oldest processing date on each product like this:

```<code>select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
having prod_date = min_prod_date
</code>```

This gives me the error:

ORA-00904: "min_prod_date": invalid identifier

So I tried to use the min() function in the having clause which gave me the error:

ORA-30483: window  functions are not allowed here

As an alternative I modified my query like this:

```<code>with temp as(
select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
    having prod_date = min_prod_date))
select * from temp where prod_date = min_prod_date
</code>```

Is this the right way to do things or Is there any other efficient method?

答:
You can use your query as sub query and fetch the desired output as following:

```<code>Select prod_id, prod_name, prod_date
From
(select prod_id, prod_name, prod_date,
        min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz'))
Where prod_date = min_prod_date
</code>```

Cheers!!

Body:
I'm trying to get the oldest processing date on each product like this:

select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
having prod_date = min_prod_date

This gives me the error:

ORA-00904: "min_prod_date": invalid identifier

So I tried to use the min() function in the having clause which gave me the error:

ORA-30483: window  functions are not allowed here

As an alternative I modified my query like this:

with temp as(
select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
    having prod_date = min_prod_date))
select * from temp where prod_date = min_prod_date

Is this the right way to do things or Is there any other efficient method?

Body:
You can use your query as sub query and fetch the desired output as following:

Select prod_id, prod_name, prod_date
From
(select prod_id, prod_name, prod_date,
        min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz'))
Where prod_date = min_prod_date

Cheers!!


问:
Use write() to write char* to file from user input
I'm trying to write a function that takes in a path from stdin and saves that path to a file.
Despite many attempts, I have lost any kind of sense of how to properly do it. Can someone show me how to do it right?
This is my code:

```<code>void char_to_file(const char *pathname, const char *dest)
{
        int fd_1;
        if (fd_1 = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
                custom_error_shout("OPEN FD_1");
        while (*(pathname) != '\0')
        {
                *(pathname++);
                if (write(fd_1, &pathname, 1) == -1)
                        custom_error_shout("WRITE TO FILE");
        }

        if (close(fd_1) == -1)
                custom_error_shout("CLOSE FD_1");
}
</code>```

The file will be created but nothing will be written in it. No errors have come out of this.

答:
You sure chose the hard way to do this. Like @tadman suggested in comments, try this instead:</p>

```<code>void char_to_file(const char *pathname, const char *dest)
{
    FILE *fp;
    fp = fopen(dest, "w");
    if (fp == NULL)
    {
        custom_error_shout("Something went wrong opening the file");
        return;
    }

    if (fputs(pathname, fp) == EOF)
        custom_error_shout("Something went wrong writing to the file");

    fclose(fp);
}
</code>```

Body:
I'm trying to write a function that takes in a path from stdin and saves that path to a file.
Despite many attempts, I have lost any kind of sense of how to properly do it. Can someone show me how to do it right?
This is my code:

void char_to_file(const char *pathname, const char *dest)
{
        int fd_1;
        if (fd_1 = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
                custom_error_shout("OPEN FD_1");
        while (*(pathname) != '\0')
        {
                *(pathname++);
                if (write(fd_1, &pathname, 1) == -1)
                        custom_error_shout("WRITE TO FILE");
        }

        if (close(fd_1) == -1)
                custom_error_shout("CLOSE FD_1");
}

The file will be created but nothing will be written in it. No errors have come out of this.

Body:
You sure chose the hard way to do this. Like @tadman suggested in comments, try this instead:

void char_to_file(const char *pathname, const char *dest)
{
    FILE *fp;
    fp = fopen(dest, "w");
    if (fp == NULL)
    {
        custom_error_shout("Something went wrong opening the file");
        return;
    }

    if (fputs(pathname, fp) == EOF)
        custom_error_shout("Something went wrong writing to the file");

    fclose(fp);
}


问:
Python complex sorting of a list by multiple attributes with condition
The challenge is from this video https://www.youtube.com/watch?v=GSBLe8cKu0s&feature=youtu.be

There is a List of buildings. The building data has the format of [left, right, height] and it is massaged into two entries: [left, height, start] and [right, height, end] where start and end is a boolean type. So basically, it is [x, y, Boolean] type. (start = True, end = False)

Now I want to sort this list of [x, y, Boolean] according to x and while x is the same, the tie break will be Boolean type. If both x and Boolean type is the same, the next tie break is to sort by y and here is the tricky part, sorting of y will be ASC or DSC according to the Boolean flag.

So the list is to be sorted by x coordinates, then start followed by end. For the same x coordinates for start(True), the  y coordinates will be sorted descending while for the same x coordinates for end(False), the y coordinates will be sorted ascending.

答:
So we have to do sort two times and we will leave the primary sort by x (and boolean) coordinates last. We will do the sort where the direction of the sort change with the boolean flag first.
Here it is:

data.sort(key=lambda k: -k[1] if k[2] else k[1])

then it will be followed by the primary sorting:

data.sort(key=lambda k: (k[0], -k[2]))

Here is the complete code with input.

```<code>def main():
    sol = Solution()  # None
    arg1 = [[1,3,4],[3,4,4],[2,6,2],[8,11,4],[7,9,3],[10,11,2]]
    r = sol.getSkyline(arg1)
    print(r)

class Solution:

    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        if not buildings: return []
        data = []
        def compare(x, start):
            print(x, start)
            return (x, start)
        for building in buildings:
            data.append([building[0], building[2], True])
            data.append([building[1], building[2], False])
        data.sort(key=lambda k: -k[1] if k[2] else k[1])
        data.sort(key=lambda k: (k[0], -k[2]))
        return data

if __name__ == '__main__':
    main()
</code>```

Here is the output:

[1, 4, True]

[2, 2, True]

[3, 4, True]

[3, 4, False]

[4, 4, False]

[6, 2, False]

[7, 3, True]

[8, 4, True]

[9, 3, False]

[10, 2, True]

[11, 2, False]

[11, 4, False]

Body:
So we have to do sort two times and we will leave the primary sort by x (and boolean) coordinates last. We will do the sort where the direction of the sort change with the boolean flag first.
Here it is:

data.sort(key=lambda k: -k[1] if k[2] else k[1])

then it will be followed by the primary sorting:

data.sort(key=lambda k: (k[0], -k[2]))

Here is the complete code with input.

def main():
    sol = Solution()  # None
    arg1 = [[1,3,4],[3,4,4],[2,6,2],[8,11,4],[7,9,3],[10,11,2]]
    r = sol.getSkyline(arg1)
    print(r)

class Solution:

    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        if not buildings: return []
        data = []
        def compare(x, start):
            print(x, start)
            return (x, start)
        for building in buildings:
            data.append([building[0], building[2], True])
            data.append([building[1], building[2], False])
        data.sort(key=lambda k: -k[1] if k[2] else k[1])
        data.sort(key=lambda k: (k[0], -k[2]))
        return data

if __name__ == '__main__':
    main()

Here is the output:

[1, 4, True]

[2, 2, True]

[3, 4, True]

[3, 4, False]

[4, 4, False]

[6, 2, False]

[7, 3, True]

[8, 4, True]

[9, 3, False]

[10, 2, True]

[11, 2, False]

[11, 4, False]