问:
B2C App registration with custom SAML policy - configuring claims
I created some custom policy for our SAML applications in Azure b2c.
Now I want to edit the claims sent by azure b2c to application in SAMLResponse.

I added the claims in the trustframwworkbase:

```<code>  <ClaimType Id="TESTFELDSTRING">
    <DisplayName>TESTFELDSTRING</DisplayName>
    <DataType>string</DataType>
    <DefaultPartnerClaimTypes>
      <Protocol Name="OpenIdConnect" PartnerClaimType="TESTFELDSTRING" />
      <Protocol Name="SAML2" PartnerClaimType="TESTFELDSTRING" />
    </DefaultPartnerClaimTypes>
    <UserHelpText>Your TESTFELDSTRING name.</UserHelpText>
    <UserInputType>TextBox</UserInputType>
  </ClaimType>
</code>```

And I changed my custom policy and added some new outputclaim there:

```<code>    <OutputClaim ClaimTypeReferenceId="TESTFELDSTRING" />
</code>```

But the claim is still missing in my SAML responses.

I have one application which expects some information as SAML Claim and I do not see how to transmit it.
On the "normal Azure AD" I will be able to configure the claims per app. So one app is sending other claims than another app. How to do this in azure b2c?
I tried to add the claim inside the manifest of my app registration with:

```<code>"optionalClaims": {
    "saml2Token": [
        {
            "name": "TESTFELDSTRING",
            "source": null,
            "essential": false,
            "additionalProperties": []
        }
]
</code>```

}
But this is not working too.
My transmitted attributes are:

```<code>    <saml:AttributeStatement xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Display Name"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Given Name"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Surname"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Email Address"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX@XXX.XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="objectId"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
                        FriendlyName="User's Object ID"
                        >
            <saml:AttributeValue xsi:type="xs:string">xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</saml:AttributeValue>
        </saml:Attribute>
    </saml:AttributeStatement>
</code>```

Anyone a suggestion?

答:
Did you follow this sample?

Did you add the new claims as output claims in the Technical profile?

Did you also add the new claims as output claims in the <RelyingParty> section?

Body:
I created some custom policy for our SAML applications in Azure b2c.
Now I want to edit the claims sent by azure b2c to application in SAMLResponse.

I added the claims in the trustframwworkbase:

  <ClaimType Id="TESTFELDSTRING">
    <DisplayName>TESTFELDSTRING</DisplayName>
    <DataType>string</DataType>
    <DefaultPartnerClaimTypes>
      <Protocol Name="OpenIdConnect" PartnerClaimType="TESTFELDSTRING" />
      <Protocol Name="SAML2" PartnerClaimType="TESTFELDSTRING" />
    </DefaultPartnerClaimTypes>
    <UserHelpText>Your TESTFELDSTRING name.</UserHelpText>
    <UserInputType>TextBox</UserInputType>
  </ClaimType>

And I changed my custom policy and added some new outputclaim there:

    <OutputClaim ClaimTypeReferenceId="TESTFELDSTRING" />

But the claim is still missing in my SAML responses.

I have one application which expects some information as SAML Claim and I do not see how to transmit it.
On the "normal Azure AD" I will be able to configure the claims per app. So one app is sending other claims than another app. How to do this in azure b2c?
I tried to add the claim inside the manifest of my app registration with:

"optionalClaims": {
    "saml2Token": [
        {
            "name": "TESTFELDSTRING",
            "source": null,
            "essential": false,
            "additionalProperties": []
        }
]

}
But this is not working too.
My transmitted attributes are:

    <saml:AttributeStatement xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Display Name"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Given Name"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Surname"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                        FriendlyName="Email Address"
                        >
            <saml:AttributeValue xsi:type="xs:string">XXX@XXX.XXX</saml:AttributeValue>
        </saml:Attribute>
        <saml:Attribute Name="objectId"
                        NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
                        FriendlyName="User's Object ID"
                        >
            <saml:AttributeValue xsi:type="xs:string">xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</saml:AttributeValue>
        </saml:Attribute>
    </saml:AttributeStatement>

Anyone a suggestion?


来源: stackexchange

问:
My bot throws no errors, but can't seem to connect to Discord
My auth.json looks like this:

```<code>{
    "token" : "[CENSORED]"
}
</code>```

My bot code looks like this :

```<code>//recognise dependancies
var auth = require("./auth.json");
var Discord = require("discord.io");
var bot = new Discord.Client({
    token: auth.token,
    autorun: true
});

//log connection message

bot.on("ready", function(){
    console.log('Logged in as ' + bot.username + ' with an ID of ' + bot.id + '')
});

...(Unrelated code)...

//reconnecting after being disconnected

bot.on('disconnect', function(){
    console.log("Disconnected from Discord. Attempting to reconnect...")
    bot.connect();
})
</code>```

Notice the disconnect function right at the end

this is what my package.json looks like :

```<code>{
  "name": "itachi",
  "version": "1.0.0",
  "description": "",
  "main": "Itachi.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Alibi",
  "license": "ISC",
  "dependencies": {
    "discord.io": "^2.5.3"
  }
}
</code>```

When I attempt to run the itachi.js file I get no errors, but it never connects, it sends the disconnection message and then stops

```<code>C:\Users\[ME]\Desktop\Itachi>node itachi.js
Disconnected from Discord. Attempting to reconnect...

C:\Users\[ME]\Desktop\Itachi>
</code>```

I don't know what to do to make it connect, I considered the possibility that it was due to slow internet, but that's not the case. I made sure that my token was correct. It just wont connect and I cant understand why.

答:
I found something!  I was having the exact same issue, but when I used this package instead, found on npm:

discord.io-gateway6

It worked perfectly.  Sounds like the normal package, discord.io, is just out of date, and uses old API for discord - whereas the gateway6 version

ContentLicense: CC BY-SA 4.0

Body:
My auth.json looks like this:

{
    "token" : "[CENSORED]"
}

My bot code looks like this :

//recognise dependancies
var auth = require("./auth.json");
var Discord = require("discord.io");
var bot = new Discord.Client({
    token: auth.token,
    autorun: true
});

//log connection message

bot.on("ready", function(){
    console.log('Logged in as ' + bot.username + ' with an ID of ' + bot.id + '')
});

...(Unrelated code)...

//reconnecting after being disconnected

bot.on('disconnect', function(){
    console.log("Disconnected from Discord. Attempting to reconnect...")
    bot.connect();
})

Notice the disconnect function right at the end

this is what my package.json looks like :

{
  "name": "itachi",
  "version": "1.0.0",
  "description": "",
  "main": "Itachi.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Alibi",
  "license": "ISC",
  "dependencies": {
    "discord.io": "^2.5.3"
  }
}

When I attempt to run the itachi.js file I get no errors, but it never connects, it sends the disconnection message and then stops

C:\Users\[ME]\Desktop\Itachi>node itachi.js
Disconnected from Discord. Attempting to reconnect...

C:\Users\[ME]\Desktop\Itachi>

I don't know what to do to make it connect, I considered the possibility that it was due to slow internet, but that's not the case. I made sure that my token was correct. It just wont connect and I cant understand why.


问:
How to properly use nested queries in EntityFramework?
I'm playing around EntityFrameworkCore with WebAPI while building voting app exercise.

I want to make the code in async way where is possible.

So should I have to use the nested query in async way somehow(// Problem 1, // Problem 2)?

```<code>/* The target of the question - the query*/
var pollResults =
                await _context.Polls
                        .Select(poll => new PollDto
                        {
                            Id = poll.Id,
                            Question = poll.Question,
                            CreatedAt = poll.CreatedAt,
                            Options = poll.Options
                            .Select(option => new OptionDto
                            {
                                Id = option.Id,
                                Value = option.Value,
                                VotesCount = option.Votes.Count() // Problem 1
                            })
                            .ToList(), // Problem 2
                            LastVotedAt = _context.PollVotes.Where(vote=>vote.PollId == poll.Id).Select(vote => vote.VoteDate).SingleOrDefault()
                        })
                        .ToListAsync();

/* Domain classes */

public class Poll
    {
        public int Id { get; set; }
        public ICollection<PollOption> Options { get; set; } = new List<PollOption>();
        public ICollection<PollVote> Votes { get; set; } = new List<PollVote>();
    }

public class PollOption
    {
        public int Id { get; set; }
        public string Value { get; set; }
        public int PollId { get; set; }
        public Poll Poll { get; set; }
        public ICollection<PollVote> Votes { get; set; } = new List<PollVote>();
    }

 public class PollVote
    {
        public int Id { get; set; }
        public int PollId { get; set; }
        public Poll Poll { get; set; }
        public int OptionId { get; set; }
        public PollOption Option { get; set; }
        public DateTime VoteDate { get; set; }
    }

/* Dto classes */

public class PollDto
    {
        public int Id { get; set; }
        public string Question { get; set; }
        public ICollection<OptionDto> Options { get; set; } = new List<OptionDto>();
        public DateTime LastVotedAt { get; set; }
    }

public class OptionDto
    {
        public int Id { get; set; }
        public string Value { get; set; }
        public int VotesCount { get; set; }
    }

</code>```

So in not nested queries Count and SingleOrDefault would make request to the database and it should be executed in async way. But in my case the whole query is a single request.

Should I have to modify something to done the methods Count and SingleOrDefault in async way ? Or calling ToListAsync at end is enough?

I believe the answer is that 1 request to the database goes in 1 async call. But I didn't find any solution in the internet.

答:
ToListAsync() at the end is enough. Expressions inside the query are used by EF to compose the query. They are not "executed" as SQL like they would have been as stand-alone statements against the DbSets.

For instance when I run something similar:

```<code>var parents = await context.Parents
    .Select(x => new
    {
        x.ParentId,
        x.Name,
        Children = x.Children.Select(c => new { c.ChildId, c.Name }).ToList(),
        ChildCount = x.Children.Count()
    }).ToListAsync();
</code>```

in a test and set a breakpoint with a profiler running. The statement produces a single SQL statement:

```<code>SELECT
    [Project2].[ParentId] AS [ParentId],
    [Project2].[Name] AS [Name],
    [Project2].[C2] AS [C1],
    [Project2].[C1] AS [C2],
    [Project2].[ChildId] AS [ChildId],
    [Project2].[Name1] AS [Name1]
    FROM ( SELECT
        [Project1].[ParentId] AS [ParentId],
        [Project1].[Name] AS [Name],
        [Extent3].[ChildId] AS [ChildId],
        [Extent3].[Name] AS [Name1],
        CASE WHEN ([Extent3].[ChildId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1],
        [Project1].[C1] AS [C2]
        FROM   (SELECT
            [Extent1].[ParentId] AS [ParentId],
            [Extent1].[Name] AS [Name],
            (SELECT
                COUNT(1) AS [A1]
                FROM [dbo].[Children] AS [Extent2]
                WHERE [Extent1].[ParentId] = [Extent2].[ParentId]) AS [C1]
            FROM [dbo].[Parents] AS [Extent1] ) AS [Project1]
        LEFT OUTER JOIN [dbo].[Children] AS [Extent3] ON [Project1].[ParentId] = [Extent3].[ParentId]
    )  AS [Project2]
    ORDER BY [Project2].[ParentId] ASC, [Project2].[C1] ASC
go
</code>```

Not 3 queries that you might be concerned would block. This was when looking at the navigation properties for related records.

The bigger question I saw when looking at your example to double-check was this line:

```<code>LastVotedAt = _context.PollVotes.Where(vote=>vote.PollId == poll.Id).Select(vote => vote.VoteDate).SingleOrDefault()
</code>```

As this would go back directly to the Context rather than access votes through a collection on the Poll.  But I tried that as well and it too still resulted in a single query.

```<code>Children = x.Children.Select(c => new { c.ChildId, c.Name }).ToList(),
ChildCount = x.Children.Count(),
YoungestChild = context.Children.OrderBy(c=>c.BirthDate).Where(c=>c.ParentId == x.ParentId).FirstOrDefault()
</code>```

In my test example I go back to the context to retrieve the Youngest child for the parent record rather than the Children navigation property. In this case it still executes as 1 query.

For questions like this I definitely recommend creating an EF experimentation sandbox project with a local database, then leverage and SQL profiler tool to watch the SQL statements being produced and when they are executed. Async is useful for queries that are expected to take a while to run, but should be used sparingly as they can lower the overall performance of the queries being run when used on every trivial query.

Body:
I'm playing around EntityFrameworkCore with WebAPI while building voting app exercise.

I want to make the code in async way where is possible.

So should I have to use the nested query in async way somehow(// Problem 1, // Problem 2)?

/* The target of the question - the query*/
var pollResults =
                await _context.Polls
                        .Select(poll => new PollDto
                        {
                            Id = poll.Id,
                            Question = poll.Question,
                            CreatedAt = poll.CreatedAt,
                            Options = poll.Options
                            .Select(option => new OptionDto
                            {
                                Id = option.Id,
                                Value = option.Value,
                                VotesCount = option.Votes.Count() // Problem 1
                            })
                            .ToList(), // Problem 2
                            LastVotedAt = _context.PollVotes.Where(vote=>vote.PollId == poll.Id).Select(vote => vote.VoteDate).SingleOrDefault()
                        })
                        .ToListAsync();

/* Domain classes */

public class Poll
    {
        public int Id { get; set; }
        public ICollection<PollOption> Options { get; set; } = new List<PollOption>();
        public ICollection<PollVote> Votes { get; set; } = new List<PollVote>();
    }

public class PollOption
    {
        public int Id { get; set; }
        public string Value { get; set; }
        public int PollId { get; set; }
        public Poll Poll { get; set; }
        public ICollection<PollVote> Votes { get; set; } = new List<PollVote>();
    }

 public class PollVote
    {
        public int Id { get; set; }
        public int PollId { get; set; }
        public Poll Poll { get; set; }
        public int OptionId { get; set; }
        public PollOption Option { get; set; }
        public DateTime VoteDate { get; set; }
    }

/* Dto classes */

public class PollDto
    {
        public int Id { get; set; }
        public string Question { get; set; }
        public ICollection<OptionDto> Options { get; set; } = new List<OptionDto>();
        public DateTime LastVotedAt { get; set; }
    }

public class OptionDto
    {
        public int Id { get; set; }
        public string Value { get; set; }
        public int VotesCount { get; set; }
    }

So in not nested queries Count and SingleOrDefault would make request to the database and it should be executed in async way. But in my case the whole query is a single request.

Should I have to modify something to done the methods Count and SingleOrDefault in async way ? Or calling ToListAsync at end is enough?

I believe the answer is that 1 request to the database goes in 1 async call. But I didn't find any solution in the internet.

Body:
ToListAsync() at the end is enough. Expressions inside the query are used by EF to compose the query. They are not "executed" as SQL like they would have been as stand-alone statements against the DbSets.

For instance when I run something similar:

var parents = await context.Parents
    .Select(x => new
    {
        x.ParentId,
        x.Name,
        Children = x.Children.Select(c => new { c.ChildId, c.Name }).ToList(),
        ChildCount = x.Children.Count()
    }).ToListAsync();

in a test and set a breakpoint with a profiler running. The statement produces a single SQL statement:

SELECT
    [Project2].[ParentId] AS [ParentId],
    [Project2].[Name] AS [Name],
    [Project2].[C2] AS [C1],
    [Project2].[C1] AS [C2],
    [Project2].[ChildId] AS [ChildId],
    [Project2].[Name1] AS [Name1]
    FROM ( SELECT
        [Project1].[ParentId] AS [ParentId],
        [Project1].[Name] AS [Name],
        [Extent3].[ChildId] AS [ChildId],
        [Extent3].[Name] AS [Name1],
        CASE WHEN ([Extent3].[ChildId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1],
        [Project1].[C1] AS [C2]
        FROM   (SELECT
            [Extent1].[ParentId] AS [ParentId],
            [Extent1].[Name] AS [Name],
            (SELECT
                COUNT(1) AS [A1]
                FROM [dbo].[Children] AS [Extent2]
                WHERE [Extent1].[ParentId] = [Extent2].[ParentId]) AS [C1]
            FROM [dbo].[Parents] AS [Extent1] ) AS [Project1]
        LEFT OUTER JOIN [dbo].[Children] AS [Extent3] ON [Project1].[ParentId] = [Extent3].[ParentId]
    )  AS [Project2]
    ORDER BY [Project2].[ParentId] ASC, [Project2].[C1] ASC
go

Not 3 queries that you might be concerned would block. This was when looking at the navigation properties for related records.

The bigger question I saw when looking at your example to double-check was this line:

LastVotedAt = _context.PollVotes.Where(vote=>vote.PollId == poll.Id).Select(vote => vote.VoteDate).SingleOrDefault()

As this would go back directly to the Context rather than access votes through a collection on the Poll.  But I tried that as well and it too still resulted in a single query.

Children = x.Children.Select(c => new { c.ChildId, c.Name }).ToList(),
ChildCount = x.Children.Count(),
YoungestChild = context.Children.OrderBy(c=>c.BirthDate).Where(c=>c.ParentId == x.ParentId).FirstOrDefault()

In my test example I go back to the context to retrieve the Youngest child for the parent record rather than the Children navigation property. In this case it still executes as 1 query.

For questions like this I definitely recommend creating an EF experimentation sandbox project with a local database, then leverage and SQL profiler tool to watch the SQL statements being produced and when they are executed. Async is useful for queries that are expected to take a while to run, but should be used sparingly as they can lower the overall performance of the queries being run when used on every trivial query.


问:
Mapping HttpClient GET response to an array of objects of a certain type
I've created a model for data I'm querying via GET and I'm simply trying to map the output from the GET to an array of this model (a Player object).

Here's what the returned response data coming from the API looks like:

```<code>[
    {
        Id: 1
        PlayerName: "Dave",
        FirstSeason: 2013,
        LastSeason: 2016,
        BattingAverageRecord: [340, 210, 220, 300]
    },
    {
        Id: 2
        PlayerName: "Dennis",
        FirstSeason: 2013,
        LastSeason: 2016,
        BattingAverageRecord: [230, 221, 312, 240]
    },
    {
        Id: 3
        PlayerName: "Mary",
        FirstSeason: 2010,
        LastSeason: 2013,
        BattingAverageRecord: [330, 123, 151, 307]
    }

];
</code>```

I've created a model for the data:

```<code>export class Player {
    constructor(public Id: number,
                public PlayerName: string,
                public FirstSeason: number,
                public LastSeason: number,
                public BattingAverageRecord: number[])
    {
        this.Id = Id;
        this.PlayerName = PlayerName;
        this.FirstSeason = FirstSeason;
        this.LastSeason = LastSeason;
        this.BattingAverageRecord = BattingAverageRecord;
    }
}
</code>```

Now I'm trying to map response date to an array of Players:

```<code>retrievePlayer(): Observable<any> {

    return this.http.get<Player[]>(this.playerAPI)
        .pipe(
            map(data => {
                return new Player(data.Id, data.PlayerName, data.FirstSeason, data.LastSeason, data.GPARecord))
            }
        )
}
</code>```

What I've tried is obviously wrong.. I've tried doing new Array(new Player(data.id ...)) but I know that's wrong too.

答:
when you map you can easily structure your data and return the new structure eg</p>

```<code>retrievePlayer(): Observable<<Player[]> {

    return this.http.get(this.playerAPI)
        .pipe(
            map(data => {
               return {
                 Id: data.Id,
                 PlayerName: data.PlayerName,
                 FirstSeason: data.FirstSeason,
                 LastSeason: data.LastSeason,
                 BattingAverageRecord: data.GPARecord

               }
            }
        )
    }
</code>```

Body:
I've created a model for data I'm querying via GET and I'm simply trying to map the output from the GET to an array of this model (a Player object).

Here's what the returned response data coming from the API looks like:

[
    {
        Id: 1
        PlayerName: "Dave",
        FirstSeason: 2013,
        LastSeason: 2016,
        BattingAverageRecord: [340, 210, 220, 300]
    },
    {
        Id: 2
        PlayerName: "Dennis",
        FirstSeason: 2013,
        LastSeason: 2016,
        BattingAverageRecord: [230, 221, 312, 240]
    },
    {
        Id: 3
        PlayerName: "Mary",
        FirstSeason: 2010,
        LastSeason: 2013,
        BattingAverageRecord: [330, 123, 151, 307]
    }

];

I've created a model for the data:

export class Player {
    constructor(public Id: number,
                public PlayerName: string,
                public FirstSeason: number,
                public LastSeason: number,
                public BattingAverageRecord: number[])
    {
        this.Id = Id;
        this.PlayerName = PlayerName;
        this.FirstSeason = FirstSeason;
        this.LastSeason = LastSeason;
        this.BattingAverageRecord = BattingAverageRecord;
    }
}

Now I'm trying to map response date to an array of Players:

retrievePlayer(): Observable<any> {

    return this.http.get<Player[]>(this.playerAPI)
        .pipe(
            map(data => {
                return new Player(data.Id, data.PlayerName, data.FirstSeason, data.LastSeason, data.GPARecord))
            }
        )
}

What I've tried is obviously wrong.. I've tried doing new Array(new Player(data.id ...)) but I know that's wrong too.

Body:
when you map you can easily structure your data and return the new structure eg

retrievePlayer(): Observable<<Player[]> {

    return this.http.get(this.playerAPI)
        .pipe(
            map(data => {
               return {
                 Id: data.Id,
                 PlayerName: data.PlayerName,
                 FirstSeason: data.FirstSeason,
                 LastSeason: data.LastSeason,
                 BattingAverageRecord: data.GPARecord

               }
            }
        )
    }


问:
Open or Create Directory from QFileDialog
I need to create a dialog for selecting a log directory that allows either the selection of a directory or the creation of a directory if a name is typed in that doesn't exist.  I have been able to accomplish one or the other but not both at once.

With Accept mode QFileDialog.AcceptOpen, I can open directories.

With Accept mode  QFileDialog.AcceptSave, I can create directories, but I cannot open an existing directory.

Code Snippet:

```<code>def open_or_create_directory(self, log_dir):
    """
    open or create a directory
    Doesn't work!!!
    """

    dialog = QtWidgets.QFileDialog(self, caption='Data Log File Dir')
    dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
    dialog.setDirectory(log_dir)
    dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
    dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
    dialog.setLabelText(QtWidgets.QFileDialog.Accept, "Select")
    if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
       logdir = dialog.selectedFiles()

</code>```

The closest path I have been able to find is QFileDialog: Selecting directories and files but I don't know how to implement this in python.

答:
Surely what the OP points out depends on the native dialogue of the OS since in my desktop manager (plasma-KDE) it allows me to do both tasks, for example with one click it allows me to navigate in a directory and with double-click it allows the editing of the route, and with right click opens a menu where one of the options allows creating directories.

If the problem is with the native dialogue then you can use the custom Qt dialog to do so enable the option QFileDialog :: DontUseNativeDialog, in it you can navigate with a click and by right clicking a menu will open where one of the actions allows the option of create a new folder

from PyQt5 import QtWidgets

def open_or_create_directory(log_dir):
    """
    open or create a directory
    """

    dialog = QtWidgets.QFileDialog(None, caption='Data Log File Dir')
    dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True)
    dialog.setDirectory(log_dir)
    dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
    dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
    dialog.setLabelText(QtWidgets.QFileDialog.Accept, "Select")
    if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
       logdir = dialog.selectedFiles()
       print(logdir)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    open_or_create_directory("/path/of/directory")
```

<p>If you consider the solution of this link to be correct then it is easy to translate it into python:</p>

```dialog = QtWidgets.QFileDialog(self)
dialog.setFileMode(QtWidgets.QFileDialog.Directory)
dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True)

l = dialog.findChild(QtWidgets.QListView, "listView")
if l is not None:
    l.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
t = dialog.findChild(QtWidgets.QTreeView)
if t is not None:
    t.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)

nMode = dialog.exec_()
names = dialog.selectedFiles()
```

Body:
I need to create a dialog for selecting a log directory that allows either the selection of a directory or the creation of a directory if a name is typed in that doesn't exist.  I have been able to accomplish one or the other but not both at once.

With Accept mode QFileDialog.AcceptOpen, I can open directories.

With Accept mode  QFileDialog.AcceptSave, I can create directories, but I cannot open an existing directory.

Code Snippet:

def open_or_create_directory(self, log_dir):
    """
    open or create a directory
    Doesn't work!!!
    """

    dialog = QtWidgets.QFileDialog(self, caption='Data Log File Dir')
    dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
    dialog.setDirectory(log_dir)
    dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
    dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
    dialog.setLabelText(QtWidgets.QFileDialog.Accept, "Select")
    if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
       logdir = dialog.selectedFiles()

The closest path I have been able to find is QFileDialog: Selecting directories and files but I don't know how to implement this in python.

Body:
Surely what the OP points out depends on the native dialogue of the OS since in my desktop manager (plasma-KDE) it allows me to do both tasks, for example with one click it allows me to navigate in a directory and with double-click it allows the editing of the route, and with right click opens a menu where one of the options allows creating directories.

If the problem is with the native dialogue then you can use the custom Qt dialog to do so enable the option QFileDialog :: DontUseNativeDialog, in it you can navigate with a click and by right clicking a menu will open where one of the actions allows the option of create a new folder

from PyQt5 import QtWidgets

def open_or_create_directory(log_dir):
    """
    open or create a directory
    """

    dialog = QtWidgets.QFileDialog(None, caption='Data Log File Dir')
    dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True)
    dialog.setDirectory(log_dir)
    dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
    dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
    dialog.setLabelText(QtWidgets.QFileDialog.Accept, "Select")
    if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
       logdir = dialog.selectedFiles()
       print(logdir)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    open_or_create_directory("/path/of/directory")

If you consider the solution of this link to be correct then it is easy to translate it into python:

dialog = QtWidgets.QFileDialog(self)
dialog.setFileMode(QtWidgets.QFileDialog.Directory)
dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True)

l = dialog.findChild(QtWidgets.QListView, "listView")
if l is not None:
    l.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
t = dialog.findChild(QtWidgets.QTreeView)
if t is not None:
    t.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)

nMode = dialog.exec_()
names = dialog.selectedFiles()


问:
Why doesn't CSS clip-path with SVG work in Safari?
I have an inline svg and a background image on the masthead.
I am using css clip-path to 'clip' out the svg animation with the image below.

I have it working great in firefox and chrome but safari doesn't apply any of the clipping/masking at all.

I checked caniuse spec's before starting this project and it states the same rules and exceptions that apply to chrome, I just tested with chrome first and it worked so I continued on it figuring safari would have the same treatment.

I have been scratching my head trying to figure out how to get the clipping to work properly in safari with no avail.

How can I get this to work in safari?
Pen for reference:
https://codepen.io/H0BB5/pen/Xpawgp

HTML

```<code><clipPath id="cross">
    <rect y="110" x="137" width="90" height="90"/>
    <rect x="0" y="110" width="90" height="90"/>
    <rect x="137" y="0" width="90" height="90"/>
    <rect x="0" y="0" width="90" height="90"/>
 </clipPath>
</code>```

CSS

```<code>#clipped {
  margin-bottom: 20px;
  clip-path: url(#cross);
}
</code>```

答:
Just need to add -webkit- prefix:

```<code>-webkit-clip-path: polygon(50% 0%, 1000% 0%, 50% 100%, -1000% 0%);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an inline svg and a background image on the masthead.
I am using css clip-path to 'clip' out the svg animation with the image below.

I have it working great in firefox and chrome but safari doesn't apply any of the clipping/masking at all.

I checked caniuse spec's before starting this project and it states the same rules and exceptions that apply to chrome, I just tested with chrome first and it worked so I continued on it figuring safari would have the same treatment.

I have been scratching my head trying to figure out how to get the clipping to work properly in safari with no avail.

How can I get this to work in safari?
Pen for reference:
https://codepen.io/H0BB5/pen/Xpawgp

HTML

<clipPath id="cross">
    <rect y="110" x="137" width="90" height="90"/>
    <rect x="0" y="110" width="90" height="90"/>
    <rect x="137" y="0" width="90" height="90"/>
    <rect x="0" y="0" width="90" height="90"/>
 </clipPath>

CSS

#clipped {
  margin-bottom: 20px;
  clip-path: url(#cross);
}

Body:
Just need to add -webkit- prefix:

-webkit-clip-path: polygon(50% 0%, 1000% 0%, 50% 100%, -1000% 0%);


问:
Get the most recent file in a directory, Node.js
I am trying to find the most recently created file in a directory using Node.js and cannot seem to find a solution. The following code seemed to be doing the trick on one machine but on another it was just pulling a random file from the directory - as I figured it might. Basically, I need to find the newest file and ONLY that file.

```<code>var fs = require('fs'); //File System
var audioFilePath = 'C:/scanner/audio/'; //Location of recorded audio files
    var audioFile = fs.readdirSync(audioFilePath)
        .slice(-1)[0]
        .replace('.wav', '.mp3');
</code>```

Many thanks!

答:
Another approach:</p>
```<code>const fs = require('fs')
const glob = require('glob')

const newestFile = glob.sync('input/*xlsx')
  .map(name => ({name, ctime: fs.statSync(name).ctime}))
  .sort((a, b) => b.ctime - a.ctime)[0].name
</code>```

Body:
I am trying to find the most recently created file in a directory using Node.js and cannot seem to find a solution. The following code seemed to be doing the trick on one machine but on another it was just pulling a random file from the directory - as I figured it might. Basically, I need to find the newest file and ONLY that file.

var fs = require('fs'); //File System
var audioFilePath = 'C:/scanner/audio/'; //Location of recorded audio files
    var audioFile = fs.readdirSync(audioFilePath)
        .slice(-1)[0]
        .replace('.wav', '.mp3');

Many thanks!

Body:
Another approach:

const fs = require('fs')
const glob = require('glob')

const newestFile = glob.sync('input/*xlsx')
  .map(name => ({name, ctime: fs.statSync(name).ctime}))
  .sort((a, b) => b.ctime - a.ctime)[0].name


问:
Handle an exception in a trigger in oracle
I'm a rookie in oracle and I want to display an error when (expAnnee*100 + expMois) < YYMM (YYMM of SYSDATE) to check the validity of a credit card.

expAnnee and expMois are numbers.

I get the following error:

```<code>PLS-00201: identifier 'NEW.EXPANNEE' must be declared
</code>```

But this is a trigger, and in my "InfoCredit" table expAnnee and expMois are indeed there.

```<code>CREATE OR REPLACE TRIGGER VALID_CARD
BEFORE INSERT ON INFOCREDIT
FOR EACH ROW
DECLARE
    ex_expired EXCEPTION;
    testdate NUMBER;
BEGIN
    SELECT to_number(to_char(to_date(SYSDATE, 'DD-MM-YYYY'), 'YYMM'))
    INTO testdate
    FROM Dual;

    if ((new.expAnnee*100+new.expMois) < testdate)
    Then RAISE ex_expired;
    END IF;

EXCEPTION

    WHEN ex_expired
    THEN DBMS_OUTPUT.PUT_LINE('CARD EXPIRED');

END;
/
</code>```

答:
Refer to new as :new

E.g.

if ((:new.expAnnee*100+:new.expMois) < testdate)

Body:
I'm a rookie in oracle and I want to display an error when (expAnnee*100 + expMois) < YYMM (YYMM of SYSDATE) to check the validity of a credit card.

expAnnee and expMois are numbers.

I get the following error:

PLS-00201: identifier 'NEW.EXPANNEE' must be declared

But this is a trigger, and in my "InfoCredit" table expAnnee and expMois are indeed there.

CREATE OR REPLACE TRIGGER VALID_CARD
BEFORE INSERT ON INFOCREDIT
FOR EACH ROW
DECLARE
    ex_expired EXCEPTION;
    testdate NUMBER;
BEGIN
    SELECT to_number(to_char(to_date(SYSDATE, 'DD-MM-YYYY'), 'YYMM'))
    INTO testdate
    FROM Dual;

    if ((new.expAnnee*100+new.expMois) < testdate)
    Then RAISE ex_expired;
    END IF;

EXCEPTION

    WHEN ex_expired
    THEN DBMS_OUTPUT.PUT_LINE('CARD EXPIRED');

END;
/


问:
Convert React inline styles to CSS rules
Is there a tool, that converts React inline style descriptions to CSS rules?

Example input:

```<code>{
    minHeight: 200,
    position: 'relative',
    flexGrow: 1,
    flexShrink: 1,
    display: 'flex',
    flexDirection: 'column',
}
</code>```

Example output:

```<code>{
    min-height: 200px;
    position: relative;
    flex-grow: 1;
    flex-shrink: 1;
    display: flex;
    flex-flow: column;
}
</code>```

To put it differently, I want a tool that does the exact opposite of this: https://github.com/raphamorim/native-css

I would like to use it manually, so command line or web-based is preferable.

答:
Yes there's a tool that does just that!

https://glitch.com/~convert-css-js

If you paste your example input into the JS side (has to be in parentheses), you get the CSS output you specified (less the final semi-colon).

Body:
Is there a tool, that converts React inline style descriptions to CSS rules?

Example input:

{
    minHeight: 200,
    position: 'relative',
    flexGrow: 1,
    flexShrink: 1,
    display: 'flex',
    flexDirection: 'column',
}

Example output:

{
    min-height: 200px;
    position: relative;
    flex-grow: 1;
    flex-shrink: 1;
    display: flex;
    flex-flow: column;
}

To put it differently, I want a tool that does the exact opposite of this: https://github.com/raphamorim/native-css

I would like to use it manually, so command line or web-based is preferable.


问:
Making a series of plots that proceed by a click
In the example below I would like to be able to control when I go to the next plot by a using mouse click (or keyboard entry)

```<code>for (i in 1:5){
    plot(1:i)
    Sys.sleep(1)
    #add something here that requests mouse click to proceed
}
</code>```

Is this possible? There is a setting in the X11() help file caled 'clickToConfirm' but I can't work out what that does.

It would also be helpful to me to be to be able to scroll back and forth through plots using the arrow keys. Is this possible?

Currently if I need to look at lots of plots I output them into a big .pdf file and scroll though them all there, but that is a bit cumbersome.

Thanks

Tom

答:
You can use locator - now plots change on click</p>

```<code>for (i in 1:5){
    plot(1:i)
    locator(1)
}
</code>```

Body:
In the example below I would like to be able to control when I go to the next plot by a using mouse click (or keyboard entry)

for (i in 1:5){
    plot(1:i)
    Sys.sleep(1)
    #add something here that requests mouse click to proceed
}

Is this possible? There is a setting in the X11() help file caled 'clickToConfirm' but I can't work out what that does.

It would also be helpful to me to be to be able to scroll back and forth through plots using the arrow keys. Is this possible?

Currently if I need to look at lots of plots I output them into a big .pdf file and scroll though them all there, but that is a bit cumbersome.

Thanks

Tom

Body:
You can use locator - now plots change on click

for (i in 1:5){
    plot(1:i)
    locator(1)
}


问:
How to copy assets with vue-cli-service build command?
Below is the content of my app src directory. How can I copy files located in src/assets/others to dist/others folder with vue-cli-service build command? Btw. my project was created with vue create command.

```<code>    src/
    ├── App.vue
    ├── assets
    |    ├── others
    |        └── metadata.xlsx
    dist/
    ├── css
    │   ├── app.4d032e62.css
    │   └── chunk-vendors.f6f30965.css
    ├── favicon.ico
    ├── img
    │   └── upload.a0fd70ac.svg
    ├── index.html
    └── js
        ├── app.11cd5b00.js
        ├── app.11cd5b00.js.map
        ├── chunk-vendors.58c6929b.js
        └── chunk-vendors.58c6929b.js.map
</code>```

答:
In a Vue CLI project, the src/assets directory normally contains files that are processed by Webpack (for minification, etc.), and static assets are stored in the public directory. So, you could move your src/assets/others to public/others, where they'll automatically be copied to dist during the build.

On the other hand, if you'd rather the src/assets directory also contain static assets for some reason, you could configure the WebpackCopyPlugin (already included in Vue CLI) to copy src/assets/others to dist/others at build time:

// vue.config.js
const path = require('path')

module.exports = {
  chainWebpack: config => {
    config.plugin('copy')
          .tap(args => {
            args[0].push({
              from: path.resolve(__dirname, 'src/assets/others'),
              to: path.resolve(__dirname, 'dist/others'),
              toType: 'dir',
              ignore: ['.DS_Store']
            })
            return args
          })
  }
}
```

Body:
Below is the content of my app src directory. How can I copy files located in src/assets/others to dist/others folder with vue-cli-service build command? Btw. my project was created with vue create command.

    src/
    ├── App.vue
    ├── assets
    |    ├── others
    |        └── metadata.xlsx
    dist/
    ├── css
    │   ├── app.4d032e62.css
    │   └── chunk-vendors.f6f30965.css
    ├── favicon.ico
    ├── img
    │   └── upload.a0fd70ac.svg
    ├── index.html
    └── js
        ├── app.11cd5b00.js
        ├── app.11cd5b00.js.map
        ├── chunk-vendors.58c6929b.js
        └── chunk-vendors.58c6929b.js.map


问:
how to append element to dom with case-sensitive elem name
In the following example I have an inline SVG. You can see that within it, some of the SVG elements (<radialGradient> and <linearGradient>) are camel case. How would I programatically add another such element to the <defs> parent.

document.createElement() converts its argument to lowercase before creating the node, so the case sensitive element name is lost. And the Square remains white in my rendered SVG.

Is there any way to do this using javascript?

const linearGradient = document.createElement('linearGradient')
linearGradient.id="my-gradient"
linearGradient.setAttribute('x1', '320.38')
linearGradient.setAttribute('y1', '145.87')
linearGradient.setAttribute('x2', '685.45')
linearGradient.setAttribute('y2', '447.31')
linearGradient.setAttribute('gradientUnits','userSpaceOnUse')

 const stop1 = document.createElement('stop')
 stop1.setAttribute('offset', '0')
 stop1.setAttribute('stop-color', '#ed1e79')

 const stop2 = document.createElement('stop')
 stop2.setAttribute('offset', '1')
 stop2.setAttribute('stop-color', '#ff0')

linearGradient.appendChild(stop1)
linearGradient.appendChild(stop2)

 document.querySelector('svg defs').appendChild(linearGradient)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg id="a663773f-8c77-4356-b99a-00f824054fe3" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 894.23 805.64">
  <defs>

    <radialGradient id="e87c7fc2-e4ed-4d65-889f-d6153929018e" cx="659.66" cy="541.62" r="261.56" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#615ab2"/>
      <stop offset="1" stop-color="#c0bde0"/>
    </radialGradient>
    <linearGradient id="a0a8f98c-a36f-4841-bfb8-51385632467d" x1="23.64" y1="496.01" x2="632.48" y2="496.01" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#fff"/>
      <stop offset="1" stop-color="#96e700"/>
    </linearGradient>
  </defs>
  <title>shapes</title>
  <g>
    <rect x="212.97" y="11" width="529.92" height="529.92" style="fill: url(#my-gradient)"/>
    <path d="M769.89,99V606.92H262V99H769.89m22-22H240V628.92H791.89V77Z" transform="translate(-38 -76.99)"/>
  </g>
  <g>
    <path d="M659.66,803.19a261.58,261.58,0,1,1,185-76.61A259.86,259.86,0,0,1,659.66,803.19Z" transform="translate(-38 -76.99)" style="fill: url(#e87c7fc2-e4ed-4d65-889f-d6153929018e)"/>
    <path d="M659.66,291.06a249.68,249.68,0,1,1-97.52,19.68,249,249,0,0,1,97.52-19.68m0-22c-150.53,0-272.56,122-272.56,272.56s122,272.57,272.56,272.57,272.57-122,272.57-272.57-122-272.56-272.57-272.56Z" transform="translate(-38 -76.99)"/>
  </g>
  <g>
    <polygon points="175.85 576.03 23.64 427.66 233.99 397.1 328.06 206.49 422.13 397.1 632.48 427.66 480.27 576.03 516.2 785.53 328.06 686.62 139.92 785.53 175.85 576.03" style="fill: url(#a0a8f98c-a36f-4841-bfb8-51385632467d)"/>
    <path d="M366.06,308.34l81.65,165.43,5.11,10.37,11.45,1.67,182.57,26.52L514.73,641.11l-8.28,8.07,1.95,11.4,31.19,181.83L376.3,756.56l-10.24-5.38-10.24,5.38L192.53,842.41l31.18-181.83,2-11.4-8.28-8.07L85.28,512.33l182.57-26.52,11.44-1.67,5.12-10.37,81.65-165.43m0-49.71L264.68,464,38,497,202,656.86,163.31,882.63,366.06,776,568.81,882.63,530.09,656.86,694.12,497,467.43,464,366.06,258.63Z" transform="translate(-38 -76.99)"/>
  </g>
</svg></code>```

答:
I think

```<code>document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient')
</code>```

should work, according to this

Body:
In the following example I have an inline SVG. You can see that within it, some of the SVG elements (<radialGradient> and <linearGradient>) are camel case. How would I programatically add another such element to the <defs> parent.

document.createElement() converts its argument to lowercase before creating the node, so the case sensitive element name is lost. And the Square remains white in my rendered SVG.

Is there any way to do this using javascript?

const linearGradient = document.createElement('linearGradient')
linearGradient.id="my-gradient"
linearGradient.setAttribute('x1', '320.38')
linearGradient.setAttribute('y1', '145.87')
linearGradient.setAttribute('x2', '685.45')
linearGradient.setAttribute('y2', '447.31')
linearGradient.setAttribute('gradientUnits','userSpaceOnUse')

 const stop1 = document.createElement('stop')
 stop1.setAttribute('offset', '0')
 stop1.setAttribute('stop-color', '#ed1e79')

 const stop2 = document.createElement('stop')
 stop2.setAttribute('offset', '1')
 stop2.setAttribute('stop-color', '#ff0')

linearGradient.appendChild(stop1)
linearGradient.appendChild(stop2)

 document.querySelector('svg defs').appendChild(linearGradient)

<svg id="a663773f-8c77-4356-b99a-00f824054fe3" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 894.23 805.64">
  <defs>

    <radialGradient id="e87c7fc2-e4ed-4d65-889f-d6153929018e" cx="659.66" cy="541.62" r="261.56" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#615ab2"/>
      <stop offset="1" stop-color="#c0bde0"/>
    </radialGradient>
    <linearGradient id="a0a8f98c-a36f-4841-bfb8-51385632467d" x1="23.64" y1="496.01" x2="632.48" y2="496.01" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#fff"/>
      <stop offset="1" stop-color="#96e700"/>
    </linearGradient>
  </defs>
  <title>shapes</title>
  <g>
    <rect x="212.97" y="11" width="529.92" height="529.92" style="fill: url(#my-gradient)"/>
    <path d="M769.89,99V606.92H262V99H769.89m22-22H240V628.92H791.89V77Z" transform="translate(-38 -76.99)"/>
  </g>
  <g>
    <path d="M659.66,803.19a261.58,261.58,0,1,1,185-76.61A259.86,259.86,0,0,1,659.66,803.19Z" transform="translate(-38 -76.99)" style="fill: url(#e87c7fc2-e4ed-4d65-889f-d6153929018e)"/>
    <path d="M659.66,291.06a249.68,249.68,0,1,1-97.52,19.68,249,249,0,0,1,97.52-19.68m0-22c-150.53,0-272.56,122-272.56,272.56s122,272.57,272.56,272.57,272.57-122,272.57-272.57-122-272.56-272.57-272.56Z" transform="translate(-38 -76.99)"/>
  </g>
  <g>
    <polygon points="175.85 576.03 23.64 427.66 233.99 397.1 328.06 206.49 422.13 397.1 632.48 427.66 480.27 576.03 516.2 785.53 328.06 686.62 139.92 785.53 175.85 576.03" style="fill: url(#a0a8f98c-a36f-4841-bfb8-51385632467d)"/>
    <path d="M366.06,308.34l81.65,165.43,5.11,10.37,11.45,1.67,182.57,26.52L514.73,641.11l-8.28,8.07,1.95,11.4,31.19,181.83L376.3,756.56l-10.24-5.38-10.24,5.38L192.53,842.41l31.18-181.83,2-11.4-8.28-8.07L85.28,512.33l182.57-26.52,11.44-1.67,5.12-10.37,81.65-165.43m0-49.71L264.68,464,38,497,202,656.86,163.31,882.63,366.06,776,568.81,882.63,530.09,656.86,694.12,497,467.43,464,366.06,258.63Z" transform="translate(-38 -76.99)"/>
  </g>
</svg>

Body:
I think

document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient')

should work, according to this


问:
The best way to store the following temporal data in DB
Imagine we have a set of entities each of which has its state: free, busy or broken. The state is specified for a day, for example, today on 2011-05-17 an entity E1 is free and tomorrow on 2011-05-18 it is busy.

There is a need to store ~10^5 entities for 1000 days. Which is the best way to do so?

I am thinking about 2 options:

represent each day as a character "0", "1" or "2" and store for every entity a string of 1000 characters

store each day with entity's state in a row, i.e. 1000 rows for an entity

The most important query for such data is: given start date and end date identify which entities are free.

Performance is of higher priority than storage.

All suggestions and comments are welcome.

答: It sounds like you might be on the right track and I would suggest because of the sheer number of records and the emphasis on performance that you keep the schema as denormalized as possible.  The fewer joins you need to make to determine the free or busy entities the better.</p>


问:
Include groupby statement in function - Python
The following function counts the number of points within different segments of a circle. This function works as intended when exporting counts for a single point in time. However, when trying export this count at different points in time using a groupby call, it still combines all counts to a single output.

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({
        'Time' : ['19:50:10.1','19:50:10.1','19:50:10.1','19:50:10.1','19:50:10.2','19:50:10.2','19:50:10.2','19:50:10.2'],
        'id' : ['A','B','C','D','A','B','C','D'],
        'x' : [1,8,0,-5,1,-1,-6,0],
        'y' : [-5,2,-5,2,5,-5,-2,2],
        'X2' : [0,0,0,0,0,0,0,0],
        'Y2' : [0,0,0,0,0,0,0,0],
        'Angle' : [0,0,0,0,0,0,0,0],
    })

def checkPoint(x, y, rotation_angle, refX, refY, radius = 10):

    section_angle_start = [(i + rotation_angle - 45) for i in [0, 90, 180, 270, 360]]

    Angle = np.arctan2(x-refX, y-refY) * 180 / np.pi
    Angle = Angle % 360

    # adjust range
    if Angle > section_angle_start[-1]:
        Angle -= 360
    elif Angle < section_angle_start[0]:
        Angle += 360

    for i in range(4):
        if section_angle_start[i] < Angle < section_angle_start[i+1]:
            break
    else:
         i = 0

    return i+1

tmp = []
result = []
</code>```

The following is my attempt to pass the checkPoint function to each unique group in Time.

```<code>for group in df.groupby('Time'):

    for i, row in df.iterrows():

        seg = checkPoint(row.x, row.y, row.Angle, row.X2, row.Y2)

        tmp.append(seg)

    result.append([tmp.count(i) for i in [1,2,3,4]])

df = pd.DataFrame(result, columns = ['1','2','3','4'])
</code>```

Out:

```<code>   1  2  3  4
0  2  1  3  2
1  4  2  6  4
</code>```

Intended Out:

```<code>   1  2  3  4
0  0  1  2  1
1  2  0  1  1
</code>```

答:
Your inner loop is running through your entire DataFrame, and generating the double-counting you are observing.

As @Kenan suggested, you can limit the inner loop to the group:

```<code>for group in df.groupby('Time'):

    for i, row in group[1].iterrows():

        seg = checkPoint(row.x_live, row.y_live, row.Angle, row.BallX, row.BallY)

        tmp.append(seg)

    result.append([tmp.count(i) for i in [1,2,3,4]])

df_result = pd.DataFrame(result, columns = ['1','2','3','4'])
print(df_result)
</code>```

Resulting in

```<code>   1  2  3  4
0  0  1  2  1
1  2  1  3  2
</code>```

Or you can use a groupby-apply construct to avoid the explicit loop:

```<code>def result(g):
    tmp = []
    for i, row in g.iterrows():
        seg = checkPoint(row.x_live, row.y_live, row.Angle, row.BallX, row.BallY)
        tmp.append(seg)
    return pd.Series([tmp.count(i) for i in [1,2,3,4]], index=[1,2,3,4])

print(df.groupby('Time').apply(result))
</code>```

Which gets you:

```<code>            1  2  3  4
Time
19:50:10.1  0  1  2  1
19:50:10.2  2  0  1  1
</code>```

Body:
The following function counts the number of points within different segments of a circle. This function works as intended when exporting counts for a single point in time. However, when trying export this count at different points in time using a groupby call, it still combines all counts to a single output.

import pandas as pd
import numpy as np

df = pd.DataFrame({
        'Time' : ['19:50:10.1','19:50:10.1','19:50:10.1','19:50:10.1','19:50:10.2','19:50:10.2','19:50:10.2','19:50:10.2'],
        'id' : ['A','B','C','D','A','B','C','D'],
        'x' : [1,8,0,-5,1,-1,-6,0],
        'y' : [-5,2,-5,2,5,-5,-2,2],
        'X2' : [0,0,0,0,0,0,0,0],
        'Y2' : [0,0,0,0,0,0,0,0],
        'Angle' : [0,0,0,0,0,0,0,0],
    })

def checkPoint(x, y, rotation_angle, refX, refY, radius = 10):

    section_angle_start = [(i + rotation_angle - 45) for i in [0, 90, 180, 270, 360]]

    Angle = np.arctan2(x-refX, y-refY) * 180 / np.pi
    Angle = Angle % 360

    # adjust range
    if Angle > section_angle_start[-1]:
        Angle -= 360
    elif Angle < section_angle_start[0]:
        Angle += 360

    for i in range(4):
        if section_angle_start[i] < Angle < section_angle_start[i+1]:
            break
    else:
         i = 0

    return i+1

tmp = []
result = []

The following is my attempt to pass the checkPoint function to each unique group in Time.

for group in df.groupby('Time'):

    for i, row in df.iterrows():

        seg = checkPoint(row.x, row.y, row.Angle, row.X2, row.Y2)

        tmp.append(seg)

    result.append([tmp.count(i) for i in [1,2,3,4]])

df = pd.DataFrame(result, columns = ['1','2','3','4'])

Out:

   1  2  3  4
0  2  1  3  2
1  4  2  6  4

Intended Out:

   1  2  3  4
0  0  1  2  1
1  2  0  1  1

Body:
Your inner loop is running through your entire DataFrame, and generating the double-counting you are observing.

As @Kenan suggested, you can limit the inner loop to the group:

for group in df.groupby('Time'):

    for i, row in group[1].iterrows():

        seg = checkPoint(row.x_live, row.y_live, row.Angle, row.BallX, row.BallY)

        tmp.append(seg)

    result.append([tmp.count(i) for i in [1,2,3,4]])

df_result = pd.DataFrame(result, columns = ['1','2','3','4'])
print(df_result)

Resulting in

   1  2  3  4
0  0  1  2  1
1  2  1  3  2

Or you can use a groupby-apply construct to avoid the explicit loop:

def result(g):
    tmp = []
    for i, row in g.iterrows():
        seg = checkPoint(row.x_live, row.y_live, row.Angle, row.BallX, row.BallY)
        tmp.append(seg)
    return pd.Series([tmp.count(i) for i in [1,2,3,4]], index=[1,2,3,4])

print(df.groupby('Time').apply(result))

Which gets you:

            1  2  3  4
Time
19:50:10.1  0  1  2  1
19:50:10.2  2  0  1  1


问:
Average of empty list throws InvalidOperationException: Sequence contains no elements
The following code

```<code>double avg = item?.TechnicianTasks?.Average(x => x.Rating) ?? 0
</code>```

throws

InvalidOperationException: Sequence contains no elements

the item.TechnicianTasks was supposed to be null, however I saw that it is an empty list, however why wouldn't the average just be zero? I'm not understanding the exception.

答:
Not much to it - it's just how the code was written.  Take a look at the docs and you'll see -

Exceptions

ArgumentNullException - source is null.

InvalidOperationException - source contains no elements.

Makes sense though.  You can't get an average from zero items.

Body:
The following code

double avg = item?.TechnicianTasks?.Average(x => x.Rating) ?? 0

throws

InvalidOperationException: Sequence contains no elements

the item.TechnicianTasks was supposed to be null, however I saw that it is an empty list, however why wouldn't the average just be zero? I'm not understanding the exception.


问:
cache TryGetValue versus Get
This is how I am implementing my CacheManager. The problem I am facing is that TryGetValue will always return null in RemoveFromCache function. This function is called after one of the tokens has expired and so I am trying to clear that token from the List in cache, while GetAllTokens is returning full list of all tokens. AddTokenToCache is working correctly.

Its a WebAPI on ASPNET-Core 3.0

CacheManager.cs

```<code>public class CacheManager : ICacheManager
{
    private IMemoryCache _cache;

    public CacheManager(IMemoryCache cache) {
        _cache = cache;

    }
    public void AddTokenToCache(string appName, string tokenString)
    {
        List<Token> tokens = new List<Token>();

        //save this token against the application record in-memory
        if (!_cache.TryGetValue(CacheHelper.CacheKey_Tokens, out tokens))
        {
            if (tokens == null)
                tokens = new List<Token>();

        }

        tokens.Add(new Token
        {
            AppName = appName,
            GeneratedAt = DateTime.Now,
            TokenId = tokenString
        });

        // Set cache options.
        var cacheEntryOptions = new MemoryCacheEntryOptions()
        ;//    .SetSlidingExpiration(TimeSpan.FromSeconds(180)); //3 minutes

        _cache.Set(CacheHelper.CacheKey_Tokens, tokens, cacheEntryOptions);
    }

    public List<Token> GetAllTokens()
    {
        return _cache.Get<List<Token>>(CacheHelper.CacheKey_Tokens);
    }

    public bool RemoveFromCache(string tokenId)
    {

        List<Token> tokens = new List<Token>();

        //remove this token from memory
        if (!_cache.TryGetValue(CacheHelper.CacheKey_Tokens, out tokens)) {
            return false;
        }
        else
        {
            if (tokens != null && tokens.Count > 0)
            {
                //_logger.LogInfo("Processing token");
                //trimming quotations from the string
                tokenId = tokenId.Substring(1, tokenId.Length - 2);
                int index = tokens.FindIndex(t => t.TokenId == tokenId);

                if (index >= 0)
                    tokens.RemoveAt(index);

                var cacheEntryOptions = new MemoryCacheEntryOptions();
                _cache.Set(CacheHelper.CacheKey_Tokens, tokens, cacheEntryOptions);

                return true;
            }
        }

        return false;
    }
}
</code>```

My calling sequence is:

AddTokenToCache (token is added successfully to cache)

GetAllToken (shows a token is added to cache)

AddTokenToCache (token is added successfully to cache)

GetAllToken (shows both tokens are added to cache)

Fire TokenExpired event which calls RemoveFromCache (tokens is null)

GetAllToken (shows both tokens are added to cache)

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ILoggerManager, LoggerManager>();

        services.AddMemoryCache();
        services.AddDbContext<GEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllers();
        services.AddRazorPages();
        services.AddSingleton<ICacheManager, CacheManager>();

        RegisterHandlerforTokenExpiredEvent(services);
        //other code removed for brevity
    }
public void RegisterHandlerforTokenExpiredEvent(IServiceCollection services)
    {
        var sp = services.BuildServiceProvider();

        var jwtManager = sp.GetService<IJWTAuthenticationManager>(); //publisher
        var cacheManager = sp.GetService<ICacheManager>(); //subscriber

        jwtManager.TokenExpired += cacheManager.OnTokenExpired;
    }
</code>```

答:
That's because you built another ServiceProvider by services.BuildServiceProvider():

```<code>public void RegisterHandlerforTokenExpiredEvent(IServiceCollection services)

{
    var sp = services.BuildServiceProvider();  // this is a different service provider from the default one built by ASP.NET Core itself.

    var jwtManager = sp.GetService<IJWTAuthenticationManager>(); //publisher
    var cacheManager = sp.GetService<ICacheManager>(); //subscriber
    // it doesn't work because the cacheManager is not the same instance that you use in the controllers
    jwtManager.TokenExpired += cacheManager.OnTokenExpired;
}
</code>```

As a result, the ICacheManager instance you get is NOT the same singleton that you inject in Controllers/Other Services. In other words, you'll have two different ICacheManager instance !

As a golden rule, DO NOT build another copy of ServiceProvider by services.BuildServiceProvider() in you application layer code unless you're pretty sure it's fine for you.

How to fix

Instead of building another copy of service provider and then getting another instance, you should always use IoC instead of Service Locator Pattern.

Seems that your JWTAuthenticationManager is a singleton and you want to bind the Event handler at startup-time. If that's the case, you could register an HostedService.

public class MyHostedService : IHostedService
{
    private readonly IJWTAuthenticationManager _jWTAuthManager;
    private readonly ICacheManager _cacheManager;

    // suppose your IJWTAuthenticationManager  is a singleton service
    public MyHostedService(IJWTAuthenticationManager jWTAuthManager, ICacheManager cacheManager)
    {
        this._jWTAuthManager = jWTAuthManager;
        this._cacheManager = cacheManager;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        this._jWTAuthManager.TokenExpired += this._cacheManager.OnTokenExpired;
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        this._jWTAuthManager.TokenExpired -= this._cacheManager.OnTokenExpired;
        return Task.CompletedTask;
    }
}
```

<p>and register this service within Startup:</p>

```services.AddHostedService<MyHostedService>();
```</li>
</ol>

<hr>

<p>Another way that doesn't need HostedService and starts at start-up time:</p>

<p>Get the service and bind the event before <code>Host.Run()</code>:</p>

```public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    var jwtMgr = host.Services.GetRequiredService<IJWTAuthenticationManager>();
    var cacheMgr = host.Services.GetRequiredService<ICacheManager>();
    jwtMgr.TokenExpired = cacheMgr.OnTokenExpired;
    host.Run();
}
```

Title: cache TryGetValue versus Get

Body:
This is how I am implementing my CacheManager. The problem I am facing is that TryGetValue will always return null in RemoveFromCache function. This function is called after one of the tokens has expired and so I am trying to clear that token from the List in cache, while GetAllTokens is returning full list of all tokens. AddTokenToCache is working correctly.

Its a WebAPI on ASPNET-Core 3.0

CacheManager.cs

public class CacheManager : ICacheManager
{
    private IMemoryCache _cache;

    public CacheManager(IMemoryCache cache) {
        _cache = cache;

    }
    public void AddTokenToCache(string appName, string tokenString)
    {
        List<Token> tokens = new List<Token>();

        //save this token against the application record in-memory
        if (!_cache.TryGetValue(CacheHelper.CacheKey_Tokens, out tokens))
        {
            if (tokens == null)
                tokens = new List<Token>();

        }

        tokens.Add(new Token
        {
            AppName = appName,
            GeneratedAt = DateTime.Now,
            TokenId = tokenString
        });

        // Set cache options.
        var cacheEntryOptions = new MemoryCacheEntryOptions()
        ;//    .SetSlidingExpiration(TimeSpan.FromSeconds(180)); //3 minutes

        _cache.Set(CacheHelper.CacheKey_Tokens, tokens, cacheEntryOptions);
    }

    public List<Token> GetAllTokens()
    {
        return _cache.Get<List<Token>>(CacheHelper.CacheKey_Tokens);
    }

    public bool RemoveFromCache(string tokenId)
    {

        List<Token> tokens = new List<Token>();

        //remove this token from memory
        if (!_cache.TryGetValue(CacheHelper.CacheKey_Tokens, out tokens)) {
            return false;
        }
        else
        {
            if (tokens != null && tokens.Count > 0)
            {
                //_logger.LogInfo("Processing token");
                //trimming quotations from the string
                tokenId = tokenId.Substring(1, tokenId.Length - 2);
                int index = tokens.FindIndex(t => t.TokenId == tokenId);

                if (index >= 0)
                    tokens.RemoveAt(index);

                var cacheEntryOptions = new MemoryCacheEntryOptions();
                _cache.Set(CacheHelper.CacheKey_Tokens, tokens, cacheEntryOptions);

                return true;
            }
        }

        return false;
    }
}

My calling sequence is:

AddTokenToCache (token is added successfully to cache)

GetAllToken (shows a token is added to cache)

AddTokenToCache (token is added successfully to cache)

GetAllToken (shows both tokens are added to cache)

Fire TokenExpired event which calls RemoveFromCache (tokens is null)

GetAllToken (shows both tokens are added to cache)

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ILoggerManager, LoggerManager>();

        services.AddMemoryCache();
        services.AddDbContext<GEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllers();
        services.AddRazorPages();
        services.AddSingleton<ICacheManager, CacheManager>();

        RegisterHandlerforTokenExpiredEvent(services);
        //other code removed for brevity
    }
public void RegisterHandlerforTokenExpiredEvent(IServiceCollection services)
    {
        var sp = services.BuildServiceProvider();

        var jwtManager = sp.GetService<IJWTAuthenticationManager>(); //publisher
        var cacheManager = sp.GetService<ICacheManager>(); //subscriber

        jwtManager.TokenExpired += cacheManager.OnTokenExpired;
    }

Body:
That's because you built another ServiceProvider by services.BuildServiceProvider():

public void RegisterHandlerforTokenExpiredEvent(IServiceCollection services)

{
    var sp = services.BuildServiceProvider();  // this is a different service provider from the default one built by ASP.NET Core itself.

    var jwtManager = sp.GetService<IJWTAuthenticationManager>(); //publisher
    var cacheManager = sp.GetService<ICacheManager>(); //subscriber
    // it doesn't work because the cacheManager is not the same instance that you use in the controllers
    jwtManager.TokenExpired += cacheManager.OnTokenExpired;
}

As a result, the ICacheManager instance you get is NOT the same singleton that you inject in Controllers/Other Services. In other words, you'll have two different ICacheManager instance !

As a golden rule, DO NOT build another copy of ServiceProvider by services.BuildServiceProvider() in you application layer code unless you're pretty sure it's fine for you.

How to fix

Instead of building another copy of service provider and then getting another instance, you should always use IoC instead of Service Locator Pattern.

Seems that your JWTAuthenticationManager is a singleton and you want to bind the Event handler at startup-time. If that's the case, you could register an HostedService.

public class MyHostedService : IHostedService
{
    private readonly IJWTAuthenticationManager _jWTAuthManager;
    private readonly ICacheManager _cacheManager;

    // suppose your IJWTAuthenticationManager  is a singleton service
    public MyHostedService(IJWTAuthenticationManager jWTAuthManager, ICacheManager cacheManager)
    {
        this._jWTAuthManager = jWTAuthManager;
        this._cacheManager = cacheManager;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        this._jWTAuthManager.TokenExpired += this._cacheManager.OnTokenExpired;
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        this._jWTAuthManager.TokenExpired -= this._cacheManager.OnTokenExpired;
        return Task.CompletedTask;
    }
}

and register this service within Startup:

services.AddHostedService<MyHostedService>();

Another way that doesn't need HostedService and starts at start-up time:

Get the service and bind the event before Host.Run():

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    var jwtMgr = host.Services.GetRequiredService<IJWTAuthenticationManager>();
    var cacheMgr = host.Services.GetRequiredService<ICacheManager>();
    jwtMgr.TokenExpired = cacheMgr.OnTokenExpired;
    host.Run();
}


问:
p-dialog onHide is not working with ngIf?
Already SO has the similar question, I tried with those solution but not working.

Actual the problem is onHide event is not triggering because of the *ngIf, If I removed the *ngIf onHide is triggering.

```<code> <p-dialog [(header)]="dialogText" *ngIf="displayDlg" [(visible)]="displayDlg"
  [modal]="true" [responsive]="true" (onHide)="close()">
</code>```

But the problem is I am having the form inside the <p-dialog If I am not using the *ngIf I am getting the undefined error when loading the page. How can I fix this issue.?

答: I had the same problem.  Solved by using a different boolean variable for the *ngIf in the p-dialog tag compared to the [(visible)] attribute.  Using the same variable for both it did not work for me.   That is the basic idea.   I did it in an object oriented way.  I won't bore you with further details.</p>

Body:
Already SO has the similar question, I tried with those solution but not working.

Actual the problem is onHide event is not triggering because of the *ngIf, If I removed the *ngIf onHide is triggering.

But the problem is I am having the form inside the <p-dialog If I am not using the *ngIf I am getting the undefined error when loading the page. How can I fix this issue.?


问:
Using tidyverse to dynamically mutate one variable from one grouped dataset from another dataset
Let's say I work with different classes (nodes, in my dataset) and I have thousands of students. Each student has their own math score, and I need to compare all individual scores with the group mean/sd.
To deal with that, I have two different datasets. The first one is "a table".

This data frame is formed of several classes (nodes), their means, and their sd.

I also have another dataset composed of students' results, like this one:

I want to have another dataset in which I get all individual results (i.e., 11, 6, 10, etc) and subtract this result from all means in the first dataset. In the future, it will be needed to check all results and all nodes together.

In other words, from the first nome (number 12 in the image), I will subtract 11 (student's result) from 68 (mean result), 6 (student's result) from 68 (mean), 10 (student's result) from 68 (mean), etc.
Then I'll move for the second node (number 7 in the image), and I will do the same (subtract 11 from 74 (mean result), 6 from 74 (mean result), 10 from 74),

The final output I would like to have is below. Please, take this image as illustrative-only:

Due to questions, to make my question clear, the following command also brings an interesting solution, but it's not functional since I'll have to manually add all columns to the new dataset:

```<code>test_result %>%
  mutate(total_header_node_12 = x - default_table$t_mean[1]) %>%
  mutate(total_header_node_74 = x - default_table$t_mean[2])
</code>```

I searched for other questions but I did not find any solution.
Any help is valuable. I use tidyverse, and I would like to remain within tidyverse environment.
Thank you
To reproduce:

```<code>> dput(default_table)
structure(list(node = structure(c(6L, 3L, 5L, 1L, 2L, 4L, 7L), .Label = c("4",
"5", "7", "8", "10", "12", "13"), class = "factor"), t_mean = c(68.8219178082192,
74.3260869565217, 83.0178571428571, 92.2108108108108, 98.3304347826087,
88.6111111111111, 48.4), t_sd = c(14.4351088961341, 16.9448394654941,
13.0272663858681, 12.2011483603603, 12.1775472144027, 14.5621088567959,
10.4876948807826), vars = c(1, 1, 1, 1, 1, 1, 1), n = c(121,
74, 92, 616, 191, 58, 7), mean = c(68, 74.6891891891892, 82.8369565217391,
91.3944805194805, 97.738219895288, 88.0172413793103, 48.7142857142857
), sd = c(14.0226008048911, 16.1151045250761, 11.0426517498479,
12.6758935948866, 12.0212336250146, 15.9169901273025, 8.63547500554709
), min = c(32, 32, 58, 36, 56, 44, 39), max = c(97, 113, 104,
123, 128, 124, 60), range = c(65, 81, 46, 87, 72, 80, 21), se = c(1.27478189135374,
1.87334284914993, 1.15127602962793, 0.510726307415094, 0.869825937534791,
2.09000319547951, 3.26390275965596), q0_25 = c(59, 64, 74.75,
84, 90, 80, 41.5), q0_5 = c(68, 73.5, 81.5, 92, 98, 87, 47),
    q0_75 = c(80, 87.75, 92.25, 100, 106, 98.75, 56)), class = "data.frame", row.names = c(NA,
-7L))

test_result <- data.frame(x = rnorm(100,10,2))
</code>```

Body:
Let's say I work with different classes (nodes, in my dataset) and I have thousands of students. Each student has their own math score, and I need to compare all individual scores with the group mean/sd.
To deal with that, I have two different datasets. The first one is "a table".

This data frame is formed of several classes (nodes), their means, and their sd.

I also have another dataset composed of students' results, like this one:

I want to have another dataset in which I get all individual results (i.e., 11, 6, 10, etc) and subtract this result from all means in the first dataset. In the future, it will be needed to check all results and all nodes together.

In other words, from the first nome (number 12 in the image), I will subtract 11 (student's result) from 68 (mean result), 6 (student's result) from 68 (mean), 10 (student's result) from 68 (mean), etc.
Then I'll move for the second node (number 7 in the image), and I will do the same (subtract 11 from 74 (mean result), 6 from 74 (mean result), 10 from 74),

The final output I would like to have is below. Please, take this image as illustrative-only:

Due to questions, to make my question clear, the following command also brings an interesting solution, but it's not functional since I'll have to manually add all columns to the new dataset:

test_result %>%
  mutate(total_header_node_12 = x - default_table$t_mean[1]) %>%
  mutate(total_header_node_74 = x - default_table$t_mean[2])

I searched for other questions but I did not find any solution.
Any help is valuable. I use tidyverse, and I would like to remain within tidyverse environment.
Thank you
To reproduce:

> dput(default_table)
structure(list(node = structure(c(6L, 3L, 5L, 1L, 2L, 4L, 7L), .Label = c("4",
"5", "7", "8", "10", "12", "13"), class = "factor"), t_mean = c(68.8219178082192,
74.3260869565217, 83.0178571428571, 92.2108108108108, 98.3304347826087,
88.6111111111111, 48.4), t_sd = c(14.4351088961341, 16.9448394654941,
13.0272663858681, 12.2011483603603, 12.1775472144027, 14.5621088567959,
10.4876948807826), vars = c(1, 1, 1, 1, 1, 1, 1), n = c(121,
74, 92, 616, 191, 58, 7), mean = c(68, 74.6891891891892, 82.8369565217391,
91.3944805194805, 97.738219895288, 88.0172413793103, 48.7142857142857
), sd = c(14.0226008048911, 16.1151045250761, 11.0426517498479,
12.6758935948866, 12.0212336250146, 15.9169901273025, 8.63547500554709
), min = c(32, 32, 58, 36, 56, 44, 39), max = c(97, 113, 104,
123, 128, 124, 60), range = c(65, 81, 46, 87, 72, 80, 21), se = c(1.27478189135374,
1.87334284914993, 1.15127602962793, 0.510726307415094, 0.869825937534791,
2.09000319547951, 3.26390275965596), q0_25 = c(59, 64, 74.75,
84, 90, 80, 41.5), q0_5 = c(68, 73.5, 81.5, 92, 98, 87, 47),
    q0_75 = c(80, 87.75, 92.25, 100, 106, 98.75, 56)), class = "data.frame", row.names = c(NA,
-7L))

test_result <- data.frame(x = rnorm(100,10,2))

Body:
You just need to add the student results as a new column and then unnest to get a long form data that you can do this comparison on. There is probably also a solution with crossing but this seemed simpler. Essentially, we want to insert the student results as a new column in the default_table, and then use unnest to expand so there is one row per node-student, as in the desired output. Then we can simply subtract the mean from the student results.

set.seed(1)
library(tidyverse)
default_table <- structure(list(node = structure(c(6L, 3L, 5L, 1L, 2L, 4L, 7L), .Label = c("4", "5", "7", "8", "10", "12", "13"), class = "factor"), t_mean = c(68.8219178082192, 74.3260869565217, 83.0178571428571, 92.2108108108108, 98.3304347826087, 88.6111111111111, 48.4), t_sd = c(14.4351088961341, 16.9448394654941, 13.0272663858681, 12.2011483603603, 12.1775472144027, 14.5621088567959, 10.4876948807826), vars = c(1, 1, 1, 1, 1, 1, 1), n = c(121, 74, 92, 616, 191, 58, 7), mean = c(68, 74.6891891891892, 82.8369565217391, 91.3944805194805, 97.738219895288, 88.0172413793103, 48.7142857142857), sd = c(14.0226008048911, 16.1151045250761, 11.0426517498479, 12.6758935948866, 12.0212336250146, 15.9169901273025, 8.63547500554709), min = c(32, 32, 58, 36, 56, 44, 39), max = c(97, 113, 104, 123, 128, 124, 60), range = c(65, 81, 46, 87, 72, 80, 21), se = c(1.27478189135374, 1.87334284914993, 1.15127602962793, 0.510726307415094, 0.869825937534791, 2.09000319547951, 3.26390275965596), q0_25 = c(59, 64, 74.75, 84, 90, 80, 41.5), q0_5 = c(68, 73.5, 81.5, 92, 98, 87, 47), q0_75 = c(80, 87.75, 92.25, 100, 106, 98.75, 56)), class = "data.frame", row.names = c(NA, -7L))
test_result <- data.frame(x = rnorm(10,10,2))

test_result <- test_result %>%
  rowid_to_column(var = "student_number") %>%
  rename(student_result = x)

default_table %>%
  mutate(students = map(node, ~ test_result)) %>%
  unnest(students) %>%
  mutate(comparative_mean = student_result - mean) %>%
  select(node, mean, student_number, student_result, comparative_mean)
#> # A tibble: 70 x 5
#>    node   mean student_number student_result comparative_mean
#>    <fct> <dbl>          <int>          <dbl>            <dbl>
#>  1 12       68              1           8.75            -59.3
#>  2 12       68              2          10.4             -57.6
#>  3 12       68              3           8.33            -59.7
#>  4 12       68              4          13.2             -54.8
#>  5 12       68              5          10.7             -57.3
#>  6 12       68              6           8.36            -59.6
#>  7 12       68              7          11.0             -57.0
#>  8 12       68              8          11.5             -56.5
#>  9 12       68              9          11.2             -56.8
#> 10 12       68             10           9.39            -58.6
#> # … with 60 more rows

Created on 2020-02-19 by the reprex package (v0.3.0)


问:
Why do I need a default docker network to start a common docker network for two docker-compose projects?
I've got two projects (a and b) which both have a docker-compose.yml file. I now want one of the projects to be able to call a service of the other project and as far as I know I need to create a common docker network for that. So to create a minimal example I made two folders (a/ and b/) which both contain a docker-compose.yml file.

This is the one in folder a/:

```<code>version: '3'

services:
  common_server:
    image: ubuntu
    ports:
      - 4444:4444
    command: >
      bash -c '
      apt update && apt install netcat -y &&
      while true; do echo -e "HTTP/1.1 200 OK\n\npong" | nc -k -l -p 4444 -q 1; done'
#    networks:
#      - my_network

  project_a:
    image: ubuntu
    depends_on:
      - common_server
#    networks:
#      - my_network
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "AAAAAAAA"; curl common_server:4444; sleep 10; done'

#networks:
#  my_network:
#    driver: bridge
</code>```

This sets up two things:

common_server: a simple ping/pong server which responds "pong" to every request it gets

project_a: a simple client which calls the common_server every 10 seconds

This works great like this. I quickly checked the docker networks using:

```<code>$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== THIS NETWORK WAS CREATED
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local
</code>```

I've got a second docker-compose.yml file in the folder b/ from which I also want to call the common_server defined in the file above. So I uncommented the lines with the network in the file above to enable my_network. Running that also works great.

When I check docker network ls again I also see the second network it created:

```<code>$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== CREATED BY THE FIRST RUN
f0a42e17007b        a_my_network        bridge              local  <== CREATED BY THE SECOND RUN
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local
</code>```

I then started the second docker-compose file:

```<code>version: '3'

services:
  project_b:
    image: ubuntu
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "BBBBBBB"; curl common_server:4444; sleep 10; done'
    networks:
     - a_my_network
networks:
  a_my_network:
    external: true
</code>```

That also works. It can call the common_server from the first docker-compose file.

The first question I have: Although I define the network as my_network in the first file, it is called a_my_network by docker. Is there a way to define the network so that I can call it the same in both docker-compose files?

I then decided to remove those two networks using docker network prune, and start again. Unfortunately, when I now run the first file again I now get the following error:

```<code>$ docker-compose up
Creating network "a_my_network" with driver "bridge"
Starting a_common_server_1 ... error

ERROR: for a_common_server_1  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found

ERROR: for common_server  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found
ERROR: Encountered errors while bringing up the project.
</code>```

So my second question: Why can I only start the first docker-compose file if I first create the a_default network by not explicitly defining a network?

答:
When you declare the network in the second file you can explicitly specify its name:.

version: '3.7'  # minimum of 3.5
networks:
  my_network:
    external: true
    name: a_my_network
```

<p>As you note at the beginning, though, Compose creates a <code>default</code> network for you, and if you don't explicitly declare <code>networks:</code> for a container it will attach to <code>default</code>.  You can reconfigure the <code>default</code> network however you'd like.</p>

<p>So probably what I'd do here is not declare <code>networks:</code> in the first <code>docker-compose.yml</code> file at all.  In the second I'd make the <code>default</code> network point at the first file's <code>default</code> network, and also not configure <code>networks:</code> for containers.</p>

<pre class="lang-yaml prettyprint-override"><code>networks:
  default:
    external: true
    name: a_default
</code>```

Compose keeps track of what's going on primarily by using labels on objects.  These are generally hidden from you but they're one of the things included in the very detailed docker inspect output.  In your last example, if you manually docker network prune a network out from under Compose, it starts to get confused.  On the other hand, if you just comment out the network you manually created and re-run docker-compose up, Compose should notice that it's created a network that's no longer needed and clean it up for you.

Body:
I've got two projects (a and b) which both have a docker-compose.yml file. I now want one of the projects to be able to call a service of the other project and as far as I know I need to create a common docker network for that. So to create a minimal example I made two folders (a/ and b/) which both contain a docker-compose.yml file.

This is the one in folder a/:

version: '3'

services:
  common_server:
    image: ubuntu
    ports:
      - 4444:4444
    command: >
      bash -c '
      apt update && apt install netcat -y &&
      while true; do echo -e "HTTP/1.1 200 OK\n\npong" | nc -k -l -p 4444 -q 1; done'
#    networks:
#      - my_network

  project_a:
    image: ubuntu
    depends_on:
      - common_server
#    networks:
#      - my_network
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "AAAAAAAA"; curl common_server:4444; sleep 10; done'

#networks:
#  my_network:
#    driver: bridge

This sets up two things:

common_server: a simple ping/pong server which responds "pong" to every request it gets

project_a: a simple client which calls the common_server every 10 seconds

This works great like this. I quickly checked the docker networks using:

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== THIS NETWORK WAS CREATED
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local

I've got a second docker-compose.yml file in the folder b/ from which I also want to call the common_server defined in the file above. So I uncommented the lines with the network in the file above to enable my_network. Running that also works great.

When I check docker network ls again I also see the second network it created:

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== CREATED BY THE FIRST RUN
f0a42e17007b        a_my_network        bridge              local  <== CREATED BY THE SECOND RUN
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local

I then started the second docker-compose file:

version: '3'

services:
  project_b:
    image: ubuntu
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "BBBBBBB"; curl common_server:4444; sleep 10; done'
    networks:
     - a_my_network
networks:
  a_my_network:
    external: true

That also works. It can call the common_server from the first docker-compose file.

The first question I have: Although I define the network as my_network in the first file, it is called a_my_network by docker. Is there a way to define the network so that I can call it the same in both docker-compose files?

I then decided to remove those two networks using docker network prune, and start again. Unfortunately, when I now run the first file again I now get the following error:

$ docker-compose up
Creating network "a_my_network" with driver "bridge"
Starting a_common_server_1 ... error

ERROR: for a_common_server_1  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found

ERROR: for common_server  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found
ERROR: Encountered errors while bringing up the project.

So my second question: Why can I only start the first docker-compose file if I first create the a_default network by not explicitly defining a network?

Body:
When you declare the network in the second file you can explicitly specify its name:.

version: '3.7'  # minimum of 3.5
networks:
  my_network:
    external: true
    name: a_my_network

As you note at the beginning, though, Compose creates a default network for you, and if you don't explicitly declare networks: for a container it will attach to default.  You can reconfigure the default network however you'd like.

So probably what I'd do here is not declare networks: in the first docker-compose.yml file at all.  In the second I'd make the default network point at the first file's default network, and also not configure networks: for containers.

networks:
  default:
    external: true
    name: a_default

Compose keeps track of what's going on primarily by using labels on objects.  These are generally hidden from you but they're one of the things included in the very detailed docker inspect output.  In your last example, if you manually docker network prune a network out from under Compose, it starts to get confused.  On the other hand, if you just comment out the network you manually created and re-run docker-compose up, Compose should notice that it's created a network that's no longer needed and clean it up for you.


问:
How to get number of rows in <textarea > using JavaScript?
I have a <textarea> element.  Can I use JavaScript to detect that there are (for example) 10 rows of text in it?

答:
The simple way:</p>

```<code>var lines = document.querySelector("textarea").value.split(/\r\n|\r|\n/).length;
</code>```

Body:
The simple way:

var lines = document.querySelector("textarea").value.split(/\r\n|\r|\n/).length;


答:
Probably, you can try :

```<code>library(dplyr)

default_table %>%
  tidyr::crossing(test_result) %>%
  mutate(comparative_mean = x - t_mean)
</code>```

This creates all combinations of default_table with test_result and then we subtract the two values from each other.

Title: Using tidyverse to dynamically mutate one variable from one grouped dataset from another dataset

Body:
Probably, you can try :

library(dplyr)

default_table %>%
  tidyr::crossing(test_result) %>%
  mutate(comparative_mean = x - t_mean)

This creates all combinations of default_table with test_result and then we subtract the two values from each other.


问:
How to configure jest-mongodb(@shelf/jest-mongodb) in typescript-node project?
I am working on integration testing, So getting a data from database makes testcase execution slower. Tried with jest-mongodb to set up a temp db. but could not find a proper documentation for setting up jest-mongodb in typescript-nodejs project. please help me to overcome this issue.

test.ts(db configuration file based on this test suites connect to db)

```<code>export default {
    jwtPrivateKey: 'secretkey',
    // Testing Database configuration
    MongoDB: {
        dbConfig: {
            user: 'user name',
            host: 'some host',
            port: 'some port',
            authMechanism: 'some mechanism',
            authSource: 'access level',
            dbName: 'database name',
            metadata: 'initializer'
        }
    }
};
</code>```

答:
Create the file: typings/global.d.ts:

```<code>declare namespace NodeJS {
  export interface Global {
    __MONGO_URI__: string;
  }
}
</code>```

Then, in your tsconfig.json:

```<code>{
  "compilerOptions": { ... },
  "include": ["./src/**/*", "./typings/*"]
}

</code>```

Body:
I am working on integration testing, So getting a data from database makes testcase execution slower. Tried with jest-mongodb to set up a temp db. but could not find a proper documentation for setting up jest-mongodb in typescript-nodejs project. please help me to overcome this issue.

test.ts(db configuration file based on this test suites connect to db)

export default {
    jwtPrivateKey: 'secretkey',
    // Testing Database configuration
    MongoDB: {
        dbConfig: {
            user: 'user name',
            host: 'some host',
            port: 'some port',
            authMechanism: 'some mechanism',
            authSource: 'access level',
            dbName: 'database name',
            metadata: 'initializer'
        }
    }
};

Body:
Create the file: typings/global.d.ts:

declare namespace NodeJS {
  export interface Global {
    __MONGO_URI__: string;
  }
}

Then, in your tsconfig.json:

{
  "compilerOptions": { ... },
  "include": ["./src/**/*", "./typings/*"]
}