问:
JDBC on Google Apps Script. Exception: Statement cancelled due to timeout or client request
I am trying to fetch data from mySQL database on Google Cloud SQL using JDBC from Google Apps Script. However, I got this error:

Exception: Statement cancelled due to timeout or client request

I can fetch some other data successfully. However, some data I can't.

I execute one of the successful queries and one of the unsuccessful queries on mySQL workbench. I can execute the unsuccessful query with no problem on mySQL workbench.

I compared the durations.

```<code>Duration / Fetch
-------------------------------------------
Successful query:     0.140 sec / 0.016 sec
Unsuccessful query:   0.406 sec / 0.047 sec
</code>```

The unsuccessful query seems to take longer. So, I set query timeout with:

```<code>stmt.setQueryTimeout(0);
</code>```

intending to set no timeout (when the value is set to zero it means that the execution has no timeout limit). Then, I executed it on Google Apps Script.

However, it doesn't work and get the same error. Could you tell me a solution for this?

答: This seems to be a known issue. Star ★ and comment  on the issue to get  Google developers to prioritise the issue. Until the issue is fixed, you can switch back to rhino runtime.</p>

Body:
I am trying to fetch data from mySQL database on Google Cloud SQL using JDBC from Google Apps Script. However, I got this error:

Exception: Statement cancelled due to timeout or client request

I can fetch some other data successfully. However, some data I can't.

I execute one of the successful queries and one of the unsuccessful queries on mySQL workbench. I can execute the unsuccessful query with no problem on mySQL workbench.

I compared the durations.

Duration / Fetch
-------------------------------------------
Successful query:     0.140 sec / 0.016 sec
Unsuccessful query:   0.406 sec / 0.047 sec

The unsuccessful query seems to take longer. So, I set query timeout with:

stmt.setQueryTimeout(0);

intending to set no timeout (when the value is set to zero it means that the execution has no timeout limit). Then, I executed it on Google Apps Script.

However, it doesn't work and get the same error. Could you tell me a solution for this?


来源: stackexchange

问:
Fail to render an animation
I'm trying to learn how to get a pretty animate graphic using R and gganimate, and I encounter some issue. When I try to animate my graphics, R seems to edit few PNG files, but then fail to render them. Here is an example of the code I use (tidyverse, gganimate, and gifski were loaded first):

```<code>p <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point()
p + transition_states(Species)
</code>```

R run the first line without issue. When it comes to the second line, console prints "rendering ----> etc.", with a countdown for a few seconds. Once it's over, it prints a lots of lines, which seems to describe the animated object (a list of PNG files, a list of states, etc.). I am guessing that's normal.

Finally, and it seems to me it is the issue, R give me a warning message:

```<code>file_renderer failed to copy frames to the destination directory
</code>```

And of course, I got no animation.

I saw other subjects about this, saying maybe it is a permission issue, but I am not good enough to understand what to do. I reproduced the issue on two machines, one on Ubuntu, the other on Windows.

答:
I really do not get why, but the problem have been solved by itself. On both computers, and both OS, the same code is now working. I didn't change anything, so can't tell what is the reason, and it's very weird because the two machines have nothing in common. Yet, they both couldn't create an animation two days ago, and they both can now.

Conclusion : if anyone have the same issue, maybe just retry a bit later ?

Conclusion 2: maybe I am just stupid, but I could use an explanation to know why then :)

ContentLicense: CC BY-SA 4.0

Title: Fail to render an animation

Body:
I'm trying to learn how to get a pretty animate graphic using R and gganimate, and I encounter some issue. When I try to animate my graphics, R seems to edit few PNG files, but then fail to render them. Here is an example of the code I use (tidyverse, gganimate, and gifski were loaded first):

p <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point()
p + transition_states(Species)

R run the first line without issue. When it comes to the second line, console prints "rendering ----> etc.", with a countdown for a few seconds. Once it's over, it prints a lots of lines, which seems to describe the animated object (a list of PNG files, a list of states, etc.). I am guessing that's normal.

Finally, and it seems to me it is the issue, R give me a warning message:

file_renderer failed to copy frames to the destination directory

And of course, I got no animation.

I saw other subjects about this, saying maybe it is a permission issue, but I am not good enough to understand what to do. I reproduced the issue on two machines, one on Ubuntu, the other on Windows.


问:
How i can use custom domain in google app engine?
Hi Google Cloud experts,
I want to use my custom domain www.example.com in App engine custom domain.I purchase domain from GoDaddy.
How can i do it.

答:
App Engine indeed supports the use of custom domains. I would recommend you to take a look at the documentation Adding a custom domain for your application.

On this tutorial, you will find all the information and steps needed for you to use your custom domain with App Engine.

Besides that, you can even use subdomains and wildcards, in case you want to use a range of domains or a list of domains, that you can redirect them to your application.

In addition, I would recommend you to take a look at the documentation Secure your custom domains with SSL, so you can find security information to implement on your application, once you are using your own domain.

Let me know if the information helped you!


问:
How to use Stencil's `EventEmitter` inside React JSX?
I created an Input web component with Stencil:

```<code>...
export class Input {
    @Prop({ mutable: true }) value: string;
    @Event() changed: EventEmitter<KeyboardEvent>;

    private handleChange (e) {
        this.value = e.target?.value;
        this.changed.emit(e);
    }

    render() {
        return (
            <div class="inputContainer">
                <input
                    type="text"
                    value={this.value}
                    onInput={this.handleChange}
                />
            </div>
        )
    }
}
</code>```

Then after trying to use it inside React jsx file, onChanged does not call console.log

```<code>...

function App() {
  return (
    <div className="App">
      // does not call console.log
      <ui-input onChanged={(e) => console.log(e)}/>
    </div>
  );
}

</code>```

As I've read so far it's because React uses the synthetic event instead of Dom events.

Is there any way to use Dom events within JSX element?

答:
You would have to manually attach the event listener using the DOM API, for example:

document.querySelector('ui-input').addEventListener('changed', console.log)
```

(You can also use the ref prop to get a reference to the DOM element which is probably more robust.)

Relevant docs section: https://stenciljs.com/docs/react#properties-and-events

Relevant Github issue: https://github.com/facebook/react/issues/7901

You have another option though, and that's to use the stencil-ds-plugins, specifically the @stencil/react-output-target npm package. When you build your component/library, the output target will generate all the necessary bindings (props, custom events, etc.) for you, and you'll be able to use your component as a react component. The only available docs so far ar in the readme: https://github.com/ionic-team/stencil-ds-plugins#react.

Body:
I created an Input web component with Stencil:

...
export class Input {
    @Prop({ mutable: true }) value: string;
    @Event() changed: EventEmitter<KeyboardEvent>;

    private handleChange (e) {
        this.value = e.target?.value;
        this.changed.emit(e);
    }

    render() {
        return (

                <input
                    type="text"
                    value={this.value}
                    onInput={this.handleChange}
                />

        )
    }
}

Then after trying to use it inside React jsx file, onChanged does not call console.log

...

function App() {
  return (

      // does not call console.log
      <ui-input onChanged={(e) => console.log(e)}/>

  );
}

As I've read so far it's because React uses the synthetic event instead of Dom events.

Is there any way to use Dom events within JSX element?

Body:
You would have to manually attach the event listener using the DOM API, for example:

document.querySelector('ui-input').addEventListener('changed', console.log)

(You can also use the ref prop to get a reference to the DOM element which is probably more robust.)

Relevant docs section: https://stenciljs.com/docs/react#properties-and-events

Relevant Github issue: https://github.com/facebook/react/issues/7901

You have another option though, and that's to use the stencil-ds-plugins, specifically the @stencil/react-output-target npm package. When you build your component/library, the output target will generate all the necessary bindings (props, custom events, etc.) for you, and you'll be able to use your component as a react component. The only available docs so far ar in the readme: https://github.com/ionic-team/stencil-ds-plugins#react.


问:
Regex recursion captured string
I have a problem with a regex that has to capture a substring that it's already captured...

I have this regex:

(?<domain>\w+\.\w+)($|\/|\.)

And I want to capture every subdomain recursively. For example, in this string:

test1.test2.abc.def

This expression captures test1.test2 and abc.def but I need to capture:
test1.test2
test2.abc
abc.def

Do you know if there is any option to do this recursively?

Thanks!

答:
You may use a well-known technique to extract overlapping matches, but you can't rely on \b boundaries as they can match between a non-word / word char and word / non-word char. You need unambiguous word boundaries for left and right hand contexts.

Use

```<code>(?=(?<!\w)(?<domain>\w+\.\w+)(?!\w))
</code>```

See the regex demo. Details:

(?= - a positive lookahead that enables testing each location in the string and capture the part of string to the right of it

(?<!\w) - a left-hand side word boundary

(?<domain>\w+\.\w+) - Group "domain": 1+ word chars, . and 1+ word chars

(?!\w) -  a right-hand side word boundary

) - end of the outer lookahead.

Another approach is to use dots as word delimiters. Then use

```<code>(?=(?<![^.])(?<domain>[^.]+\.[^.]+)(?![^.]))
</code>```

See this regex demo. Adjust as you see fit.

Title: Regex recursion captured string

Body:
You may use a well-known technique to extract overlapping matches, but you can't rely on \b boundaries as they can match between a non-word / word char and word / non-word char. You need unambiguous word boundaries for left and right hand contexts.

Use

(?=(?<!\w)(?<domain>\w+\.\w+)(?!\w))

See the regex demo. Details:

(?= - a positive lookahead that enables testing each location in the string and capture the part of string to the right of it

(?<!\w) - a left-hand side word boundary

(?<domain>\w+\.\w+) - Group "domain": 1+ word chars, . and 1+ word chars

(?!\w) -  a right-hand side word boundary

) - end of the outer lookahead.

Another approach is to use dots as word delimiters. Then use

(?=(?<![^.])(?<domain>[^.]+\.[^.]+)(?![^.]))

See this regex demo. Adjust as you see fit.


问:
Find conflicted date intervals using SQL
Suppose I have following table in Sql Server 2008:

```<code>ItemId StartDate   EndDate
1      NULL        2011-01-15
2      2011-01-16  2011-01-25
3      2011-01-26  NULL
</code>```

As you can see, this table has StartDate and EndDate columns. I want to validate data in these columns. Intervals cannot conflict with each other. So, the table above is valid, but the next table is invalid, becase first row has End Date greater than StartDate in the second row.

```<code>ItemId StartDate   EndDate
1      NULL        2011-01-17
2      2011-01-16  2011-01-25
3      2011-01-26  NULL
</code>```

NULL means infinity here.

Could you help me to write a script for data validation?

[The second task]

Thanks for the answers.
I have a complication. Let's assume, I have such table:

```<code>ItemId  IntervalId StartDate   EndDate
1       1          NULL        2011-01-15
2       1          2011-01-16  2011-01-25
3       1          2011-01-26  NULL
4       2          NULL        2011-01-17
5       2          2011-01-16  2011-01-25
6       2          2011-01-26  NULL
</code>```

Here I want to validate intervals within a groups of IntervalId, but not within the whole table. So, Interval 1 will be valid, but Interval 2 will be invalid.

And also. Is it possible to add a constraint to the table in order to avoid such invalid records?

[Final Solution]

I created function to check if interval is conflicted:

```<code>CREATE FUNCTION [dbo].[fnIntervalConflict]
(
    @intervalId INT,
    @originalItemId INT,
    @startDate DATETIME,
    @endDate DATETIME
)
RETURNS BIT
AS
BEGIN

    SET @startDate = ISNULL(@startDate,'1/1/1753 12:00:00 AM')
    SET @endDate = ISNULL(@endDate,'12/31/9999 11:59:59 PM')

    DECLARE @conflict BIT = 0

    SELECT TOP 1 @conflict = 1
    FROM Items
    WHERE IntervalId = @intervalId
    AND ItemId <> @originalItemId
    AND (
    (ISNULL(StartDate,'1/1/1753 12:00:00 AM') >= @startDate
     AND ISNULL(StartDate,'1/1/1753 12:00:00 AM') <= @endDate)
     OR (ISNULL(EndDate,'12/31/9999 11:59:59 PM') >= @startDate
     AND ISNULL(EndDate,'12/31/9999 11:59:59 PM') <= @endDate)
    )

    RETURN @conflict
END
</code>```

And then I added 2 constraints to my table:

```<code>ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_Dates CHECK (StartDate IS NULL OR EndDate IS NULL OR StartDate <= EndDate)

GO
</code>```

and

```<code>ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_ValidInterval CHECK (([dbo].[fnIntervalConflict]([IntervalId], ItemId,[StartDate],[EndDate])=(0)))

GO
</code>```

I know, the second constraint slows insert and update operations, but it is not very important for my application.
And also, now I can call function fnIntervalConflict from my application code before inserts and updates of data in the table.

答:
This will give you the rows that are incorrect.

Added ROW_NUMBER() as I didnt know if all entries where in order.

```<code>-- Testdata
declare @date datetime = '2011-01-17'

;with yourTable(itemID, startDate, endDate)
as
(
    SELECT  1,  NULL, @date
    UNION ALL
    SELECT  2,  dateadd(day, -1, @date),    DATEADD(day, 10, @date)
    UNION ALL
    SELECT  3,  DATEADD(day, 60, @date),    NULL
)

-- End testdata

,tmp
as
(
    select  *
            ,ROW_NUMBER() OVER(order by startDate) as rowno
    from    yourTable
)

select  *
from    tmp t1
left join   tmp t2
    on t1.rowno = t2.rowno - 1
where   t1.endDate > t2.startDate
</code>```

EDIT:
As for the updated question:

Just add a PARTITION BY clause to the ROW_NUMBER() query and alter the join.

```<code>-- Testdata
declare @date datetime = '2011-01-17'

;with yourTable(itemID, startDate, endDate, intervalID)
as
(
    SELECT  1,  NULL, @date, 1
    UNION ALL
    SELECT  2,  dateadd(day, 1, @date), DATEADD(day, 10, @date),1
    UNION ALL
    SELECT  3,  DATEADD(day, 60, @date),    NULL,   1
    UNION ALL
    SELECT  4,  NULL, @date, 2
    UNION ALL
    SELECT  5,  dateadd(day, -1, @date),    DATEADD(day, 10, @date),2
    UNION ALL
    SELECT  6,  DATEADD(day, 60, @date),    NULL,   2
)

-- End testdata

,tmp
as
(
    select  *
            ,ROW_NUMBER() OVER(partition by intervalID order by startDate) as rowno
    from    yourTable
)

select  *
from    tmp t1
left join   tmp t2
    on t1.rowno = t2.rowno - 1
    and t1.intervalID = t2.intervalID
where   t1.endDate > t2.startDate
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have following table in Sql Server 2008:

ItemId StartDate   EndDate
1      NULL        2011-01-15
2      2011-01-16  2011-01-25
3      2011-01-26  NULL

As you can see, this table has StartDate and EndDate columns. I want to validate data in these columns. Intervals cannot conflict with each other. So, the table above is valid, but the next table is invalid, becase first row has End Date greater than StartDate in the second row.

ItemId StartDate   EndDate
1      NULL        2011-01-17
2      2011-01-16  2011-01-25
3      2011-01-26  NULL

NULL means infinity here.

Could you help me to write a script for data validation?

[The second task]

Thanks for the answers.
I have a complication. Let's assume, I have such table:

ItemId  IntervalId StartDate   EndDate
1       1          NULL        2011-01-15
2       1          2011-01-16  2011-01-25
3       1          2011-01-26  NULL
4       2          NULL        2011-01-17
5       2          2011-01-16  2011-01-25
6       2          2011-01-26  NULL

Here I want to validate intervals within a groups of IntervalId, but not within the whole table. So, Interval 1 will be valid, but Interval 2 will be invalid.

And also. Is it possible to add a constraint to the table in order to avoid such invalid records?

[Final Solution]

I created function to check if interval is conflicted:

CREATE FUNCTION [dbo].[fnIntervalConflict]
(
    @intervalId INT,
    @originalItemId INT,
    @startDate DATETIME,
    @endDate DATETIME
)
RETURNS BIT
AS
BEGIN

    SET @startDate = ISNULL(@startDate,'1/1/1753 12:00:00 AM')
    SET @endDate = ISNULL(@endDate,'12/31/9999 11:59:59 PM')

    DECLARE @conflict BIT = 0

    SELECT TOP 1 @conflict = 1
    FROM Items
    WHERE IntervalId = @intervalId
    AND ItemId <> @originalItemId
    AND (
    (ISNULL(StartDate,'1/1/1753 12:00:00 AM') >= @startDate
     AND ISNULL(StartDate,'1/1/1753 12:00:00 AM') <= @endDate)
     OR (ISNULL(EndDate,'12/31/9999 11:59:59 PM') >= @startDate
     AND ISNULL(EndDate,'12/31/9999 11:59:59 PM') <= @endDate)
    )

    RETURN @conflict
END

And then I added 2 constraints to my table:

ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_Dates CHECK (StartDate IS NULL OR EndDate IS NULL OR StartDate <= EndDate)

GO

and

ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_ValidInterval CHECK (([dbo].[fnIntervalConflict]([IntervalId], ItemId,[StartDate],[EndDate])=(0)))

GO

I know, the second constraint slows insert and update operations, but it is not very important for my application.
And also, now I can call function fnIntervalConflict from my application code before inserts and updates of data in the table.

Body:
This will give you the rows that are incorrect.

Added ROW_NUMBER() as I didnt know if all entries where in order.

-- Testdata
declare @date datetime = '2011-01-17'

;with yourTable(itemID, startDate, endDate)
as
(
    SELECT  1,  NULL, @date
    UNION ALL
    SELECT  2,  dateadd(day, -1, @date),    DATEADD(day, 10, @date)
    UNION ALL
    SELECT  3,  DATEADD(day, 60, @date),    NULL
)

-- End testdata

,tmp
as
(
    select  *
            ,ROW_NUMBER() OVER(order by startDate) as rowno
    from    yourTable
)

select  *
from    tmp t1
left join   tmp t2
    on t1.rowno = t2.rowno - 1
where   t1.endDate > t2.startDate

EDIT:
As for the updated question:

Just add a PARTITION BY clause to the ROW_NUMBER() query and alter the join.

-- Testdata
declare @date datetime = '2011-01-17'

;with yourTable(itemID, startDate, endDate, intervalID)
as
(
    SELECT  1,  NULL, @date, 1
    UNION ALL
    SELECT  2,  dateadd(day, 1, @date), DATEADD(day, 10, @date),1
    UNION ALL
    SELECT  3,  DATEADD(day, 60, @date),    NULL,   1
    UNION ALL
    SELECT  4,  NULL, @date, 2
    UNION ALL
    SELECT  5,  dateadd(day, -1, @date),    DATEADD(day, 10, @date),2
    UNION ALL
    SELECT  6,  DATEADD(day, 60, @date),    NULL,   2
)

-- End testdata

,tmp
as
(
    select  *
            ,ROW_NUMBER() OVER(partition by intervalID order by startDate) as rowno
    from    yourTable
)

select  *
from    tmp t1
left join   tmp t2
    on t1.rowno = t2.rowno - 1
    and t1.intervalID = t2.intervalID
where   t1.endDate > t2.startDate


问:
Azure DevOps Pipeline - Release API - Update Release Definition add and remove a templated stage
We have a Azure DevOps Pipeline Release Definition, and i am looking at putting in place some automation for a new 'Stage' to be created from a template when a pull request is triggered on branch x, and the stage to be removed when the branch is deleted. i will be using github actions for this.

The API doc's are not super easy to follow.

My question are:

is this possible, dose the API support making such adding and removing of stage's  to a _releaseDefinition ?

if so is there any examples on how to do this ?

Doc's
https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/update%20release?view=azure-devops-rest-5.1#releasedefinitionshallowreference

答:
The api you should use is Update-definition api:

```<code>PUT https://vsrm.dev.azure.com/{org name}/{project name}/_apis/release/definitions?api-version=5.1
</code>```

For the request body of adding stage/removing stage, it in fact only made changes into environments parameter:

One stage definition corresponds to one grey code block.

Adding stage: Add a template JSON code block of stage definition(the grey one display in my left screenshots). This code structure is fixed.

Removing stage: Remove the complete corresponding stage definition.

Here is the one complete stage definition sample:

```<code> {
            "id": -1,
            "name": "Stage 3",
            "rank": 3,
            "variables": {},
            "variableGroups": [],
            "preDeployApprovals": {
                "approvals": [
                    {
                        "rank": 1,
                        "isAutomated": true,
                        "isNotificationOn": false,
                        "id": 7
                    }
                ],
                "approvalOptions": {
                    "requiredApproverCount": null,
                    "releaseCreatorCanBeApprover": false,
                    "autoTriggeredAndPreviousEnvironmentApprovedCanBeSkipped": false,
                    "enforceIdentityRevalidation": false,
                    "timeoutInMinutes": 0,
                    "executionOrder": "beforeGates"
                }
            },
            "deployStep": {
                "id": 8
            },
            "postDeployApprovals": {
                "approvals": [
                    {
                        "rank": 1,
                        "isAutomated": true,
                        "isNotificationOn": false,
                        "id": 9
                    }
                ],
                "approvalOptions": {
                    "requiredApproverCount": null,
                    "releaseCreatorCanBeApprover": false,
                    "autoTriggeredAndPreviousEnvironmentApprovedCanBeSkipped": false,
                    "enforceIdentityRevalidation": false,
                    "timeoutInMinutes": 0,
                    "executionOrder": "afterSuccessfulGates"
                }
            },
            "deployPhases": [
                {
                    "deploymentInput": {
                        "parallelExecution": {
                            "parallelExecutionType": "none"
                        },
                        "agentSpecification": {
                            "identifier": "vs2017-win2016"
                        },
                        "skipArtifactsDownload": false,
                        "artifactsDownloadInput": {
                            "downloadInputs": []
                        },
                        "queueId": 247,
                        "demands": [],
                        "enableAccessToken": false,
                        "timeoutInMinutes": 0,
                        "jobCancelTimeoutInMinutes": 1,
                        "condition": "succeeded()",
                        "overrideInputs": {}
                    },
                    "rank": 1,
                    "phaseType": "agentBasedDeployment",
                    "name": "Agent job",
                    "refName": null,
                    "workflowTasks": []
                }
            ],
            "environmentOptions": {
                "emailNotificationType": "OnlyOnFailure",
                "emailRecipients": "release.environment.owner;release.creator",
                "skipArtifactsDownload": false,
                "timeoutInMinutes": 0,
                "enableAccessToken": false,
                "publishDeploymentStatus": true,
                "badgeEnabled": false,
                "autoLinkWorkItems": false,
                "pullRequestDeploymentEnabled": false
            },
            "demands": [],
            "conditions": [],
            "executionPolicy": {
                "concurrencyCount": 1,
                "queueDepthCount": 0
            },
            "schedules": [],
            "owner": {
        "displayName": "{user name}",
        "id": "{user id}",
        "isContainer": false,
        "uniqueName": "{creator account}",
        "url": "https://dev.azure.com/{org name}/"
      },
            "retentionPolicy": {
                "daysToKeep": 30,
                "releasesToKeep": 3,
                "retainBuild": true
            },
            "processParameters": {},
            "properties": {
                "BoardsEnvironmentType": {
                    "$type": "System.String",
                    "$value": "unmapped"
                },
                "LinkBoardsWorkItems": {
                    "$type": "System.String",
                    "$value": "False"
                }
            },
            "preDeploymentGates": {
                "id": 0,
                "gatesOptions": null,
                "gates": []
            },
            "postDeploymentGates": {
                "id": 0,
                "gatesOptions": null,
                "gates": []
            },
            "environmentTriggers": [],
            "badgeUrl": "https://vsrm.dev.azure.com/{org}/_apis/{project name}/Release/badge/3c3xxx6414512/2/3"
        },
</code>```

Here has some key parameters you need pay attention: id, owner, rank and conditions.

id: This is the stage id you specified to stage, its value must less than 1. Any value that less than 1 is okay here.

owner: This is required. Or you will receive the message that notify you the stage must has owner.

rank: The natural numbers greater than 1. Here I suggest you increment it based on other stages.

conditions: This is the one which you can configure which stage the current new one will depend on. The nutshell is it used to specify stage execution location of release.

When you updating release, you must pack and set the whole release definition as request body. Get the original one, add new customized stage definition part into it. Then update to api.

In fact, I suggest you do adding a stage with UI for test. Then go History tab of release definition page. Then choose Compare difference of three dots.

We provided you the difference of definition in the panel(left panel is the original, the right is updated), and you can clearly get what you should focus on to apply your idea.

Body:
The api you should use is Update-definition api:

PUT https://vsrm.dev.azure.com/{org name}/{project name}/_apis/release/definitions?api-version=5.1

For the request body of adding stage/removing stage, it in fact only made changes into environments parameter:

One stage definition corresponds to one grey code block.

Adding stage: Add a template JSON code block of stage definition(the grey one display in my left screenshots). This code structure is fixed.

Removing stage: Remove the complete corresponding stage definition.

Here is the one complete stage definition sample:

 {
            "id": -1,
            "name": "Stage 3",
            "rank": 3,
            "variables": {},
            "variableGroups": [],
            "preDeployApprovals": {
                "approvals": [
                    {
                        "rank": 1,
                        "isAutomated": true,
                        "isNotificationOn": false,
                        "id": 7
                    }
                ],
                "approvalOptions": {
                    "requiredApproverCount": null,
                    "releaseCreatorCanBeApprover": false,
                    "autoTriggeredAndPreviousEnvironmentApprovedCanBeSkipped": false,
                    "enforceIdentityRevalidation": false,
                    "timeoutInMinutes": 0,
                    "executionOrder": "beforeGates"
                }
            },
            "deployStep": {
                "id": 8
            },
            "postDeployApprovals": {
                "approvals": [
                    {
                        "rank": 1,
                        "isAutomated": true,
                        "isNotificationOn": false,
                        "id": 9
                    }
                ],
                "approvalOptions": {
                    "requiredApproverCount": null,
                    "releaseCreatorCanBeApprover": false,
                    "autoTriggeredAndPreviousEnvironmentApprovedCanBeSkipped": false,
                    "enforceIdentityRevalidation": false,
                    "timeoutInMinutes": 0,
                    "executionOrder": "afterSuccessfulGates"
                }
            },
            "deployPhases": [
                {
                    "deploymentInput": {
                        "parallelExecution": {
                            "parallelExecutionType": "none"
                        },
                        "agentSpecification": {
                            "identifier": "vs2017-win2016"
                        },
                        "skipArtifactsDownload": false,
                        "artifactsDownloadInput": {
                            "downloadInputs": []
                        },
                        "queueId": 247,
                        "demands": [],
                        "enableAccessToken": false,
                        "timeoutInMinutes": 0,
                        "jobCancelTimeoutInMinutes": 1,
                        "condition": "succeeded()",
                        "overrideInputs": {}
                    },
                    "rank": 1,
                    "phaseType": "agentBasedDeployment",
                    "name": "Agent job",
                    "refName": null,
                    "workflowTasks": []
                }
            ],
            "environmentOptions": {
                "emailNotificationType": "OnlyOnFailure",
                "emailRecipients": "release.environment.owner;release.creator",
                "skipArtifactsDownload": false,
                "timeoutInMinutes": 0,
                "enableAccessToken": false,
                "publishDeploymentStatus": true,
                "badgeEnabled": false,
                "autoLinkWorkItems": false,
                "pullRequestDeploymentEnabled": false
            },
            "demands": [],
            "conditions": [],
            "executionPolicy": {
                "concurrencyCount": 1,
                "queueDepthCount": 0
            },
            "schedules": [],
            "owner": {
        "displayName": "{user name}",
        "id": "{user id}",
        "isContainer": false,
        "uniqueName": "{creator account}",
        "url": "https://dev.azure.com/{org name}/"
      },
            "retentionPolicy": {
                "daysToKeep": 30,
                "releasesToKeep": 3,
                "retainBuild": true
            },
            "processParameters": {},
            "properties": {
                "BoardsEnvironmentType": {
                    "$type": "System.String",
                    "$value": "unmapped"
                },
                "LinkBoardsWorkItems": {
                    "$type": "System.String",
                    "$value": "False"
                }
            },
            "preDeploymentGates": {
                "id": 0,
                "gatesOptions": null,
                "gates": []
            },
            "postDeploymentGates": {
                "id": 0,
                "gatesOptions": null,
                "gates": []
            },
            "environmentTriggers": [],
            "badgeUrl": "https://vsrm.dev.azure.com/{org}/_apis/{project name}/Release/badge/3c3xxx6414512/2/3"
        },

Here has some key parameters you need pay attention: id, owner, rank and conditions.

id: This is the stage id you specified to stage, its value must less than 1. Any value that less than 1 is okay here.

owner: This is required. Or you will receive the message that notify you the stage must has owner.

rank: The natural numbers greater than 1. Here I suggest you increment it based on other stages.

conditions: This is the one which you can configure which stage the current new one will depend on. The nutshell is it used to specify stage execution location of release.

When you updating release, you must pack and set the whole release definition as request body. Get the original one, add new customized stage definition part into it. Then update to api.

In fact, I suggest you do adding a stage with UI for test. Then go History tab of release definition page. Then choose Compare difference of three dots.

We provided you the difference of definition in the panel(left panel is the original, the right is updated), and you can clearly get what you should focus on to apply your idea.


问:
Colour Changing Bouncing Ball
I'm working on a project to make an animation in pygame. The assignment is this:

Add 2 other balls to the screen (3 in total) that will all be different colors, different sizes and start in different directions. They will all bounce around continuously.

Hint: you will need to create all new variables for each ball

  i.e.  x2,y2, dx2, dy2

  and you will need to check each ball individually for hitting a wall and update the vertical and horizontal position of each ball individually.

Level 4 Challenge: when the balls hit the wall and the colors change to make each color randomly change.

Here is my code so far, I am using Python 3.7 on a Mac. The code so far has the first ball bouncing and staying the same color. I can't figure out how to make two more balls and have them change color each time they hit a wall. If someone could please help I literally cannot figure this out.

```<code>import pygame
import sys
pygame.init()

screensize = (800,600)
screen = pygame.display.set_mode(screensize,0)
pygame.display.set_caption("Animation Test")

WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)

screen.fill(WHITE)
pygame.display.update()

x = 100
y = 200
dx = 2
dy = 2
go = True
while go:
    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            go = False

    screen.fill(WHITE)

    x = x + dx
    y = y + dy
    Colour = BLUE

    if (x>=775):
            dx = -dx
    elif (x>=775):
        dx = -dx
    Colour = RED
</code>```

答:
Create a function (createball) which can crate a random ball. A ball is a tuple of x and y position, the movement vector dx, dy and the color ((x, y, dx, dy, color)). Create a certain number of ball (max_balls) with random positions (random.randint(a, b)) and random colors (random.choice(seq)):

radius = 25
color_list = [GREEN, BLUE, RED]

def createball():
    x = random.randint(radius, screensize[0]-radius)
    y = random.randint(radius, screensize[1]-radius)
    color = random.choice(color_list)
    return x, y, 2, 2, color
```

<p>Crate the 3 balls and store them to the variables as suggested in the assignment (<code>x2, y2, dx2, dy2</code>):</p>

<pre class="lang-py prettyprint-override"><code>x, y, dx, dy, color = createball()
x2, y2, dx2, dy2, color2 = createball()
x3, y3, dx3, dy3, color3 = createball()
</code>```

Create a function (moveball) which can move a ball, change there direction when the hit the bounds and change the color. Move the balls in the application loop:

def moveball(x, y, dx, dy, color):
    x, y = x + dx, y + dy
    if not radius < x < screensize[0]-radius:
        dx = -dx
        color = random.choice(color_list)
    if not radius < y < screensize[1]-radius:
        dy = -dy
        color = random.choice(color_list)
    return x, y, dx, dy, color

while run:

    # [...]

    x, y, dx, dy, color = moveball(x, y, dx, dy, color)
    x2, y2, dx2, dy2, color2 = moveball(x2, y2, dx2, dy2, color2)
    x3, y3, dx3, dy3, color3 = moveball(x3, y3, dx3, dy3, color3)
```

<p>See the example:</p>

<p><img src="https://i.stack.imgur.com/Bz0cu.gif" alt=""></p>

<pre class="lang-py prettyprint-override"><code>import pygame
import sys
import random

pygame.init()
screensize = (800,600)
screen = pygame.display.set_mode(screensize,0)
pygame.display.set_caption("Animation Test")
clock = pygame.time.Clock()

WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)

radius = 25
color_list = [GREEN, BLUE, RED]

def createball():
    x = random.randint(radius, screensize[0]-radius)
    y = random.randint(radius, screensize[1]-radius)
    color = random.choice(color_list)
    return x, y, 2, 2, color

def moveball(x, y, dx, dy, color):
    x, y = x + dx, y + dy
    if not radius < x < screensize[0]-radius:
        dx = -dx
        color = random.choice(color_list)
    if not radius < y < screensize[1]-radius:
        dy = -dy
        color = random.choice(color_list)
    return x, y, dx, dy, color

x, y, dx, dy, color = createball()
x2, y2, dx2, dy2, color2 = createball()
x3, y3, dx3, dy3, color3 = createball()

go = True
while go:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False

    x, y, dx, dy, color = moveball(x, y, dx, dy, color)
    x2, y2, dx2, dy2, color2 = moveball(x2, y2, dx2, dy2, color2)
    x3, y3, dx3, dy3, color3 = moveball(x3, y3, dx3, dy3, color3)

    screen.fill(WHITE)
    pygame.draw.circle(screen, color, (x, y), radius)
    pygame.draw.circle(screen, color2, (x2, y2), radius)
    pygame.draw.circle(screen, color3, (x3, y3), radius)
    pygame.display.flip()
</code>```

A bit more sophisticated approach with a ball class can be found at Use vector2 in pygame.

Title: Colour Changing Bouncing Ball

Body:
I'm working on a project to make an animation in pygame. The assignment is this:

Add 2 other balls to the screen (3 in total) that will all be different colors, different sizes and start in different directions. They will all bounce around continuously.

Hint: you will need to create all new variables for each ball

  i.e.  x2,y2, dx2, dy2

  and you will need to check each ball individually for hitting a wall and update the vertical and horizontal position of each ball individually.

Level 4 Challenge: when the balls hit the wall and the colors change to make each color randomly change.

Here is my code so far, I am using Python 3.7 on a Mac. The code so far has the first ball bouncing and staying the same color. I can't figure out how to make two more balls and have them change color each time they hit a wall. If someone could please help I literally cannot figure this out.

import pygame
import sys
pygame.init()

screensize = (800,600)
screen = pygame.display.set_mode(screensize,0)
pygame.display.set_caption("Animation Test")

WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)

screen.fill(WHITE)
pygame.display.update()

x = 100
y = 200
dx = 2
dy = 2
go = True
while go:
    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            go = False

    screen.fill(WHITE)

    x = x + dx
    y = y + dy
    Colour = BLUE

    if (x>=775):
            dx = -dx
    elif (x>=775):
        dx = -dx
    Colour = RED

Body:
Create a function (createball) which can crate a random ball. A ball is a tuple of x and y position, the movement vector dx, dy and the color ((x, y, dx, dy, color)). Create a certain number of ball (max_balls) with random positions (random.randint(a, b)) and random colors (random.choice(seq)):

radius = 25
color_list = [GREEN, BLUE, RED]

def createball():
    x = random.randint(radius, screensize[0]-radius)
    y = random.randint(radius, screensize[1]-radius)
    color = random.choice(color_list)
    return x, y, 2, 2, color

Crate the 3 balls and store them to the variables as suggested in the assignment (x2, y2, dx2, dy2):

x, y, dx, dy, color = createball()
x2, y2, dx2, dy2, color2 = createball()
x3, y3, dx3, dy3, color3 = createball()

Create a function (moveball) which can move a ball, change there direction when the hit the bounds and change the color. Move the balls in the application loop:

def moveball(x, y, dx, dy, color):
    x, y = x + dx, y + dy
    if not radius < x < screensize[0]-radius:
        dx = -dx
        color = random.choice(color_list)
    if not radius < y < screensize[1]-radius:
        dy = -dy
        color = random.choice(color_list)
    return x, y, dx, dy, color

while run:

    # [...]

    x, y, dx, dy, color = moveball(x, y, dx, dy, color)
    x2, y2, dx2, dy2, color2 = moveball(x2, y2, dx2, dy2, color2)
    x3, y3, dx3, dy3, color3 = moveball(x3, y3, dx3, dy3, color3)

See the example:

import pygame
import sys
import random

pygame.init()
screensize = (800,600)
screen = pygame.display.set_mode(screensize,0)
pygame.display.set_caption("Animation Test")
clock = pygame.time.Clock()

WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)

radius = 25
color_list = [GREEN, BLUE, RED]

def createball():
    x = random.randint(radius, screensize[0]-radius)
    y = random.randint(radius, screensize[1]-radius)
    color = random.choice(color_list)
    return x, y, 2, 2, color

def moveball(x, y, dx, dy, color):
    x, y = x + dx, y + dy
    if not radius < x < screensize[0]-radius:
        dx = -dx
        color = random.choice(color_list)
    if not radius < y < screensize[1]-radius:
        dy = -dy
        color = random.choice(color_list)
    return x, y, dx, dy, color

x, y, dx, dy, color = createball()
x2, y2, dx2, dy2, color2 = createball()
x3, y3, dx3, dy3, color3 = createball()

go = True
while go:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False

    x, y, dx, dy, color = moveball(x, y, dx, dy, color)
    x2, y2, dx2, dy2, color2 = moveball(x2, y2, dx2, dy2, color2)
    x3, y3, dx3, dy3, color3 = moveball(x3, y3, dx3, dy3, color3)

    screen.fill(WHITE)
    pygame.draw.circle(screen, color, (x, y), radius)
    pygame.draw.circle(screen, color2, (x2, y2), radius)
    pygame.draw.circle(screen, color3, (x3, y3), radius)
    pygame.display.flip()

A bit more sophisticated approach with a ball class can be found at Use vector2 in pygame.


问:
Azure DevOps Project pipeline not able to access NuGet package from Artifact Feed in different Project
Updated 20-Feb-2020

Summary

Azure DevOps pipeline build not able to find NuGet package from our private feed under Artifacts.

Our Azure DevOps environment

In Azure, we have our company "space": dev.azure.com/OurCompany

Under that, we have multiple Projects, so for example, imagine these three:

Green: this holds applications of a certain type

Blue: this holds applications of a different type

Red: this holds our "common" helper code

RED

RED holds all our common helper code are DLLs consumed by applications in GREEN and BLUE.  These are made available as NuGet packages.

Under RED's Artifacts, we see an "organisational scoped feed" called "OurCompany".  We understood that we couldn't use this because these NuGet packages need to be available to everyone in OurCompany, which means not only on Azure, but also on our DeskTop machines in our Corporate network (where we run Visual Studio).  The "organisational scoped feed" I don't think is exposed to our Corporate Network.

We therefore created a new Feed under RED's Artifacts.  When I view Permissions, I see the following entries:

{me} : (Owner)

[OurCompany]\Project Collection Adminstrators : (Owner)

[RED]\Project Administrators : (Owner)

RED Build Service (OurCompany) : (Contributor)

Project Collection Build Service (OurCompany) : (Contributor)

[RED]\Contributors (Contributor)

Corporate

So, back in Corporate, we add the NuGet package feed to our Visual Studio and it can then pull the NuGet packages down from Azure.

GREEN and BLUE

In here we have our products.  We create a build Pipeline and we add a NuGet restore step:

```<code>- task: NuGetCommand@2
  displayName: 'Restore for Our Application'
  inputs:
    command: 'restore'
    restoreSolution: '**/*.sln'
    feedsToUse: 'select'
    vstsFeed: '{Guid1}/{Guid2}'
</code>```

The two Guids were filled in when we picket the Azure Artifacts feed from the drop-down.

GREEN or BLUE NuGet Restore Failure

So this is where we run into our issue.  When the NuGet restore step executes, it fails with the following message:

```<code>Unable to find version 'nnnn.n.n' of package 'TheNuGetPackage'.
</code>```

The log output is vast, but the salient lines appear to be:

```<code>2020-02-18T18:36:35.2838118Z [command]C:\hostedtoolcache\windows\NuGet\5.4.0\x64\nuget.exe sources Add -NonInteractive -Name {Guid2} -Source https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json
-ConfigFile d:\a\1\Nuget\tempNuGet_356.config 2020-02-18T18:36:35.7513495Z Package source with Name: {Guid2} added successfully. 2020-02-18T18:36:41.1671856Z     [CredentialProvider.183638]Command-line v0.1.20+a5d37185a1a95acb4f0g997b9c23cab99508: "d:\a\_tasks\NuGetCommand_333b11bd-d341-40d9-bdbd-b32d5ce6f23b\2.164.0\CredentialProviderV2\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe"
-Plugin 2020-02-18T18:36:41.1673979Z     [CredentialProvider]Handling 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 3 - Payload: {"Uri":"https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json","IsRetry":false,"IsNonInteractive":true,"CanShowDialog":true} 2020-02-18T18:36:41.1674299Z     [CredentialProvider]Handling auth request, Uri: https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json, IsRetry: False, IsNonInteractive: True, CanShowDialog: True 2020-02-18T18:36:41.1674465Z     [CredentialProvider]URI: https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json 2020-02-18T18:36:41.1674818Z     [CredentialProvider]Skipping NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoint.VstsBuildTaskServiceEndpointCredentialProvider, cannot provide credentials for https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json 2020-02-18T18:36:41.1675261Z     [CredentialProvider]VstsBuildTaskCredentialProvider - https://dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1675425Z     [CredentialProvider]VstsBuildTaskCredentialProvider - https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1675722Z    [CredentialProvider]VstsBuildTaskCredentialProvider - https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1676021Z    [CredentialProvider]VstsBuildTaskCredentialProvider - https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1676161Z    [CredentialProvider]VstsBuildTaskCredentialProvider - Matched prefix: https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1676330Z    [CredentialProvider]VstsBuildTaskCredentialProvider - Found credentials for endpoint https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json 2020-02-18T18:36:41.1680820Z   https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json: Unable to load the service index for source https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json. 2020-02-18T18:36:41.1680996Z   Response status code does not indicate success: 404 (Not Found - VS800075: The project with id 'vstfs:///Classification/TeamProject/{Guid1}' does not exist, or you do not have permission to access it. (DevOps Activity ID: 0628EDE7-6E7E-465D-A6AE-7B6B0AA065D2)).
</code>```

This looks like a permissions thing to me.  But what seems odd is that the Artifact Feed in RED was discoverable when creating the Pipeline Build YAML when we then don't have permissions to use it.

I did try adding permissions to the Feed in RED.  Clicking on the "Add users/groups".  I found the following and added them as either Reader or Contributor, but with no success.

[GREEN]\ Green Team

GREEN Build Services

So:

Am I going about this the wrong way?  If so, what ought I be doing (I thought I'd followed the Azure DevOps instructions fairly closely)

Am I going about this the right way?  If so, what have I missed?

Update #1

Verbose error message from Restore step

https://api.nuget.org/v3/index.json: Package 'Package1.nnnn.n.n' is
  not found on source 'https://api.nuget.org/v3/index.json'.

  https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json:
  Unable to load the service index for source
  https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json.
  Response status code does not indicate success: 404 (Not Found -
  VS800075: The project with id
  'vstfs:///Classification/TeamProject/{Guid1}' does not exist, or you
  do not have permission to access it. (DevOps Activity ID: {Guid})).

答:
Azure DevOps Project pipeline not able to access Artifact Feed in different project

I think you are going the right ways. There is known issue about the project scope feed.

As the document Package permissions in Azure Pipelines stated:

To use packages from a feed in Azure Pipelines, the appropriate build
  identity must have permission to your feed. By default, the Project
  Collection Build Service is a Contributor. If you've changed your
  builds to run at project scope, you'll need to add the project-level
  build identity as a Reader or Contributor, as desired. The
  project-level build identity is named as follows:

[Project name] Build Service ([Organization name]) (e.g. FabrikamFiber
  Build Service (codesharing-demo))

You could check this thread for some more details.

Hope this helps.

Body:
Updated 20-Feb-2020

Summary

Azure DevOps pipeline build not able to find NuGet package from our private feed under Artifacts.

Our Azure DevOps environment

In Azure, we have our company "space": dev.azure.com/OurCompany

Under that, we have multiple Projects, so for example, imagine these three:

Green: this holds applications of a certain type

Blue: this holds applications of a different type

Red: this holds our "common" helper code

RED

RED holds all our common helper code are DLLs consumed by applications in GREEN and BLUE.  These are made available as NuGet packages.

Under RED's Artifacts, we see an "organisational scoped feed" called "OurCompany".  We understood that we couldn't use this because these NuGet packages need to be available to everyone in OurCompany, which means not only on Azure, but also on our DeskTop machines in our Corporate network (where we run Visual Studio).  The "organisational scoped feed" I don't think is exposed to our Corporate Network.

We therefore created a new Feed under RED's Artifacts.  When I view Permissions, I see the following entries:

{me} : (Owner)

[OurCompany]\Project Collection Adminstrators : (Owner)

[RED]\Project Administrators : (Owner)

RED Build Service (OurCompany) : (Contributor)

Project Collection Build Service (OurCompany) : (Contributor)

[RED]\Contributors (Contributor)

Corporate

So, back in Corporate, we add the NuGet package feed to our Visual Studio and it can then pull the NuGet packages down from Azure.

GREEN and BLUE

In here we have our products.  We create a build Pipeline and we add a NuGet restore step:

- task: NuGetCommand@2
  displayName: 'Restore for Our Application'
  inputs:
    command: 'restore'
    restoreSolution: '**/*.sln'
    feedsToUse: 'select'
    vstsFeed: '{Guid1}/{Guid2}'

The two Guids were filled in when we picket the Azure Artifacts feed from the drop-down.

GREEN or BLUE NuGet Restore Failure

So this is where we run into our issue.  When the NuGet restore step executes, it fails with the following message:

Unable to find version 'nnnn.n.n' of package 'TheNuGetPackage'.

The log output is vast, but the salient lines appear to be:

2020-02-18T18:36:35.2838118Z [command]C:\hostedtoolcache\windows\NuGet\5.4.0\x64\nuget.exe sources Add -NonInteractive -Name {Guid2} -Source https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json
-ConfigFile d:\a\1\Nuget\tempNuGet_356.config 2020-02-18T18:36:35.7513495Z Package source with Name: {Guid2} added successfully. 2020-02-18T18:36:41.1671856Z     [CredentialProvider.183638]Command-line v0.1.20+a5d37185a1a95acb4f0g997b9c23cab99508: "d:\a\_tasks\NuGetCommand_333b11bd-d341-40d9-bdbd-b32d5ce6f23b\2.164.0\CredentialProviderV2\plugins\netfx\CredentialProvider.Microsoft\CredentialProvider.Microsoft.exe"
-Plugin 2020-02-18T18:36:41.1673979Z     [CredentialProvider]Handling 'Request' 'GetAuthenticationCredentials'. Time elapsed in ms: 3 - Payload: {"Uri":"https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json","IsRetry":false,"IsNonInteractive":true,"CanShowDialog":true} 2020-02-18T18:36:41.1674299Z     [CredentialProvider]Handling auth request, Uri: https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json, IsRetry: False, IsNonInteractive: True, CanShowDialog: True 2020-02-18T18:36:41.1674465Z     [CredentialProvider]URI: https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json 2020-02-18T18:36:41.1674818Z     [CredentialProvider]Skipping NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoint.VstsBuildTaskServiceEndpointCredentialProvider, cannot provide credentials for https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json 2020-02-18T18:36:41.1675261Z     [CredentialProvider]VstsBuildTaskCredentialProvider - https://dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1675425Z     [CredentialProvider]VstsBuildTaskCredentialProvider - https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1675722Z    [CredentialProvider]VstsBuildTaskCredentialProvider - https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1676021Z    [CredentialProvider]VstsBuildTaskCredentialProvider - https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1676161Z    [CredentialProvider]VstsBuildTaskCredentialProvider - Matched prefix: https://pkgs.dev.azure.com/OurCompany/ 2020-02-18T18:36:41.1676330Z    [CredentialProvider]VstsBuildTaskCredentialProvider - Found credentials for endpoint https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json 2020-02-18T18:36:41.1680820Z   https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json: Unable to load the service index for source https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json. 2020-02-18T18:36:41.1680996Z   Response status code does not indicate success: 404 (Not Found - VS800075: The project with id 'vstfs:///Classification/TeamProject/{Guid1}' does not exist, or you do not have permission to access it. (DevOps Activity ID: 0628EDE7-6E7E-465D-A6AE-7B6B0AA065D2)).

This looks like a permissions thing to me.  But what seems odd is that the Artifact Feed in RED was discoverable when creating the Pipeline Build YAML when we then don't have permissions to use it.

I did try adding permissions to the Feed in RED.  Clicking on the "Add users/groups".  I found the following and added them as either Reader or Contributor, but with no success.

[GREEN]\ Green Team

GREEN Build Services

So:

Am I going about this the wrong way?  If so, what ought I be doing (I thought I'd followed the Azure DevOps instructions fairly closely)

Am I going about this the right way?  If so, what have I missed?

Update #1

Verbose error message from Restore step

https://api.nuget.org/v3/index.json: Package 'Package1.nnnn.n.n' is
  not found on source 'https://api.nuget.org/v3/index.json'.

  https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json:
  Unable to load the service index for source
  https://pkgs.dev.azure.com/OurCompany/{Guid1}/_packaging/{Guid2}/nuget/v3/index.json.
  Response status code does not indicate success: 404 (Not Found -
  VS800075: The project with id
  'vstfs:///Classification/TeamProject/{Guid1}' does not exist, or you
  do not have permission to access it. (DevOps Activity ID: {Guid})).


问:
xml Error in Android Studio
android studio

I just make a new project and it doesn't work.
Look at the link. Some of files like 'colors.xml', there is a problem that the files are made that way.
What can I do?

答: You must synchronize your project first once you created a new project to add those dependencies that validate the codes including the Layout Files. The synchronize button is at the right top of the Android Studio.</p>

Title: xml Error in Android Studio


问:
determine if string has unique characters
The  problem asks to "implement an algorithm to determine if a string has all unique character.

I saw the solution, but don't quite understand.

```<code>public boolean isUniqueChars(String str) {
    if (str.length() > 256) return false;
    boolean[] char_set = new boolean[256];
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i);
        if (char_set[val])
            return false;
        char_set[val] = true;
    }
    return true;
}
</code>```

Do we not use parseInt or (int) converter in front of the code? (Will str.charAt[i] be automatically changed to int?)
What does boolean[] char set=new boolean[256] mean?
Why do we need to set char_set[val]=true?

答:
```<code>public class CheckStringUniqueChars {

    public static boolean checkUnique(String str) {
        int i=0,j=str.length()-1;
        while(i<j) {
            if(str.charAt(i) == str.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}
</code>```

Body:
The  problem asks to "implement an algorithm to determine if a string has all unique character.

I saw the solution, but don't quite understand.

public boolean isUniqueChars(String str) {
    if (str.length() > 256) return false;
    boolean[] char_set = new boolean[256];
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i);
        if (char_set[val])
            return false;
        char_set[val] = true;
    }
    return true;
}

Do we not use parseInt or (int) converter in front of the code? (Will str.charAt[i] be automatically changed to int?)
What does boolean[] char set=new boolean[256] mean?
Why do we need to set char_set[val]=true?


问:
how to get correct ClientID
update:
asp.net

```<code><asp:RadioButtonList runat="server" ID="rbl" RepeatDirection="Horizontal">
    <asp:ListItem Text="None" Value="0" Selected="True" Enabled="true" />
    <asp:ListItem Text="Float" Value="1" Selected="False" Enabled="true" />
    <asp:ListItem Text="Float1" Value="2" Selected="False" Enabled="true" />
    <asp:ListItem Text="Center" Value="3" Selected="False" Enabled="false" />
</asp:RadioButtonList>
</code>```

when i view the source this is what it is rendering:

```<code>$('#ctl00_ctl00_ContentMain_rbl').hover(
    function (){
        $('#div1').dialog({title: "some title"});
        $('#div1').dialog('open');
    }
);
</code>```

the correct clientid is: ctl00_ctl00_ContentMain_rbl_0, ctl00_ctl00_ContentMain_rbl_1, ctl00_ctl00_ContentMain_rbl_2

the code does not work and it did not give me the correct ClientID name when i try to read it... what is the other way round for this problem, define class name ???

```<code>   $('#<%= rbl.ClientID %>').hover(
            function (){
                $('#div1').dialog({title: "Float Images Left"});
                $('#div1').dialog('open');
            }            );
</code>```

答:
Yes, the easiest way will be defining class to all components you want to find with jQuery.

Another way is using the attribute ends with selector:

```<code>$('[id$="_rbl"]').hover( // Etc.
</code>```

But it can cause problems if you have another rbl inside another container.

Remember that your items inside the RadioButtonList will be inputs, then you can do:

```<code>$('[id$="_rbl"] input:enabled').hover( // Etc.
</code>```

So, if you define a class for your RadioButtonList:

```<code>$(".myclass input:enabled").hover( // Etc.
</code>```

Title: how to get correct ClientID

Body:
update:
asp.net

<asp:RadioButtonList runat="server" ID="rbl" RepeatDirection="Horizontal">
    <asp:ListItem Text="None" Value="0" Selected="True" Enabled="true" />
    <asp:ListItem Text="Float" Value="1" Selected="False" Enabled="true" />
    <asp:ListItem Text="Float1" Value="2" Selected="False" Enabled="true" />
    <asp:ListItem Text="Center" Value="3" Selected="False" Enabled="false" />
</asp:RadioButtonList>

when i view the source this is what it is rendering:

$('#ctl00_ctl00_ContentMain_rbl').hover(
    function (){
        $('#div1').dialog({title: "some title"});
        $('#div1').dialog('open');
    }
);

the correct clientid is: ctl00_ctl00_ContentMain_rbl_0, ctl00_ctl00_ContentMain_rbl_1, ctl00_ctl00_ContentMain_rbl_2

the code does not work and it did not give me the correct ClientID name when i try to read it... what is the other way round for this problem, define class name ???

   $('#<%= rbl.ClientID %>').hover(
            function (){
                $('#div1').dialog({title: "Float Images Left"});
                $('#div1').dialog('open');
            }            );

Body:
Yes, the easiest way will be defining class to all components you want to find with jQuery.

Another way is using the attribute ends with selector:

$('[id$="_rbl"]').hover( // Etc.

But it can cause problems if you have another rbl inside another container.

Remember that your items inside the RadioButtonList will be inputs, then you can do:

$('[id$="_rbl"] input:enabled').hover( // Etc.

So, if you define a class for your RadioButtonList:

$(".myclass input:enabled").hover( // Etc.


问:
Protractor, how to test user accounts?
I am wondering what's the best approach is regarding end-to-end testing. If I understand it correctly the idea end-to-end testing is to cover user stories and test them in automatic manner. For example, using Protractor for Angular.js application.

In my current project you are capable to create user accounts and login in. How does this work? Would you use a specifically prepared database to test logging into an account. Also what about the registration process. How should this be tested? Are their any best practices regarding this?

答:
In my opinion there are two approaches to this problem:

Make your tests point to a real database that is a copy of your production environment one. This will make tests check if your database is properly accessed and data is returned as you expect. This is a possibility but not the correct to me as e2e testing should check the client frontend experience and not how the app is leaning on the backend part.

Make use of a mock backend. A mock backend is kind of a "fake server" that you can develop at client side to return the information you need to make your application work. I think this is the correct approach as you focus on making your APP work regardless of the server possible issues.

You can see an example in this tutorial:
https://blog.cloudboost.io/building-your-first-tests-for-angular5-with-protractor-a48dfc225a75

To be more concrete, in this file:
https://github.com/shootermv/protractor-tutorial/blob/master/src/app/_helpers/fake-backend.ts

Greetings.

Title: Protractor, how to test user accounts?


问:
What is the time complexity performance of Scala's Vector data structure?
I know that most of the Vector methods are effectively O(1) (constant time) because of the tree they use, but I cannot find any information on the contains method. My first thought is that it would have to be O(n) to check all the elements but I am not sure.

答:
Answering the question in the title, performance characteristics (2.13 docs version) of basic operations head, tail, apply, update, prepend, append, insert are all listed as eC for Vector:

eC The operation takes effectively constant time, but this might depend on some assumptions such as maximum length of a vector or distribution of hash keys.

You are correct contains is O(N), as there is no hashing or nothing else that would avoid the need to compare with all items. Still, if you want to be sure, it is best to check the implementation.

As finding the correct implementation in the library sources can be difficult because of many traits and overrides used to implement the containers, the best way to check this is the debugger. Use a code like:

```<code>val v = Vector(0, 1, 2)
v.contains(1)
</code>```

Use the debugger to step into v.contains and the source you will see is:

```<code>  def contains[A1 >: A](elem: A1): Boolean = exists (_ == elem)
</code>```

If you are still not convinced at this point, some more "step into" will lead you to:

```<code>  def exists(p: A => Boolean): Boolean = {
    var res = false
    while (!res && hasNext) res = p(next())
    res
  }
</code>```

Body:
Answering the question in the title, performance characteristics (2.13 docs version) of basic operations head, tail, apply, update, prepend, append, insert are all listed as eC for Vector:

eC The operation takes effectively constant time, but this might depend on some assumptions such as maximum length of a vector or distribution of hash keys.

You are correct contains is O(N), as there is no hashing or nothing else that would avoid the need to compare with all items. Still, if you want to be sure, it is best to check the implementation.

As finding the correct implementation in the library sources can be difficult because of many traits and overrides used to implement the containers, the best way to check this is the debugger. Use a code like:

val v = Vector(0, 1, 2)
v.contains(1)

Use the debugger to step into v.contains and the source you will see is:

  def contains[A1 >: A](elem: A1): Boolean = exists (_ == elem)

If you are still not convinced at this point, some more "step into" will lead you to:

  def exists(p: A => Boolean): Boolean = {
    var res = false
    while (!res && hasNext) res = p(next())
    res
  }


问:
How to use a a library module in a front-end external javascript file?
Situation:

I have a server side running with express.js and there I get data from SQL database. I would like to show this data to the client side, by sending it to the client.

In the front-end, I need to take this data and make it into a chart. It is possible to do it with the  tag in the HTML and include the Plotly library, which I want to use. However, I would like this operation to be done in a separate file, an external JS script for client. This avoids hard-to-read code in the HTML.

The problem is, how can I import Plotly to the external front-end file and use it?

答:
I hope I understood your need correctly :

One simple option would be to include both of your script in your html related document with the one required by the second one first :

...

<script src="path of your script where you use ploty"></script>
```

PS:

Also just a proposition but did you thing about importing Ploty in your js backend and use it in your front-end ? or with post/get or with socket ?

Body:
I hope I understood your need correctly :

One simple option would be to include both of your script in your html related document with the one required by the second one first :

...
<script src="path script 1" />
<script src="path script 2 depending on script 1" />

so in your case using CDN :

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="path of your script where you use ploty"></script>

PS:

Also just a proposition but did you thing about importing Ploty in your js backend and use it in your front-end ? or with post/get or with socket ?


问:
Inheritance base class reference C#
```<code>class Base
    {
        //...
        public int i = 5;
    }

class Drifted : Base
{
    //...
    public int b = 10;
}

Base ObjectOrReference = new Drifted();
</code>```

So Base ObjectOrReference;is reference to the base type.
When we write Base ObjectOrReference = new Drifted(); it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference object?"

答:
Yes, ObjectOrReference is an object and a valid object.

It is an object of Drifted Type. It is a basic concept of Object Oriented Programming that  pointer/ref of base class(ObjectOrReference in your case) can hold/refer to object of it's derived classes(Drifted in your case) thats why it is not an error and a valid object of Drifted type

Title: Inheritance base class reference C#

Body:
class Base
    {
        //...
        public int i = 5;
    }

class Drifted : Base
{
    //...
    public int b = 10;
}

Base ObjectOrReference = new Drifted();

So Base ObjectOrReference;is reference to the base type.
When we write Base ObjectOrReference = new Drifted(); it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference object?"


问:
CPLEX vs Constraint Programming Solution for a linearly constrained MIP with a nonlinear objective(division)
I am trying to solve an MIP with a non-linear objective such as sum(a(i)*x(i))/sum(b(i)*x(i)) where a(i) and b(i) are parameters. Since CPLEX cannot extract this expression, I tried using CP.

However, I have constraint stating that the decision variable x(i) should be a multiplier of 2.5, therefore a float. Since CP cannot handle floats, I set x to be an integer, and implied to be multiplier of 25. In every other constraint and expression I divided x by 10, so that the calculations remained the same.

First, I solved the model with the multiplier 5, I got a solution with a very small gap, which is fine. When I changed the multiplier to 25, the model cannot terminated within 2 hours (stucked with a gap of 90%). I believe this happened due to scaling, but still cannot figure it out, since I am not familiar with the CP algorithm.

I am still working to linearize the oblective but, any suggestion on both CPLEX and CP engine solutions will be highly appreciated.
Thanks in advance.

答:
Thank you @Alex Fleischer. I tried what you suggested. My decision variable's index is a tuple therefore I wrote a code like below:

```<code>dvar int scalex[1..card(hm)] in 0..10000;
int scale=100;

dexpr float A[1..card(hm)]=[];
int max_range=card(hm);

execute{
for (var i=1;i<=max_range;i++){
    A[i]==scalex[i]/scale;
}
}
</code>```

I received Scripting runtime error: cannot convert to a number, "[a IloNumVar]" error. How can I fix this?
Thank you.

Body:
Thank you @Alex Fleischer. I tried what you suggested. My decision variable's index is a tuple therefore I wrote a code like below:

dvar int scalex[1..card(hm)] in 0..10000;
int scale=100;

dexpr float A[1..card(hm)]=[];
int max_range=card(hm);

execute{
for (var i=1;i<=max_range;i++){
    A[i]==scalex[i]/scale;
}
}

I received Scripting runtime error: cannot convert to a number, "[a IloNumVar]" error. How can I fix this?
Thank you.


问:
Change Collection Propery When Nested Collection Property Changes
Full solution: https://github.com/fallingsappy/portfolio/tree/master/DDrop

I have three collections. First one:

```<code>public class Series : INotifyPropertyChanged
{
    private ObservableCollection<DropPhoto> _dropPhotosSeries;
    public ObservableCollection<DropPhoto> DropPhotosSeries
    {
        get
        {
            return _dropPhotosSeries;
        }
        set
        {
            _dropPhotosSeries = value;
            OnPropertyChanged(new PropertyChangedEventArgs("DropPhotosSeries"));
        }
    }
    private bool _canDrawPlot;
    public bool CanDrawPlot
    {
        get
        {
            return _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters != null).ToList().Count > 1 && _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters == null).ToList().Count == 0;
        }
        set
        {
            _canDrawPlot = value;
            OnPropertyChanged(new PropertyChangedEventArgs("CanDrawPlot"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}
</code>```

Second:

```<code>public class DropPhoto : INotifyPropertyChanged
{
    private Drop _drop;
    public Drop Drop
    {
        get
        {
            return _drop;
        }
        set
        {
            _drop = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Drop"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}
</code>```

Last:

```<code>public class Drop : INotifyPropertyChanged
{
    private double? _radiusInMeters;
    public double? RadiusInMeters
    {
        get
        {
            return _radiusInMeters;
        }
        set
        {
            _radiusInMeters = value;
            OnPropertyChanged(new PropertyChangedEventArgs("RadiusInMeters"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}
</code>```

I want to update (invoke?) property CanDrawPlot every time something is happens to two other collection (Drop and DropPhot.cs). For example, if DropPhotosSeries.Count goes lower then 2 I need to change CanDrawPlot to false. CanDrawPlot should update UI. Here is the XAML:

```<code>                <TabItem IsEnabled="{Binding CurrentSeries.CanDrawPlot, ElementName=AppMainWindow,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" x:Name="SingleSeriesPlotTabItem" Header="График" >
                    <uc:ScatterPlot x:Name="SingleSeriesPlot" User="{Binding User, ElementName=AppMainWindow}" ParticularSeriesIndex="{Binding ParticularSeriesIndex, ElementName=AppMainWindow}"/>
                </TabItem>
</code>```

CurrentSeries is instantiated in MainWindowXaml.cs:

```<code>public static readonly DependencyProperty CurrentSeriesProperty = DependencyProperty.Register("CurrentSeries", typeof(Series), typeof(MainWindow));
public Series CurrentSeries
{
    get { return (Series)GetValue(CurrentSeriesProperty); }
    set
    {
        SetValue(CurrentSeriesProperty, value);
    }
}
</code>```

---------------UPDATE---------------

I changed my code accordingly to Rob's answer:

```<code>public class Series : INotifyPropertyChanged
{
    public Series()
    {
        _dropPhotosSeries = new ObservableCollection<DropPhoto>();
        _dropPhotosSeries.CollectionChanged += _dropPhotosSeries_CollectionChanged;
    }
     private void _dropPhotosSeries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(nameof(CanDrawPlot)));
    }

    private bool _canDrawPlot;
    public bool CanDrawPlot
    {
        get
        {
            return _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters != null).ToList().Count > 1 && _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters == null).ToList().Count == 0;
        }
        set
        {
            _canDrawPlot = value;
            OnPropertyChanged(new PropertyChangedEventArgs("CanDrawPlot"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}
</code>```

Now CanDrawPlot correctly notifies changes in DropPhoto Collection. But I need to invoke it also by changes in inner Drop class of DropPhotoSeries. Here what i did:

```<code>public class Drop : INotifyPropertyChanged
{
    Series _series;
    public Drop(Series series)
    {
        _series = series;
    }

    private double? _radiusInMeters;
    public double? RadiusInMeters
    {
        get
        {
            return _radiusInMeters;
        }
        set
        {
            _radiusInMeters = value;
            OnPropertyChanged(new PropertyChangedEventArgs(nameof(_series)));
            OnPropertyChanged(new PropertyChangedEventArgs("RadiusInMeters"));
        }
    }
}
</code>```

its not working, what's wrong?

答:
You need to hook up to CollectionChanged event of the ObservableCollection and in there you have to raise PropertyChanged for CanDrawPlot.

EXAMPLE:

Add constructor to the Series class and in the constructor instantiate the observable collection and subscribe to the CollectionChanged event.

```<code>public Series()
{
    _dropPhotosSeries = new ObservableCollection<DropPhoto>();
    _dropPhotosSeries.CollectionChanged += _dropPhotosSeries_CollectionChanged;
}

private void _dropPhotosSeries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    OnPropertyChanged(new PropertyChangedEventArgs(nameof(CanDrawPlot)));
}
</code>```

Body:
Full solution: https://github.com/fallingsappy/portfolio/tree/master/DDrop

I have three collections. First one:

public class Series : INotifyPropertyChanged
{
    private ObservableCollection<DropPhoto> _dropPhotosSeries;
    public ObservableCollection<DropPhoto> DropPhotosSeries
    {
        get
        {
            return _dropPhotosSeries;
        }
        set
        {
            _dropPhotosSeries = value;
            OnPropertyChanged(new PropertyChangedEventArgs("DropPhotosSeries"));
        }
    }
    private bool _canDrawPlot;
    public bool CanDrawPlot
    {
        get
        {
            return _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters != null).ToList().Count > 1 && _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters == null).ToList().Count == 0;
        }
        set
        {
            _canDrawPlot = value;
            OnPropertyChanged(new PropertyChangedEventArgs("CanDrawPlot"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}

Second:

public class DropPhoto : INotifyPropertyChanged
{
    private Drop _drop;
    public Drop Drop
    {
        get
        {
            return _drop;
        }
        set
        {
            _drop = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Drop"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}

Last:

public class Drop : INotifyPropertyChanged
{
    private double? _radiusInMeters;
    public double? RadiusInMeters
    {
        get
        {
            return _radiusInMeters;
        }
        set
        {
            _radiusInMeters = value;
            OnPropertyChanged(new PropertyChangedEventArgs("RadiusInMeters"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}

I want to update (invoke?) property CanDrawPlot every time something is happens to two other collection (Drop and DropPhot.cs). For example, if DropPhotosSeries.Count goes lower then 2 I need to change CanDrawPlot to false. CanDrawPlot should update UI. Here is the XAML:

                <TabItem IsEnabled="{Binding CurrentSeries.CanDrawPlot, ElementName=AppMainWindow,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" x:Name="SingleSeriesPlotTabItem" Header="График" >
                    <uc:ScatterPlot x:Name="SingleSeriesPlot" User="{Binding User, ElementName=AppMainWindow}" ParticularSeriesIndex="{Binding ParticularSeriesIndex, ElementName=AppMainWindow}"/>
                </TabItem>

CurrentSeries is instantiated in MainWindowXaml.cs:

public static readonly DependencyProperty CurrentSeriesProperty = DependencyProperty.Register("CurrentSeries", typeof(Series), typeof(MainWindow));
public Series CurrentSeries
{
    get { return (Series)GetValue(CurrentSeriesProperty); }
    set
    {
        SetValue(CurrentSeriesProperty, value);
    }
}

---------------UPDATE---------------

I changed my code accordingly to Rob's answer:

public class Series : INotifyPropertyChanged
{
    public Series()
    {
        _dropPhotosSeries = new ObservableCollection<DropPhoto>();
        _dropPhotosSeries.CollectionChanged += _dropPhotosSeries_CollectionChanged;
    }
     private void _dropPhotosSeries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(nameof(CanDrawPlot)));
    }

    private bool _canDrawPlot;
    public bool CanDrawPlot
    {
        get
        {
            return _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters != null).ToList().Count > 1 && _dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters == null).ToList().Count == 0;
        }
        set
        {
            _canDrawPlot = value;
            OnPropertyChanged(new PropertyChangedEventArgs("CanDrawPlot"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}

Now CanDrawPlot correctly notifies changes in DropPhoto Collection. But I need to invoke it also by changes in inner Drop class of DropPhotoSeries. Here what i did:

public class Drop : INotifyPropertyChanged
{
    Series _series;
    public Drop(Series series)
    {
        _series = series;
    }

    private double? _radiusInMeters;
    public double? RadiusInMeters
    {
        get
        {
            return _radiusInMeters;
        }
        set
        {
            _radiusInMeters = value;
            OnPropertyChanged(new PropertyChangedEventArgs(nameof(_series)));
            OnPropertyChanged(new PropertyChangedEventArgs("RadiusInMeters"));
        }
    }
}

its not working, what's wrong?

Body:
You need to hook up to CollectionChanged event of the ObservableCollection and in there you have to raise PropertyChanged for CanDrawPlot.

EXAMPLE:

Add constructor to the Series class and in the constructor instantiate the observable collection and subscribe to the CollectionChanged event.

public Series()
{
    _dropPhotosSeries = new ObservableCollection<DropPhoto>();
    _dropPhotosSeries.CollectionChanged += _dropPhotosSeries_CollectionChanged;
}

private void _dropPhotosSeries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    OnPropertyChanged(new PropertyChangedEventArgs(nameof(CanDrawPlot)));
}


问:
How to deploy next.js 9 to aws lambda
I am developing a project with next.js9. I have some problems and questions. I would like to deploy my next.js 9 project to AWS lambda.

official next.js 9 doc tell me "each page in the pages directory becomes a serverless lambda." Above library is not working like doc. How can I deploy from each page to each lambda?

What is reasonable solution to deployment? please someone who use nextjs 9 in production level help me.

I am using this library https://github.com/danielcondemarin/serverless-next.js.
it's working well. but all options are fixed. I would like to deploy my project to Tokyo region. but I have no idea how to change region. always deploy to N. virginia region. I already checked doc but I think they don't have options. and test like this yml file.

serverless.yml

```<code>myNextApplication:
  component: serverless-next.js
region: ap-northeast-1
</code>```

but it was not working. if someone know how to change region with serverless-next.js. Please help me.

Thank you in advance

答:
There is a webpack plugin, that can help next-aws-lambda-webpack-plugin.

This plugin generate for each page a directory with the serverless code of the Next.JS

This plugin do not use Serverless framwork so you can use native AWS deployment solution for your infrastructure like : AWS SAM ou AWS cloudformation for your deployment and benefit from AWS support.

With AWS native solution deployment you are free to choose any wanted region.

Title: How to deploy next.js 9 to aws lambda

Body:
I am developing a project with next.js9. I have some problems and questions. I would like to deploy my next.js 9 project to AWS lambda.

official next.js 9 doc tell me "each page in the pages directory becomes a serverless lambda." Above library is not working like doc. How can I deploy from each page to each lambda?

What is reasonable solution to deployment? please someone who use nextjs 9 in production level help me.

I am using this library https://github.com/danielcondemarin/serverless-next.js.
it's working well. but all options are fixed. I would like to deploy my project to Tokyo region. but I have no idea how to change region. always deploy to N. virginia region. I already checked doc but I think they don't have options. and test like this yml file.

serverless.yml

myNextApplication:
  component: serverless-next.js
region: ap-northeast-1

but it was not working. if someone know how to change region with serverless-next.js. Please help me.

Thank you in advance


问:
Share FAQs on social media
I'm using the FAQ WD Plugin for FAQ page of my website. I want to add social share to individual questions. The functionality should be that if a user shares an FAQ on any social media network, the link should be to the FAQ page with that particular question open.

Can anyone suggest some how to achieve the goal?

答:
I edited the share link to contain the ID as a query string. Then on load of the page, I added a check if the URL contains an ID query param.

If the url has a query param 'ID', then in the particular FAQ with that ID, I added the 'opened' CSS class to open it.

Title: Share FAQs on social media


问:
How to sort a Vector of Vectors?
In Java I am wondering how to sort vectors of vectors on a particular column where one vector is used as a row and one vector is used to hold all the row vectors e.g.

```<code> Vector row = new Vector();
    Vector main = new Vector();

    row.add("Column1");
    row.add("Column2");
    row.add("Column3");

    main.add(row);
</code>```

Then sort the variables in one of the columns e.g. Column2.

Thank you

答:
I guess you want to sort in 'main' rather than 'row':</p>

```<code>Vector<String> row = new Vector<String>();
Vector<Vector<String>> main = new Vector<Vector<String>>();

Collections.sort(main, new Comparator<Vector<String>>(){
    @Override  public int compare(Vector<String> v1, Vector<String> v2) {
        return v1.get(1).compareTo(v2.get(1)); //If you order by 2nd element in row
}});
</code>```

Title: How to sort a Vector of Vectors?

Body:
In Java I am wondering how to sort vectors of vectors on a particular column where one vector is used as a row and one vector is used to hold all the row vectors e.g.

 Vector row = new Vector();
    Vector main = new Vector();

    row.add("Column1");
    row.add("Column2");
    row.add("Column3");

    main.add(row);

Then sort the variables in one of the columns e.g. Column2.

Thank you

Body:
I guess you want to sort in 'main' rather than 'row':

Vector<String> row = new Vector<String>();
Vector<Vector<String>> main = new Vector<Vector<String>>();

Collections.sort(main, new Comparator<Vector<String>>(){
    @Override  public int compare(Vector<String> v1, Vector<String> v2) {
        return v1.get(1).compareTo(v2.get(1)); //If you order by 2nd element in row
}});


答:
Well, simply load it from a CDN :) That's what CDNs are here for</p>

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.33.1/plotly-basic.min.js">
</code>```

Title: How to use a a library module in a front-end external javascript file?

Body:
Situation:

I have a server side running with express.js and there I get data from SQL database. I would like to show this data to the client side, by sending it to the client.

In the front-end, I need to take this data and make it into a chart. It is possible to do it with the  tag in the HTML and include the Plotly library, which I want to use. However, I would like this operation to be done in a separate file, an external JS script for client. This avoids hard-to-read code in the HTML.

The problem is, how can I import Plotly to the external front-end file and use it?

Body:
Well, simply load it from a CDN :) That's what CDNs are here for

<script src="https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.33.1/plotly-basic.min.js">


问:
Get last N entries and order by ascending
I'm building a simple message box. Each message belongs to a conversation. What I'm trying to do is get the last 5 messages in the conversation and order them by ascending.

InboxController.php

```<code>public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->latest()
        ->take(5)
        ->get();

    $messages->orderBy('created_at','asc');

    return MessageResource::collection($messages);
}
</code>```

Error

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.

答:
Use sortBy function. Collection doesn;t have an function named orderBy.

```<code>$collection->sortBy('created_at');
</code>```

Reference:- https://laravel.com/docs/5.8/collections#method-sortby

Body:
I'm building a simple message box. Each message belongs to a conversation. What I'm trying to do is get the last 5 messages in the conversation and order them by ascending.

InboxController.php

public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->latest()
        ->take(5)
        ->get();

    $messages->orderBy('created_at','asc');

    return MessageResource::collection($messages);
}

Error

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.

Body:
Use sortBy function. Collection doesn;t have an function named orderBy.

$collection->sortBy('created_at');

Reference:- https://laravel.com/docs/5.8/collections#method-sortby


问:
Getting element content with JSOUP node's attributes
I'm having troubles with JSoup.

I have this html code:

```<code> <div title = "test" data-x="test1">I am the content</div>
</code>```

I'm using Jsoup to parse the html file.

When I'm traversing it like this:

```<code>html.traverse(new NodeVisitor() {
        public void head(Node node, int depth) {
            System.out.println(node.attributes());

        }

        public void tail(Node node, int depth) {
            ...
        }
   });
</code>```

I can see with the print that Jsoup assumes Element content is an attribute. Is that right?
I was expecting to get only "title" and "data-x" in this example.

Thanks

答:
When you traverse some node, NodeVisitor access its content as well, considering it a child node of text type. You can filter out node attributes using depth variable.

```<code>    Document doc = Jsoup.parse(data);
    doc.getElementsByTag("div").traverse(new NodeVisitor() {

        public void head(Node node, int depth) {
            System.out.println(depth + ":" + node.attributes());
        }

        public void tail(Node node, int depth) {

        }
    });
</code>```

Output will be as follows:

```<code>0: title="test" data-x="test1"
1: #text="I am the content"
</code>```

So inside of head() method add the check for the depth:

```<code>       public void head(Node node, int depth) {
            if(depth == 0) {
                Attributes attributes = node.attributes();
                // handle attributes
            }
        }
</code>```

Body:
I'm having troubles with JSoup.

I have this html code:

I am the content

I'm using Jsoup to parse the html file.

When I'm traversing it like this:

html.traverse(new NodeVisitor() {
        public void head(Node node, int depth) {
            System.out.println(node.attributes());

        }

        public void tail(Node node, int depth) {
            ...
        }
   });

I can see with the print that Jsoup assumes Element content is an attribute. Is that right?
I was expecting to get only "title" and "data-x" in this example.

Thanks

Body:
When you traverse some node, NodeVisitor access its content as well, considering it a child node of text type. You can filter out node attributes using depth variable.

    Document doc = Jsoup.parse(data);
    doc.getElementsByTag("div").traverse(new NodeVisitor() {

        public void head(Node node, int depth) {
            System.out.println(depth + ":" + node.attributes());
        }

        public void tail(Node node, int depth) {

        }
    });

Output will be as follows:

0: title="test" data-x="test1"
1: #text="I am the content"

So inside of head() method add the check for the depth:

       public void head(Node node, int depth) {
            if(depth == 0) {
                Attributes attributes = node.attributes();
                // handle attributes
            }
        }