问:
"No suitable constructor was found for entity type" when adding migrations for entities with value objects
I have a Supplier entity

Supplier Entity

```<code>public class Supplier : BaseEntity
{
    public string? AccountCode { get; set; }
    public string? CompanyName { get; set; }
    public List<Address>? Addresses { get; set; } = new();
    public List<Person>? People { get; set; } = new();
    public List<SocialMediaAccount>? SocialMediaAccounts { get; set; } = new();
    public Media? Logo { get; set; }
    public Media? CoverPicture { get; set; }
}
</code>```

Address, Person and SocialMediaAccount are value objects as below; I am giving code for Address only since this is where the error occurs.

Address ValueObject

```<code>public class Address : ValueObject
{
    public string? AddressLabel { get; init; }
    public string? BuildingName { get; init; }
    public string? UnitNumber { get; set; }
    public string? StreetAddress1 { get; init; }
    public string? StreetAddress2 { get; init; }
    public string? MinorMunicipality { get; init; }
    public string? MajorMunicipality { get; init; }
    public string? County { get; init; }
    public string? PostCode { get; init; }
    public Country? Country { get; init; }

    public Address(string? addressLabel, string? buildingName, string? unitNumber, string? streetAddress1, string? streetAddress2, string? minorMunicipality, string? majorMunicipality, string? county, string? postCode, Country? country)
    {
        AddressLabel= addressLabel;
        BuildingName = buildingName;
        UnitNumber = unitNumber;
        StreetAddress1 = streetAddress1;
        StreetAddress2 = streetAddress2;
        MinorMunicipality = minorMunicipality;
        MajorMunicipality = majorMunicipality;
        County = county;
        PostCode = postCode;
        Country = country;
    }

    protected override IEnumerable<object?> GetEqualityComponents()
    {
        yield return AddressLabel;
        yield return BuildingName;
        yield return UnitNumber;
        yield return StreetAddress1;
        yield return StreetAddress2;
        yield return MinorMunicipality;
        yield return MajorMunicipality;
        yield return County;
        yield return PostCode;
        yield return Country;
    }
}
</code>```

Within the Address value object, Country ValueObject is also a value object

```<code>public class Country : ValueObject
{
    public string? Name { get; init; }
    public string? Alpha3Code { get; init; }
    public string? EmojiFlag { get; init; }

    public Country(string? name, string? alpha3Code, string? emojiFlag)
    {
        Name = name;
        Alpha3Code = alpha3Code;
        EmojiFlag = emojiFlag;
    }

    protected override IEnumerable<object?> GetEqualityComponents()
    {
        yield return Name;
        yield return Alpha3Code;
        yield return EmojiFlag;
    }
}
</code>```

My SupplierConfiguration class is as follows;

```<code>public class SupplierConfiguration : IEntityTypeConfiguration<Supplier>
{
    public void Configure(EntityTypeBuilder<Supplier> builder)
    {
        builder.Property(t => t.AccountCode)
            .HasMaxLength(32);

        builder.Property(t => t.CompanyName)
            .HasMaxLength(512)
            .IsRequired();

        builder.OwnsMany(p => p.Addresses, addressNavigationBuilder =>
        {
            addressNavigationBuilder.Property(t => t.AddressLabel).HasMaxLength(64).IsRequired();
            addressNavigationBuilder.Property(t => t.BuildingName).HasMaxLength(64);
            addressNavigationBuilder.Property(t => t.UnitNumber).HasMaxLength(32);
            addressNavigationBuilder.Property(t => t.StreetAddress1).HasMaxLength(256);
            addressNavigationBuilder.Property(t => t.StreetAddress2).HasMaxLength(256);
            addressNavigationBuilder.Property(t => t.MinorMunicipality).HasMaxLength(128);
            addressNavigationBuilder.Property(t => t.MajorMunicipality).HasMaxLength(128);
            addressNavigationBuilder.Property(t => t.County).HasMaxLength(128);
            addressNavigationBuilder.Property(t => t.PostCode).HasMaxLength(32);

            addressNavigationBuilder.OwnsOne(t => t.Country, countryNavigationBuilder =>
            {
                countryNavigationBuilder.Property(c => c.Name).HasMaxLength(64);
                countryNavigationBuilder.Property(c => c.Alpha3Code).HasMaxLength(3);
                countryNavigationBuilder.Property(c => c.EmojiFlag).HasMaxLength(50);
            });

        });

         builder.OwnsMany(p => p.SocialMediaAccounts, socialMediaAccountNavigationBuilder =>
            {
                socialMediaAccountNavigationBuilder.Property(t => t.Handle).HasMaxLength(maxLength: 128);
                socialMediaAccountNavigationBuilder.Property(t => t.FullURL).HasMaxLength(2048).IsRequired();
            });

        builder.OwnsMany(c => c.People, personNavigationBuilder =>
            {
                personNavigationBuilder.Property(t => t.Prefix).HasMaxLength(12);

                personNavigationBuilder.Property(t => t.FirstName).HasMaxLength(128).IsRequired();

                personNavigationBuilder.Property(t => t.MiddleName).HasMaxLength(128);

                personNavigationBuilder.Property(t => t.LastName).HasMaxLength(128).IsRequired();

                personNavigationBuilder.Property(t => t.JobTitle).HasMaxLength(128);

                personNavigationBuilder.Property(t => t.Notes).HasMaxLength(512);

                personNavigationBuilder.OwnsOne(p => p.ProfilePicture);

                personNavigationBuilder.OwnsMany(p => p.EmailAddresses, emailNavigationBuilder =>
                {
                    emailNavigationBuilder.Property(e => e.Email).HasMaxLength(128).IsRequired();
                    emailNavigationBuilder.Property(e => e.Label).HasMaxLength(128);
                });

                personNavigationBuilder.OwnsMany(p => p.SocialMediaAccounts, socialMediaAccountNavigationBuilder =>
                {
                    socialMediaAccountNavigationBuilder.Property(t => t.Handle).HasMaxLength(maxLength: 128);
                    socialMediaAccountNavigationBuilder.Property(t => t.FullURL).HasMaxLength(2048).IsRequired();
                });

                builder.OwnsOne(p => p.Logo, logoNavigationBuilder =>
                {
                    logoNavigationBuilder.Property(l => l.Label).HasMaxLength(128).IsRequired();
                    logoNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(64).IsRequired();
                    logoNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(512).IsRequired();
                });

                builder.OwnsOne(p => p.CoverPicture, coverPictureNavigationBuilder =>
                {
                    coverPictureNavigationBuilder.Property(l => l.Label).HasMaxLength(128).IsRequired();
                    coverPictureNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(64).IsRequired();
                    coverPictureNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(512).IsRequired();
                });

            });
    }
}
</code>```

When I try to run migration to create my initial database, I get the following error
No suitable constructor was found for entity type 'Supplier.Addresses#Address'. The following constructors had parameters that could not be bound to properties of the entity type:
Cannot bind 'country' in 'Supplier.Addresses#Address(string addressLabel, string buildingName, string unitNumber, string streetAddress1, string streetAddress2, string minorMunicipality, string majorMunicipality, string county, string postCode, Country country)'
Note that only mapped properties can be bound to constructor parameters. Navigations to related entities, including references to owned types, cannot be bound.

I would be grateful if someone help me solve this.

Body:
I have a Supplier entity

Supplier Entity

public class Supplier : BaseEntity
{
    public string? AccountCode { get; set; }
    public string? CompanyName { get; set; }
    public List<Address>? Addresses { get; set; } = new();
    public List<Person>? People { get; set; } = new();
    public List<SocialMediaAccount>? SocialMediaAccounts { get; set; } = new();
    public Media? Logo { get; set; }
    public Media? CoverPicture { get; set; }
}

Address, Person and SocialMediaAccount are value objects as below; I am giving code for Address only since this is where the error occurs.

Address ValueObject

public class Address : ValueObject
{
    public string? AddressLabel { get; init; }
    public string? BuildingName { get; init; }
    public string? UnitNumber { get; set; }
    public string? StreetAddress1 { get; init; }
    public string? StreetAddress2 { get; init; }
    public string? MinorMunicipality { get; init; }
    public string? MajorMunicipality { get; init; }
    public string? County { get; init; }
    public string? PostCode { get; init; }
    public Country? Country { get; init; }

    public Address(string? addressLabel, string? buildingName, string? unitNumber, string? streetAddress1, string? streetAddress2, string? minorMunicipality, string? majorMunicipality, string? county, string? postCode, Country? country)
    {
        AddressLabel= addressLabel;
        BuildingName = buildingName;
        UnitNumber = unitNumber;
        StreetAddress1 = streetAddress1;
        StreetAddress2 = streetAddress2;
        MinorMunicipality = minorMunicipality;
        MajorMunicipality = majorMunicipality;
        County = county;
        PostCode = postCode;
        Country = country;
    }

    protected override IEnumerable<object?> GetEqualityComponents()
    {
        yield return AddressLabel;
        yield return BuildingName;
        yield return UnitNumber;
        yield return StreetAddress1;
        yield return StreetAddress2;
        yield return MinorMunicipality;
        yield return MajorMunicipality;
        yield return County;
        yield return PostCode;
        yield return Country;
    }
}

Within the Address value object, Country ValueObject is also a value object

public class Country : ValueObject
{
    public string? Name { get; init; }
    public string? Alpha3Code { get; init; }
    public string? EmojiFlag { get; init; }

    public Country(string? name, string? alpha3Code, string? emojiFlag)
    {
        Name = name;
        Alpha3Code = alpha3Code;
        EmojiFlag = emojiFlag;
    }

    protected override IEnumerable<object?> GetEqualityComponents()
    {
        yield return Name;
        yield return Alpha3Code;
        yield return EmojiFlag;
    }
}

My SupplierConfiguration class is as follows;

public class SupplierConfiguration : IEntityTypeConfiguration<Supplier>
{
    public void Configure(EntityTypeBuilder<Supplier> builder)
    {
        builder.Property(t => t.AccountCode)
            .HasMaxLength(32);

        builder.Property(t => t.CompanyName)
            .HasMaxLength(512)
            .IsRequired();

        builder.OwnsMany(p => p.Addresses, addressNavigationBuilder =>
        {
            addressNavigationBuilder.Property(t => t.AddressLabel).HasMaxLength(64).IsRequired();
            addressNavigationBuilder.Property(t => t.BuildingName).HasMaxLength(64);
            addressNavigationBuilder.Property(t => t.UnitNumber).HasMaxLength(32);
            addressNavigationBuilder.Property(t => t.StreetAddress1).HasMaxLength(256);
            addressNavigationBuilder.Property(t => t.StreetAddress2).HasMaxLength(256);
            addressNavigationBuilder.Property(t => t.MinorMunicipality).HasMaxLength(128);
            addressNavigationBuilder.Property(t => t.MajorMunicipality).HasMaxLength(128);
            addressNavigationBuilder.Property(t => t.County).HasMaxLength(128);
            addressNavigationBuilder.Property(t => t.PostCode).HasMaxLength(32);

            addressNavigationBuilder.OwnsOne(t => t.Country, countryNavigationBuilder =>
            {
                countryNavigationBuilder.Property(c => c.Name).HasMaxLength(64);
                countryNavigationBuilder.Property(c => c.Alpha3Code).HasMaxLength(3);
                countryNavigationBuilder.Property(c => c.EmojiFlag).HasMaxLength(50);
            });

        });

         builder.OwnsMany(p => p.SocialMediaAccounts, socialMediaAccountNavigationBuilder =>
            {
                socialMediaAccountNavigationBuilder.Property(t => t.Handle).HasMaxLength(maxLength: 128);
                socialMediaAccountNavigationBuilder.Property(t => t.FullURL).HasMaxLength(2048).IsRequired();
            });

        builder.OwnsMany(c => c.People, personNavigationBuilder =>
            {
                personNavigationBuilder.Property(t => t.Prefix).HasMaxLength(12);

                personNavigationBuilder.Property(t => t.FirstName).HasMaxLength(128).IsRequired();

                personNavigationBuilder.Property(t => t.MiddleName).HasMaxLength(128);

                personNavigationBuilder.Property(t => t.LastName).HasMaxLength(128).IsRequired();

                personNavigationBuilder.Property(t => t.JobTitle).HasMaxLength(128);

                personNavigationBuilder.Property(t => t.Notes).HasMaxLength(512);

                personNavigationBuilder.OwnsOne(p => p.ProfilePicture);

                personNavigationBuilder.OwnsMany(p => p.EmailAddresses, emailNavigationBuilder =>
                {
                    emailNavigationBuilder.Property(e => e.Email).HasMaxLength(128).IsRequired();
                    emailNavigationBuilder.Property(e => e.Label).HasMaxLength(128);
                });

                personNavigationBuilder.OwnsMany(p => p.SocialMediaAccounts, socialMediaAccountNavigationBuilder =>
                {
                    socialMediaAccountNavigationBuilder.Property(t => t.Handle).HasMaxLength(maxLength: 128);
                    socialMediaAccountNavigationBuilder.Property(t => t.FullURL).HasMaxLength(2048).IsRequired();
                });

                builder.OwnsOne(p => p.Logo, logoNavigationBuilder =>
                {
                    logoNavigationBuilder.Property(l => l.Label).HasMaxLength(128).IsRequired();
                    logoNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(64).IsRequired();
                    logoNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(512).IsRequired();
                });

                builder.OwnsOne(p => p.CoverPicture, coverPictureNavigationBuilder =>
                {
                    coverPictureNavigationBuilder.Property(l => l.Label).HasMaxLength(128).IsRequired();
                    coverPictureNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(64).IsRequired();
                    coverPictureNavigationBuilder.Property(l => l.MediaFor).HasMaxLength(512).IsRequired();
                });

            });
    }
}

When I try to run migration to create my initial database, I get the following error
No suitable constructor was found for entity type 'Supplier.Addresses#Address'. The following constructors had parameters that could not be bound to properties of the entity type:
Cannot bind 'country' in 'Supplier.Addresses#Address(string addressLabel, string buildingName, string unitNumber, string streetAddress1, string streetAddress2, string minorMunicipality, string majorMunicipality, string county, string postCode, Country country)'
Note that only mapped properties can be bound to constructor parameters. Navigations to related entities, including references to owned types, cannot be bound.

I would be grateful if someone help me solve this.


来源: stackexchange

问:
Not sure why JavaScript Array.prototype.filter approach runs faster than a second approach
I have two different approaches to filtering an array of objects based on an array of "active codes" that each objects attribute "indCode" is compared against. I thought the 'bucketFilter' approach would have less time complexity, and run faster, but in fact the 'basicFilter' function utilizing .filter() is faster. Need help understanding why.

```<code>function createTest (num) {
  const returnArray = [];

  for (let i = 0, end = num; i < end; i++) {
    const testObj = {},
      codeGenerate = Math.floor(Math.random() * 6) + 1;

    switch(codeGenerate) {
        case 1:
        testObj.indCode = '01';
        break;
      case 2:
        testObj.indCode = '02';
        break;
      case 3:
        testObj.indCode = '03';
        break;
      case 4:
        testObj.indCode = '04';
        break;
      case 5:
        testObj.indCode = '05';
        break;
      case 6:
        testObj.indCode = '06';
        break;
    }

    testObj.name = 'Test' + i;
    returnArray.push(testObj);
  }

  return returnArray;
}

const activeCodes = ['01', '02', '03', '04', '05', '06'];

const bucketFilter = (filterArr) => {
  const buckets = [ [], [], [], [], [], [] ],
    codeIndexMap = {
      '01': 0,
      '02': 1,
      '03': 2,
      '04': 3,
      '05': 4,
      '06': 5
    },
    finalArr = [];

    console.time('bucketFiltering');

    // Break up into buckets
    for (let i = 0, end = filterArr.length; i < end; i++) {
        const bucketIndex = codeIndexMap[filterArr[i].indCode];
      buckets[bucketIndex].push(filterArr[i]);
    }

    // breakdown selected arrays and push to finalArr
    for (let i = 0, end = activeCodes.length; i < end; i++) {
        const currentCode = activeCodes[i],
        currentBucket = buckets[codeIndexMap[currentCode]];

      for (let j = 0,  jEnd = currentBucket.length; j < jEnd; j++) {
        finalArr.push(currentBucket[j]);
      }
    }
    console.timeEnd('bucketFiltering');
    return finalArr;
};

const basicFiltering = (filterArr) => {
    const filteredArray = filterArr.filter((obj, index) => {
    if (index === 0) {
      console.time('basicFiltering');
    }
    if (index === filterArr.length -1) {
      console.timeEnd('basicFiltering');
    }
    return activeCodes.includes(obj.indCode) && obj;
  });

  return filteredArray;
}

const testData = createTest(4000);

const bucketFiltered =  bucketFilter(testData);
const basicFiltered = basicFiltering(testData);

console.log('%cBucket Filtering', 'color: aquamarine', bucketFiltered);
console.log('%cBasic Filtering', 'color: orange', basicFiltered);
</code>```

As stated above, I have two functions. One is labeled basicFiltering, and just utilizes the native .filter() method. The function loops through some test data once, comparing each item against an array of active codes, and returns the object if there is a match.

The second function, is borrowed from Radix sort, and loops through once, breaking everything up into smaller "bucket" arrays based on an attribute named indCode. We then loop through an array containing the active codes utilized in the previous function as well. For each entry, pull that corresponding "bucket", and push to final array that we will flatten later. After all buckets are added, flatten and return the array.

Now this is where I'm getting confused, from my understanding, while less readable, the second function (or the bucket approach) should have less time complexity and total iterations, and thus be faster. Instead, it runs slightly slower than the first approach. I understand that .filter() is faster, I would just like someone to tell me why.

ContentLicense: CC BY-SA 4.0

Body:
I have two different approaches to filtering an array of objects based on an array of "active codes" that each objects attribute "indCode" is compared against. I thought the 'bucketFilter' approach would have less time complexity, and run faster, but in fact the 'basicFilter' function utilizing .filter() is faster. Need help understanding why.

function createTest (num) {
  const returnArray = [];

  for (let i = 0, end = num; i < end; i++) {
    const testObj = {},
      codeGenerate = Math.floor(Math.random() * 6) + 1;

    switch(codeGenerate) {
        case 1:
        testObj.indCode = '01';
        break;
      case 2:
        testObj.indCode = '02';
        break;
      case 3:
        testObj.indCode = '03';
        break;
      case 4:
        testObj.indCode = '04';
        break;
      case 5:
        testObj.indCode = '05';
        break;
      case 6:
        testObj.indCode = '06';
        break;
    }

    testObj.name = 'Test' + i;
    returnArray.push(testObj);
  }

  return returnArray;
}

const activeCodes = ['01', '02', '03', '04', '05', '06'];

const bucketFilter = (filterArr) => {
  const buckets = [ [], [], [], [], [], [] ],
    codeIndexMap = {
      '01': 0,
      '02': 1,
      '03': 2,
      '04': 3,
      '05': 4,
      '06': 5
    },
    finalArr = [];

    console.time('bucketFiltering');

    // Break up into buckets
    for (let i = 0, end = filterArr.length; i < end; i++) {
        const bucketIndex = codeIndexMap[filterArr[i].indCode];
      buckets[bucketIndex].push(filterArr[i]);
    }

    // breakdown selected arrays and push to finalArr
    for (let i = 0, end = activeCodes.length; i < end; i++) {
        const currentCode = activeCodes[i],
        currentBucket = buckets[codeIndexMap[currentCode]];

      for (let j = 0,  jEnd = currentBucket.length; j < jEnd; j++) {
        finalArr.push(currentBucket[j]);
      }
    }
    console.timeEnd('bucketFiltering');
    return finalArr;
};

const basicFiltering = (filterArr) => {
    const filteredArray = filterArr.filter((obj, index) => {
    if (index === 0) {
      console.time('basicFiltering');
    }
    if (index === filterArr.length -1) {
      console.timeEnd('basicFiltering');
    }
    return activeCodes.includes(obj.indCode) && obj;
  });

  return filteredArray;
}

const testData = createTest(4000);

const bucketFiltered =  bucketFilter(testData);
const basicFiltered = basicFiltering(testData);

console.log('%cBucket Filtering', 'color: aquamarine', bucketFiltered);
console.log('%cBasic Filtering', 'color: orange', basicFiltered);

As stated above, I have two functions. One is labeled basicFiltering, and just utilizes the native .filter() method. The function loops through some test data once, comparing each item against an array of active codes, and returns the object if there is a match.

The second function, is borrowed from Radix sort, and loops through once, breaking everything up into smaller "bucket" arrays based on an attribute named indCode. We then loop through an array containing the active codes utilized in the previous function as well. For each entry, pull that corresponding "bucket", and push to final array that we will flatten later. After all buckets are added, flatten and return the array.

Now this is where I'm getting confused, from my understanding, while less readable, the second function (or the bucket approach) should have less time complexity and total iterations, and thus be faster. Instead, it runs slightly slower than the first approach. I understand that .filter() is faster, I would just like someone to tell me why.


问:
Baseball Spray Charts - R
I am looking to create a baseball field function that creates spray charts using section percentage vectors. Instead of using (x,y) coordinates, I am looking to create a spray chart that applies these percentage vectors to its corresponding location--also adjusting the background color based on size of value, maybe 20% results in dark green and 10% results in lighter green and < 5% results in white.

An example of data is shown below:

RF
CF
LF
3B
SS
2B
1B
C
P
LFTCENTER
UPTHEMIDDLE
RGHTCENTER

9
6
9
9
6
19
3
3
9
9
3
12

I would like to take this data and create an object that looks something like what's show below:

I would like to do this because my data isn't in-depth enough to have coordinates of batted ball position, so my spray chart would vary from the "normal" spray chart:

I have searched the web to create this spray chart I am looking for, but everything I found was formatted in different coding languages I am not familiar with. I was able to create these percentages quite easily from play-by-play data--which is helpful in itself, but I would like to create visualizations.

Note: I am working in R.

Title: Baseball Spray Charts - R


问:
c# compact framework 3.5 importing multiple certificates
I would like to use C# Compact Framework (CF) 3.5 to import multiple X509Certificates. The existing library System.Security.Cryptography.X509Certificates supports single certificate import. Is there a way to import multiple certificates using using C# Compact Framework? Has anybody implemented this previously in a way that I can reference?

Newer versions of C# support X509CertificatesCollection which is not available in the CF that I am using.

I have pre-defined dependencies on an existing platform that require me to use

c#

Compact Framework 3.5

Windows CE

I have implemented this and tried to reverse engineer the X509CertificateCollection.

```<code>using System.Security.Cryptography.X509Certificates;

class MyProgram
{

    static void Main(string[] args)
    {
        string fileName = "c:\\cert\\file_0.cer";
        string password = "Labuser1";
        bool result  = isSingleCertificate(fileName, password);
        ParseMultipleCertificates(fileName, password);
    }

    static bool isSingleCertificate(string path, string password)
    {
        bool isSingle; // = true;
        X509Certificate2Collection collection = new X509Certificate2Collection();
        // X509CertificateCollection collection = new X509CertificateCollection();
        collection.Import(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        isSingle = (collection.Count == 1) ? true : false;
        return isSingle;
    }

    static List<string> ParseMultipleCertificates(string path, string password)
    {
        X509Certificate2Collection collection = new X509Certificate2Collection();
        // X509CertificateCollection collection = new X509CertificateCollection();

        collection.Import(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        int index = 0;
        List<string> filePathList = new List<string>();

         int inc = 0;

        foreach (X509Certificate2 cert in collection)
        {
            ++inc;
            string filename = "c:\\cert\\temp\\file_" + inc.ToString() + ".cer"; // = GetTempFilePathWithExtension(".cer");
            filePathList.Add(filename);
            byte[] myArray = new byte[10000];
            if (password.Length > 0) myArray = cert.Export(X509ContentType.Cert, password);
            else cert.Export(X509ContentType.Cert);

            using (FileStream fileStream = new FileStream(filename, FileMode.Create))
            {
                for (int i = 0; i < myArray.Length; i++)
                {
                    fileStream.WriteByte(myArray[i]);
                }

                fileStream.Seek(0, SeekOrigin.Begin);
                fileStream.Close();
            }
        }
        return filePathList;
    }
}
</code>```

Body:
I would like to use C# Compact Framework (CF) 3.5 to import multiple X509Certificates. The existing library System.Security.Cryptography.X509Certificates supports single certificate import. Is there a way to import multiple certificates using using C# Compact Framework? Has anybody implemented this previously in a way that I can reference?

Newer versions of C# support X509CertificatesCollection which is not available in the CF that I am using.

I have pre-defined dependencies on an existing platform that require me to use

c#

Compact Framework 3.5

Windows CE

I have implemented this and tried to reverse engineer the X509CertificateCollection.

using System.Security.Cryptography.X509Certificates;

class MyProgram
{

    static void Main(string[] args)
    {
        string fileName = "c:\\cert\\file_0.cer";
        string password = "Labuser1";
        bool result  = isSingleCertificate(fileName, password);
        ParseMultipleCertificates(fileName, password);
    }

    static bool isSingleCertificate(string path, string password)
    {
        bool isSingle; // = true;
        X509Certificate2Collection collection = new X509Certificate2Collection();
        // X509CertificateCollection collection = new X509CertificateCollection();
        collection.Import(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        isSingle = (collection.Count == 1) ? true : false;
        return isSingle;
    }

    static List<string> ParseMultipleCertificates(string path, string password)
    {
        X509Certificate2Collection collection = new X509Certificate2Collection();
        // X509CertificateCollection collection = new X509CertificateCollection();

        collection.Import(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        int index = 0;
        List<string> filePathList = new List<string>();

         int inc = 0;

        foreach (X509Certificate2 cert in collection)
        {
            ++inc;
            string filename = "c:\\cert\\temp\\file_" + inc.ToString() + ".cer"; // = GetTempFilePathWithExtension(".cer");
            filePathList.Add(filename);
            byte[] myArray = new byte[10000];
            if (password.Length > 0) myArray = cert.Export(X509ContentType.Cert, password);
            else cert.Export(X509ContentType.Cert);

            using (FileStream fileStream = new FileStream(filename, FileMode.Create))
            {
                for (int i = 0; i < myArray.Length; i++)
                {
                    fileStream.WriteByte(myArray[i]);
                }

                fileStream.Seek(0, SeekOrigin.Begin);
                fileStream.Close();
            }
        }
        return filePathList;
    }
}


问:
Why I am getting Segmentation fault error in C programming while changing character in string using index?
While learnng about pointer in C, I am getting Segmentation fault error in an online compiler because of changing value of a particular character of a stirng variable. I first tried it in my local compiler but it was printing nothing as output. What is the reason for the problem, and how can it be solved?

Code I write is :

```<code>#include <stdio.h>

int main(void)
{
    char *a = "abcd";
    a[0] = 'A';

    printf("%s\n",a);

}
</code>```

Output of online compiler :

```<code>Segmentation fault
</code>```

Output of offline compiler was nothing.

Body:
While learnng about pointer in C, I am getting Segmentation fault error in an online compiler because of changing value of a particular character of a stirng variable. I first tried it in my local compiler but it was printing nothing as output. What is the reason for the problem, and how can it be solved?

Code I write is :

#include <stdio.h>

int main(void)
{
    char *a = "abcd";
    a[0] = 'A';

    printf("%s\n",a);

}

Output of online compiler :

Segmentation fault

Output of offline compiler was nothing.


问:
How to filter after group by in this Dune Analytics example?
This dune analytics script is trying to 1) obtain the list of the most traded NFT projects in the last 30 days and 2) add a row of a single collection ("Wicked Ape Bone Club" - contract address = 0xbe6e3669464E7dB1e1528212F0BfF5039461CB82).

While it does add the specific collection to the top 30 table, it doesn't preserve the correct ranking. The ranking shouldn't be 1, and should be a lot lower. Apparently, the HAVING after GROUP BY happens before the aggregation. How can the second filtering (obtaining only the row with the single specified collection) be done after the aggregation?

Code below

```<code>(SELECT
                ROW_NUMBER() OVER (ORDER BY SUM(original_amount) DESC) AS "Rank",
                CASE WHEN nftp."nft_collection" IS NOT NULL THEN CONCAT('<a href="',nftp.url,'" target="_blank">',nftp.nft_collection,'</a>')
                ELSE CONCAT('<a href="https://etherscan.io/token/0',SUBSTRING("nft_contract_address"::text, 2),'">',CONCAT('0',SUBSTRING("nft_contract_address"::text, 2)),'</a>') END AS "OPENSEA",
                COUNT(tx_hash) AS "Sales",
                SUM(original_amount) AS "Volume ETH",
                percentile_cont(.1) within GROUP (ORDER BY original_amount) AS "Floor Price",
                percentile_cont(.5) within GROUP (ORDER BY original_amount) AS "Median",
                nft_contract_address
            FROM nft.trades n
                LEFT JOIN dune_user_generated."cryptuschrist_nft_projects2" nftp on nftp."nft_contract" = n.nft_contract_address
                    WHERE  (block_time > now() - interval  '30 day')
                        AND number_of_items = 1
                        AND original_currency in ('ETH','WETH')
                        AND nft_contract_address NOT IN ('\xc36cf0cfcb5d905b8b513860db0cfe63f6cf9f5c', '\x4e1f41613c9084fdb9e34e11fae9412427480e56', '\x7bd29408f11d2bfc23c34f18275bbf23bb716bc7', '\xce25e60a89f200b1fa40f6c313047ffe386992c3', '\xfb3765e0e7ac73e736566af913fa58c3cfd686b7','\x495f947276749ce646f68ac8c248420045cb7b5e','\xc99f70bfd82fb7c8f8191fdfbfb735606b15e5c5','\xb932a70a57673d89f4acffbe830e8ed7f75fb9e0', '\x3b3ee1931dc30c1957379fac9aba94d1c48a5405')
                        GROUP BY nft_contract_address , nftp.nft_collection, nftp.url
                        HAVING nft_contract_address IN ('\xbe6e3669464E7dB1e1528212F0BfF5039461CB82')
                        )

UNION
    (SELECT
            ROW_NUMBER() OVER (ORDER BY SUM(original_amount) DESC) AS "Rank",
            CASE WHEN nftp."nft_collection" IS NOT NULL THEN CONCAT('<a href="',nftp.url,'" target="_blank">',nftp.nft_collection,'</a>')
            ELSE CONCAT('<a href="https://etherscan.io/token/0',SUBSTRING("nft_contract_address"::text, 2),'">',CONCAT('0',SUBSTRING("nft_contract_address"::text, 2)),'</a>') END AS "OPENSEA",
            COUNT(tx_hash) AS "Sales",
            SUM(original_amount) AS "Volume ETH",
            percentile_cont(.1) within GROUP (ORDER BY original_amount) AS "Floor Price",
            percentile_cont(.5) within GROUP (ORDER BY original_amount) AS "Median",
            nft_contract_address
        FROM nft.trades n
            LEFT JOIN dune_user_generated."cryptuschrist_nft_projects2" nftp on nftp."nft_contract" = n.nft_contract_address
                WHERE  (block_time > now() - interval  '30 day')
                    AND number_of_items = 1
                    AND original_currency in ('ETH','WETH')
                    AND nft_contract_address NOT IN ('\xc36cf0cfcb5d905b8b513860db0cfe63f6cf9f5c', '\x4e1f41613c9084fdb9e34e11fae9412427480e56', '\x7bd29408f11d2bfc23c34f18275bbf23bb716bc7', '\xce25e60a89f200b1fa40f6c313047ffe386992c3', '\xfb3765e0e7ac73e736566af913fa58c3cfd686b7','\x495f947276749ce646f68ac8c248420045cb7b5e','\xc99f70bfd82fb7c8f8191fdfbfb735606b15e5c5','\xb932a70a57673d89f4acffbe830e8ed7f75fb9e0', '\x3b3ee1931dc30c1957379fac9aba94d1c48a5405')
                        GROUP BY nft_contract_address , nftp.nft_collection, nftp.url
                        ORDER BY 4 DESC
                        LIMIT '30'
                        )
ORDER BY "Rank" ASC
</code>```

Body:
This dune analytics script is trying to 1) obtain the list of the most traded NFT projects in the last 30 days and 2) add a row of a single collection ("Wicked Ape Bone Club" - contract address = 0xbe6e3669464E7dB1e1528212F0BfF5039461CB82).

While it does add the specific collection to the top 30 table, it doesn't preserve the correct ranking. The ranking shouldn't be 1, and should be a lot lower. Apparently, the HAVING after GROUP BY happens before the aggregation. How can the second filtering (obtaining only the row with the single specified collection) be done after the aggregation?

Code below

(SELECT
                ROW_NUMBER() OVER (ORDER BY SUM(original_amount) DESC) AS "Rank",
                CASE WHEN nftp."nft_collection" IS NOT NULL THEN CONCAT('',nftp.nft_collection,'')
                ELSE CONCAT('',CONCAT('0',SUBSTRING("nft_contract_address"::text, 2)),'') END AS "OPENSEA",
                COUNT(tx_hash) AS "Sales",
                SUM(original_amount) AS "Volume ETH",
                percentile_cont(.1) within GROUP (ORDER BY original_amount) AS "Floor Price",
                percentile_cont(.5) within GROUP (ORDER BY original_amount) AS "Median",
                nft_contract_address
            FROM nft.trades n
                LEFT JOIN dune_user_generated."cryptuschrist_nft_projects2" nftp on nftp."nft_contract" = n.nft_contract_address
                    WHERE  (block_time > now() - interval  '30 day')
                        AND number_of_items = 1
                        AND original_currency in ('ETH','WETH')
                        AND nft_contract_address NOT IN ('\xc36cf0cfcb5d905b8b513860db0cfe63f6cf9f5c', '\x4e1f41613c9084fdb9e34e11fae9412427480e56', '\x7bd29408f11d2bfc23c34f18275bbf23bb716bc7', '\xce25e60a89f200b1fa40f6c313047ffe386992c3', '\xfb3765e0e7ac73e736566af913fa58c3cfd686b7','\x495f947276749ce646f68ac8c248420045cb7b5e','\xc99f70bfd82fb7c8f8191fdfbfb735606b15e5c5','\xb932a70a57673d89f4acffbe830e8ed7f75fb9e0', '\x3b3ee1931dc30c1957379fac9aba94d1c48a5405')
                        GROUP BY nft_contract_address , nftp.nft_collection, nftp.url
                        HAVING nft_contract_address IN ('\xbe6e3669464E7dB1e1528212F0BfF5039461CB82')
                        )

UNION
    (SELECT
            ROW_NUMBER() OVER (ORDER BY SUM(original_amount) DESC) AS "Rank",
            CASE WHEN nftp."nft_collection" IS NOT NULL THEN CONCAT('',nftp.nft_collection,'')
            ELSE CONCAT('',CONCAT('0',SUBSTRING("nft_contract_address"::text, 2)),'') END AS "OPENSEA",
            COUNT(tx_hash) AS "Sales",
            SUM(original_amount) AS "Volume ETH",
            percentile_cont(.1) within GROUP (ORDER BY original_amount) AS "Floor Price",
            percentile_cont(.5) within GROUP (ORDER BY original_amount) AS "Median",
            nft_contract_address
        FROM nft.trades n
            LEFT JOIN dune_user_generated."cryptuschrist_nft_projects2" nftp on nftp."nft_contract" = n.nft_contract_address
                WHERE  (block_time > now() - interval  '30 day')
                    AND number_of_items = 1
                    AND original_currency in ('ETH','WETH')
                    AND nft_contract_address NOT IN ('\xc36cf0cfcb5d905b8b513860db0cfe63f6cf9f5c', '\x4e1f41613c9084fdb9e34e11fae9412427480e56', '\x7bd29408f11d2bfc23c34f18275bbf23bb716bc7', '\xce25e60a89f200b1fa40f6c313047ffe386992c3', '\xfb3765e0e7ac73e736566af913fa58c3cfd686b7','\x495f947276749ce646f68ac8c248420045cb7b5e','\xc99f70bfd82fb7c8f8191fdfbfb735606b15e5c5','\xb932a70a57673d89f4acffbe830e8ed7f75fb9e0', '\x3b3ee1931dc30c1957379fac9aba94d1c48a5405')
                        GROUP BY nft_contract_address , nftp.nft_collection, nftp.url
                        ORDER BY 4 DESC
                        LIMIT '30'
                        )
ORDER BY "Rank" ASC


问:
How to fix the Duplicate Object Angular
I have 2 row each row has a button each index, Once i open it, it will show a textbox you can input anything once you submit it. it will pass the data to the result; and put it to the this.name so here is my problem once i saved it to my web api i got the duplicate data which i i don't know why anyone could help me.

here i input

```<code>Index(0)
0: {ArrayList: 0, itemName: 'TEST001A'}
1: {ArrayList: 0, itemName: 'TEST001B'}
length: 2
[[Prototype]]: Array(0)

Index(1)
0: {ArrayList: 576, itemName: 'TEST002A'}
1: {ArrayList: 576, itemName: 'TEST002B'}
length: 2
[[Prototype]]: Array(0)
</code>```

But Once i Saved it, it gives me this result

```<code>TEST002A
TEST002B
TEST002A
TEST002B
</code>```

here i retrieved my data once i close the dialog!

```<code>dialogRef.afterClosed().subscribe((result) => {
   this.names= result
    })
</code>```

here i post all my data.

```<code>  onSave(){
    for(const details of this.fg.value?.displayArray){
            this.service.pD(details).subscribe((resp) =>{
              this.test001 = resp.id;
              for(let i = 0; i < this.names.length; i++){
                this.names[i].ArrayList = this.test001
              this.service.pS(this.names[i]).subscribe((res)=>{
                console.log(res)
              })
            }
        })
      }
     }
</code>```

here is the example of the code:https://stackblitz.com/edit/angular-d6nfhr-1lrbkb

Title: How to fix the Duplicate Object Angular

Body:
I have 2 row each row has a button each index, Once i open it, it will show a textbox you can input anything once you submit it. it will pass the data to the result; and put it to the this.name so here is my problem once i saved it to my web api i got the duplicate data which i i don't know why anyone could help me.

here i input

Index(0)
0: {ArrayList: 0, itemName: 'TEST001A'}
1: {ArrayList: 0, itemName: 'TEST001B'}
length: 2
[[Prototype]]: Array(0)

Index(1)
0: {ArrayList: 576, itemName: 'TEST002A'}
1: {ArrayList: 576, itemName: 'TEST002B'}
length: 2
[[Prototype]]: Array(0)

But Once i Saved it, it gives me this result

TEST002A
TEST002B
TEST002A
TEST002B

here i retrieved my data once i close the dialog!

dialogRef.afterClosed().subscribe((result) => {
   this.names= result
    })

here i post all my data.

  onSave(){
    for(const details of this.fg.value?.displayArray){
            this.service.pD(details).subscribe((resp) =>{
              this.test001 = resp.id;
              for(let i = 0; i < this.names.length; i++){
                this.names[i].ArrayList = this.test001
              this.service.pS(this.names[i]).subscribe((res)=>{
                console.log(res)
              })
            }
        })
      }
     }

here is the example of the code:https://stackblitz.com/edit/angular-d6nfhr-1lrbkb


问:
Is there a way to reload a Django template screen using the previous request data to an API call?
I built a simple weather app utilizing the OpenWeatherMap API using Python/Django and Django Templates for the client side. I created a refresh button in the
 using an  and  tag, which is intended to refresh to the most current weather information for the currently queried city, but when I click on it, it refreshes the page and shows the weather info for the default city, which I set it to 'Chicago' in views.py. Is there a way to set the refresh button to show the weather info for the currently queried city and not the default city?

views.py :

```<code>def index(request):
    configure()
    if 'city' in request.POST:
        city = request.POST['city']
    else:
        city = 'Chicago'

    appid = os.getenv('OPEN_WEATHER_API_KEY')
    URL = 'https://api.openweathermap.org/data/2.5/weather'
    PARAMS = {'q': city, 'appid': appid, 'units': 'imperial'}
    r = requests.get(url=URL, params=PARAMS)
    if r:
        print(f"==> SUCCESS!: Here's the weather information for {city}. <==")
    elif city == '':
        messages.info(
            request, f'Please enter a city or country.')
        print(
            f'!!==> ERROR: User submitted an empty field. <==!!')
        return redirect('/')
    else:
        messages.info(
            request, f"'{city}' does not exist! Please check your spelling and try searching for a different city or country.")
        print(
            f"!!==> ERROR: User entered '{city}'. This value does not exist. <==!!")
        return redirect('/')
    res = r.json()
    description = res['weather'][0]['description']
    icon = res['weather'][0]['icon']
    temp = res['main']['temp']
    city = res['name']
    country = res['sys']['country']

    day = datetime.date.today()

    return render(request, 'blizzrd/index.html', {'description': description, 'icon': icon, 'temp': temp, 'city': city, 'day': day, 'country': country})
</code>```

index.html:

```<code>{% load static %}
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blizzrd</title>
    <link rel="shortcut icon" type="image/png" href="{% static 'images/blizzrd_tab_logo.png' %}" />
    <meta name="description" content="description"/>
    <meta name="author" content="author" />
    <meta name="keywords" content="keywords" />
    <link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css" />
  </head>
  <body>
    <video autoplay playsinline loop muted>
      <source src="{% static 'images/blizzrd_background.mp4' %}" type="video/mp4">
    </video>
    <img src="https://i.postimg.cc/fW1xwWyH/blizzrd-logo.png" alt="logo" id="logo" />
    <h1 class="header">Local forecast by city</h1>
    <form method="POST">{% csrf_token %}
      <input type='text' placeholder="Enter city" name="city" />
      <button type="submit">Brrr</button>
    </form>
    <div class="error-grid">
      {% for message in messages %}
      <h3>{{message}}</h3>
      {% endfor %}
    </div>
    <div class="info-grid">
      <div>
        <h1>{{city}}, {{country}}</h1>
        <h2>{{description}}</h2>
        <h2 class="temp">{{temp}}ºF</h2>
        <h2>{{day}}</h2>
      </div>
      <img src="http://openweathermap.org/img/w/{{icon}}.png" width="100px" />
      <a href="{{ request.get_full_path }}">
        <img src="{% static 'images/reload_icon.png' %}" alt="reload" class="reload" />
      </a>
    </div>
  </body>
</html>
</code>```

href="http://devapp.pythonanywhere.com/" rel="nofollow noreferrer">link to weather app

I tried setting up my request like this instead, but it still refreshes to the default 'Chicago' city:

```<code>configure()
    if 'city' in request.POST:
        city = request.POST['city']
    elif '' in request.POST:
        city = r.city
    else:
        city = 'Chicago'
</code>```

Body:
I built a simple weather app utilizing the OpenWeatherMap API using Python/Django and Django Templates for the client side. I created a refresh button in the
 using an  and  tag, which is intended to refresh to the most current weather information for the currently queried city, but when I click on it, it refreshes the page and shows the weather info for the default city, which I set it to 'Chicago' in views.py. Is there a way to set the refresh button to show the weather info for the currently queried city and not the default city?

views.py :

def index(request):
    configure()
    if 'city' in request.POST:
        city = request.POST['city']
    else:
        city = 'Chicago'

    appid = os.getenv('OPEN_WEATHER_API_KEY')
    URL = 'https://api.openweathermap.org/data/2.5/weather'
    PARAMS = {'q': city, 'appid': appid, 'units': 'imperial'}
    r = requests.get(url=URL, params=PARAMS)
    if r:
        print(f"==> SUCCESS!: Here's the weather information for {city}. <==")
    elif city == '':
        messages.info(
            request, f'Please enter a city or country.')
        print(
            f'!!==> ERROR: User submitted an empty field. <==!!')
        return redirect('/')
    else:
        messages.info(
            request, f"'{city}' does not exist! Please check your spelling and try searching for a different city or country.")
        print(
            f"!!==> ERROR: User entered '{city}'. This value does not exist. <==!!")
        return redirect('/')
    res = r.json()
    description = res['weather'][0]['description']
    icon = res['weather'][0]['icon']
    temp = res['main']['temp']
    city = res['name']
    country = res['sys']['country']

    day = datetime.date.today()

    return render(request, 'blizzrd/index.html', {'description': description, 'icon': icon, 'temp': temp, 'city': city, 'day': day, 'country': country})

index.html:

{% load static %}
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blizzrd</title>
    <link rel="shortcut icon" type="image/png" href="{% static 'images/blizzrd_tab_logo.png' %}" />
    <meta name="description" content="description"/>
    <meta name="author" content="author" />
    <meta name="keywords" content="keywords" />
    <link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css" />

    <video autoplay playsinline loop muted>
      <source src="{% static 'images/blizzrd_background.mp4' %}" type="video/mp4">
    </video>

Local forecast by city

    <form method="POST">{% csrf_token %}
      <input type='text' placeholder="Enter city" name="city" />
      <button type="submit">Brrr</button>
    </form>

      {% for message in messages %}

{{message}}

      {% endfor %}

{{city}}, {{country}}

{{description}}

{{temp}}ºF

{{day}}

link to weather app

I tried setting up my request like this instead, but it still refreshes to the default 'Chicago' city:

configure()
    if 'city' in request.POST:
        city = request.POST['city']
    elif '' in request.POST:
        city = r.city
    else:
        city = 'Chicago'


问:
Accessing part of dictionary item
I am trying to gain information about all of the different cyclone seasons in a dataset at the same time. So far I have created a dictionary with the following:

```<code>#Getting number of storms; total and in each season
season = dict()

for year in range(1970, 2020):
    season[year] = ibtracs_all.get_season(year)

print("Number of seasons:")
print(len(season))
</code>```

Which gets me a dictionary with the key for each item being the respective year (i.e. 1970).

Each item contains the following information when I print the dictionary as a result of the tropycal module function 'get_season':

```<code>Season Summary:
    Total Storms:      13
    Named Storms:      0
    Hurricanes:        0
    Major Hurricanes:  0
    Season ACE:        0.0
More Information:
    year:          1970
    basin:         south_indian
    source_basin:  south_indian
    source:        ibtracs
    source_info:   Joint Typhoon Warning Center (unofficial), 1971: <tropycal.tracks.Season>
</code>```

How can I determine how many storms (Total Storms) there are in each season from this dictionary? I imagine some kind of additional loop through the dictionary but am unsure.

UPDATE: I have tried the following which only results in error:

```<code>x = season[year]['season_summary']['total_storms']
</code>```

Title: Accessing part of dictionary item

Body:
I am trying to gain information about all of the different cyclone seasons in a dataset at the same time. So far I have created a dictionary with the following:

#Getting number of storms; total and in each season
season = dict()

for year in range(1970, 2020):
    season[year] = ibtracs_all.get_season(year)

print("Number of seasons:")
print(len(season))

Which gets me a dictionary with the key for each item being the respective year (i.e. 1970).

Each item contains the following information when I print the dictionary as a result of the tropycal module function 'get_season':

Season Summary:
    Total Storms:      13
    Named Storms:      0
    Hurricanes:        0
    Major Hurricanes:  0
    Season ACE:        0.0
More Information:
    year:          1970
    basin:         south_indian
    source_basin:  south_indian
    source:        ibtracs
    source_info:   Joint Typhoon Warning Center (unofficial), 1971: <tropycal.tracks.Season>

How can I determine how many storms (Total Storms) there are in each season from this dictionary? I imagine some kind of additional loop through the dictionary but am unsure.

UPDATE: I have tried the following which only results in error:

x = season[year]['season_summary']['total_storms']


问:
Google Analytics Data API Get All Viewd Items
I need to retrieve data from Google Analytics Data API and get all items with item_id and item_name properties. With this code, I only get the total number of items but without item details. Any idea how to do that?

I have this code in my Console app:

```<code>using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;
using Google.Apis.Auth.OAuth2;

using Google.Apis.Util.Store;

namespace AnalyticsSamples
{
    class Program
    {
        private const string PropertyId = "xxxxxxxxx";
        private const string PathToCreds = @"C:\Temp\json1.json";

        static async Task Main(string[] args)
        {
            Console.WriteLine("Start");

            await SampleRunReport(PropertyId);
        }

        static async Task SampleRunReport(string propertyId = "xxxxxxxxx")
        {
            // Using a default constructor instructs the client to use the credentials
            // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
            //var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);

            BetaAnalyticsDataClient client;
            await using (var stream = new FileStream(PathToCreds, FileMode.Open, FileAccess.Read))
            {
                // Requesting Authentication or loading previously stored authentication for userName
                var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                    new[] { "https://www.googleapis.com/auth/analytics.readonly" },
                    "userName",
                    CancellationToken.None,
                    new FileDataStore("credPath", true)).Result;

                client = await new BetaAnalyticsDataClientBuilder
                {
                    TokenAccessMethod = credential.GetAccessTokenForRequestAsync
                }.BuildAsync();
            }

            var request = new RunReportRequest
            {
                Property = "properties/" + PropertyId,
                Dimensions = { new Dimension { Name = "date" }, },
                Metrics = { new Metric { Name = "itemViewEvents" }, new Metric { Name = "itemsViewed" } },
                DateRanges = { new DateRange { StartDate = "2023-01-01", EndDate = "today" }, },
            };

            var response = await client.RunReportAsync(request);

            Console.WriteLine("Report result:");

            foreach (var row in response.Rows)
            {
                Console.WriteLine(
                    $"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}");
            }
        }
    }
}
</code>```

And this code in my web page where I fire the event view_item

```<code>gtag("event", "view_item", {
        currency: "EUR",
        value: 200,
        items: [
            {
                item_id: "SKU_12345",
                item_name: "Samsung TV"
            }
        ]
    });
</code>```

Body:
I need to retrieve data from Google Analytics Data API and get all items with item_id and item_name properties. With this code, I only get the total number of items but without item details. Any idea how to do that?

I have this code in my Console app:

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;
using Google.Apis.Auth.OAuth2;

using Google.Apis.Util.Store;

namespace AnalyticsSamples
{
    class Program
    {
        private const string PropertyId = "xxxxxxxxx";
        private const string PathToCreds = @"C:\Temp\json1.json";

        static async Task Main(string[] args)
        {
            Console.WriteLine("Start");

            await SampleRunReport(PropertyId);
        }

        static async Task SampleRunReport(string propertyId = "xxxxxxxxx")
        {
            // Using a default constructor instructs the client to use the credentials
            // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
            //var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);

            BetaAnalyticsDataClient client;
            await using (var stream = new FileStream(PathToCreds, FileMode.Open, FileAccess.Read))
            {
                // Requesting Authentication or loading previously stored authentication for userName
                var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                    new[] { "https://www.googleapis.com/auth/analytics.readonly" },
                    "userName",
                    CancellationToken.None,
                    new FileDataStore("credPath", true)).Result;

                client = await new BetaAnalyticsDataClientBuilder
                {
                    TokenAccessMethod = credential.GetAccessTokenForRequestAsync
                }.BuildAsync();
            }

            var request = new RunReportRequest
            {
                Property = "properties/" + PropertyId,
                Dimensions = { new Dimension { Name = "date" }, },
                Metrics = { new Metric { Name = "itemViewEvents" }, new Metric { Name = "itemsViewed" } },
                DateRanges = { new DateRange { StartDate = "2023-01-01", EndDate = "today" }, },
            };

            var response = await client.RunReportAsync(request);

            Console.WriteLine("Report result:");

            foreach (var row in response.Rows)
            {
                Console.WriteLine(
                    $"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}");
            }
        }
    }
}

And this code in my web page where I fire the event view_item

gtag("event", "view_item", {
        currency: "EUR",
        value: 200,
        items: [
            {
                item_id: "SKU_12345",
                item_name: "Samsung TV"
            }
        ]
    });


问:
Access to attribute and method in OOP
i'm a beginner in python and starting  to learn OOP and the class way of programming

so i came across the following code :

```<code>class Employee :
    def __init__(self,name,age,salary):
        self.name ,self.age ,self.salary = name , age ,salary
    def __str__(self) -> str:
         return f'Employee name is {self.name} and {self.age} years old and is given a {self.salary} EGP a month  '

class EmployeeManger:
    Employee_list = []

    def add_Employee(self) :
        print('\n adding a new employee\n')
        name = input ('Please enter employee name : \n ')
        age  = input ('Please enter employee age : \n ')
        salary  = input ('Please enter employee salary : \n ')
        EmployeeManger.Employee_list.append(Employee(name,age,salary))
        print(EmployeeManger.Employee_list[0])

    def list_Employee(self) :
        if len(EmployeeManger.Employee_list) == 0 :
            print('No Employee Entered Yet')
        else :
            for emp in EmployeeManger.Employee_list :
                print(emp)

    def delete_Employee_with_age (self,start_age,end_age) :

        for x in range(len(EmployeeManger.Employee_list)-1,-1,-1):
            y = EmployeeManger.Employee_list[x]
            if start_age <= int(y.age) <=end_age :
                print(f'\nDeleteing {y.name}')
                EmployeeManger.Employee_list.pop(x)

    def find_by_name(self,S_name) :

        for y in EmployeeManger.Employee_list :
            if y.name == S_name :
                print(f'the name is found and {x.name} is a employee')
            else :
                print('Not found ')
</code>```

in line ( 31 and 38 ) i can't understand y.age and  y.name  what does it refer to ? and can someone please explain how python was able to access those values and understand those values as can't find where it was defined for it ?

i hope i made the question as clear as possible

Title: Access to attribute and method in OOP

Body:
i'm a beginner in python and starting  to learn OOP and the class way of programming

so i came across the following code :

class Employee :
    def __init__(self,name,age,salary):
        self.name ,self.age ,self.salary = name , age ,salary
    def __str__(self) -> str:
         return f'Employee name is {self.name} and {self.age} years old and is given a {self.salary} EGP a month  '

class EmployeeManger:
    Employee_list = []

    def add_Employee(self) :
        print('\n adding a new employee\n')
        name = input ('Please enter employee name : \n ')
        age  = input ('Please enter employee age : \n ')
        salary  = input ('Please enter employee salary : \n ')
        EmployeeManger.Employee_list.append(Employee(name,age,salary))
        print(EmployeeManger.Employee_list[0])

    def list_Employee(self) :
        if len(EmployeeManger.Employee_list) == 0 :
            print('No Employee Entered Yet')
        else :
            for emp in EmployeeManger.Employee_list :
                print(emp)

    def delete_Employee_with_age (self,start_age,end_age) :

        for x in range(len(EmployeeManger.Employee_list)-1,-1,-1):
            y = EmployeeManger.Employee_list[x]
            if start_age <= int(y.age) <=end_age :
                print(f'\nDeleteing {y.name}')
                EmployeeManger.Employee_list.pop(x)

    def find_by_name(self,S_name) :

        for y in EmployeeManger.Employee_list :
            if y.name == S_name :
                print(f'the name is found and {x.name} is a employee')
            else :
                print('Not found ')

in line ( 31 and 38 ) i can't understand y.age and  y.name  what does it refer to ? and can someone please explain how python was able to access those values and understand those values as can't find where it was defined for it ?

i hope i made the question as clear as possible


问:
How to ask for administrative privilege only once in OSX?
So I have an app that runs shell command twice, once to disable sleep and then a few moments later to enable sleep. The code looks as follows:

```<code>  NSAppleScript(source: "do shell script \"sudo pmset -a disablesleep 1\" with administrator " +
                    "privileges")!.executeAndReturnError(nil)
      // and then same code with with '0' instead of 1 to disable it
</code>```

However the issue is I don't want the user to enter their password EVERYTIME they call these commands. It's making for a poor user experience. Is there a way I can grant the entire app admin privilege and run shell commands however I want? Or is there a way to run this shell command without the user authorization?

Body:
So I have an app that runs shell command twice, once to disable sleep and then a few moments later to enable sleep. The code looks as follows:

  NSAppleScript(source: "do shell script \"sudo pmset -a disablesleep 1\" with administrator " +
                    "privileges")!.executeAndReturnError(nil)
      // and then same code with with '0' instead of 1 to disable it

However the issue is I don't want the user to enter their password EVERYTIME they call these commands. It's making for a poor user experience. Is there a way I can grant the entire app admin privilege and run shell commands however I want? Or is there a way to run this shell command without the user authorization?


问:
MicroROS build_agent.sh fails
I'm following the tutorial for microROS for teensy found here

https://micro.ros.org/docs/tutorials/core/teensy_with_arduino/

Everything up to the build step works ok, but build fails, error output below, but before we get to that, I wanted to provide some more context:

Building this inside a docker container on Nvidia Jetson Nano 4GB (B01)

```<code>/etc/nv_tegra_release
L4T BSP Version:  L4T R32.7.1
</code>```

I tried it with several container images found here:

https://github.com/dusty-nv/jetson-containers

ROS2Foxy:

```<code>dustynv/ros:foxy-ros-base-l4t-r32.7.1
dustynv/ros:foxy-pytorch-l4t-r32.7.1
</code>```

When I launched the docker container in both tests I used either:

```<code>./scripts/docker_run.sh -c dustynv/ros:foxy-ros-base-l4t-r32.7.1
./scripts/docker_run.sh -c dustynv/ros:foxy-pytorch-l4t-r32.7.1
</code>```

once inside the docker container This is the bit where it all goes south:

Build step

```<code>ros2 run micro_ros_setup build_agent.sh
</code>```

Below the parts of the output trace that are relevant:

```<code>[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
--- stderr: micro_ros_agent
Cloning into 'xrceagent'...
Switched to a new branch 'ros2'
HEAD is now at 3eb56b5 Release v2.3.0
Cloning into 'spdlog'...
HEAD is now at eb322062 Bump version to 1.9.2
CMake Warning (dev) at /usr/share/cmake-3.22/Modules/FindPackageHandleStandardArgs.cmake:438 (message):
The package name passed to `find_package_handle_standard_args` (tinyxml2)
does not match the name of the calling package (TinyXML2).  This can lead
to problems in calling code that expects `find_package` result variables
(e.g., `_FOUND`) to follow a certain pattern.
Call Stack (most recent call first):
cmake/modules/FindTinyXML2.cmake:40 (find_package_handle_standard_args)
/opt/ros/foxy/install/share/fastrtps/cmake/fastrtps-config.cmake:51 (find_package)
CMakeLists.txt:153 (find_package)
This warning is for project developers.  Use -Wno-dev to suppress it.

/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::signs'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `vtable for fmt::v6::format_error'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::snprintf_float<double>(double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::error_handler::on_error(char const*)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `char fmt::v6::internal::decimal_point_impl<char>(fmt::v6::internal::locale_ref)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::zero_or_powers_of_10_32'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `char fmt::v6::internal::thousands_sep_impl<char>(fmt::v6::internal::locale_ref)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `std::locale fmt::v6::internal::locale_ref::get<std::locale>() const'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `typeinfo for fmt::v6::format_error'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > fmt::v6::internal::grouping_impl<char>(fmt::v6::internal::locale_ref)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::format_float<long double>(long double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `spdlog::details::log_msg::log_msg(spdlog::source_loc, fmt::v6::basic_string_view<char>, spdlog::level::level_enum, fmt::v6::basic_string_view<char>)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::snprintf_float<long double>(long double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::format_error::~format_error()'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::hex_digits'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::digits'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::format_float<double>(double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::zero_or_powers_of_10_64'
collect2: error: ld returned 1 exit status
make[5]: *** [micro_ros_agent] Error 1
make[4]: *** [CMakeFiles/micro_ros_agent.dir/all] Error 2
make[3]: *** [all] Error 2
make[2]: *** [micro_ros_agent-prefix/src/micro_ros_agent-stamp/micro_ros_agent-build] Error 2
make[1]: *** [CMakeFiles/micro_ros_agent.dir/all] Error 2
make: *** [all] Error 2
---
Failed   <<< micro_ros_agent [10min 2s, exited with code 2]

Summary: 1 package finished [10min 48s]
1 package failed: micro_ros_agent
1 package had stderr output: micro_ros_agent
</code>```

I have also tried to completely reformat the SD card for the Jetson and start fresh. Same problem. So far I have spent 2 fulls days trying to overcome this problem. I think it is time to throw up my arms and ask for some kind soul out there to provide some insight!

Title: MicroROS build_agent.sh fails

Body:
I'm following the tutorial for microROS for teensy found here

https://micro.ros.org/docs/tutorials/core/teensy_with_arduino/

Everything up to the build step works ok, but build fails, error output below, but before we get to that, I wanted to provide some more context:

Building this inside a docker container on Nvidia Jetson Nano 4GB (B01)

/etc/nv_tegra_release
L4T BSP Version:  L4T R32.7.1

I tried it with several container images found here:

https://github.com/dusty-nv/jetson-containers

ROS2Foxy:

dustynv/ros:foxy-ros-base-l4t-r32.7.1
dustynv/ros:foxy-pytorch-l4t-r32.7.1

When I launched the docker container in both tests I used either:

./scripts/docker_run.sh -c dustynv/ros:foxy-ros-base-l4t-r32.7.1
./scripts/docker_run.sh -c dustynv/ros:foxy-pytorch-l4t-r32.7.1

once inside the docker container This is the bit where it all goes south:

Build step

ros2 run micro_ros_setup build_agent.sh

Below the parts of the output trace that are relevant:

[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
[Processing: micro_ros_agent]
--- stderr: micro_ros_agent
Cloning into 'xrceagent'...
Switched to a new branch 'ros2'
HEAD is now at 3eb56b5 Release v2.3.0
Cloning into 'spdlog'...
HEAD is now at eb322062 Bump version to 1.9.2
CMake Warning (dev) at /usr/share/cmake-3.22/Modules/FindPackageHandleStandardArgs.cmake:438 (message):
The package name passed to `find_package_handle_standard_args` (tinyxml2)
does not match the name of the calling package (TinyXML2).  This can lead
to problems in calling code that expects `find_package` result variables
(e.g., `_FOUND`) to follow a certain pattern.
Call Stack (most recent call first):
cmake/modules/FindTinyXML2.cmake:40 (find_package_handle_standard_args)
/opt/ros/foxy/install/share/fastrtps/cmake/fastrtps-config.cmake:51 (find_package)
CMakeLists.txt:153 (find_package)
This warning is for project developers.  Use -Wno-dev to suppress it.

/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::signs'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `vtable for fmt::v6::format_error'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::snprintf_float<double>(double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::error_handler::on_error(char const*)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `char fmt::v6::internal::decimal_point_impl<char>(fmt::v6::internal::locale_ref)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::zero_or_powers_of_10_32'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `char fmt::v6::internal::thousands_sep_impl<char>(fmt::v6::internal::locale_ref)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `std::locale fmt::v6::internal::locale_ref::get<std::locale>() const'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `typeinfo for fmt::v6::format_error'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > fmt::v6::internal::grouping_impl<char>(fmt::v6::internal::locale_ref)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::format_float<long double>(long double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `spdlog::details::log_msg::log_msg(spdlog::source_loc, fmt::v6::basic_string_view<char>, spdlog::level::level_enum, fmt::v6::basic_string_view<char>)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::snprintf_float<long double>(long double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::format_error::~format_error()'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::hex_digits'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::digits'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `int fmt::v6::internal::format_float<double>(double, int, fmt::v6::internal::float_specs, fmt::v6::internal::buffer<char>&)'
/microros_ws/install/micro_ros_agent/lib/libmicroxrcedds_agent.so.2.3.0: undefined reference to `fmt::v6::internal::basic_data<void>::zero_or_powers_of_10_64'
collect2: error: ld returned 1 exit status
make[5]: *** [micro_ros_agent] Error 1
make[4]: *** [CMakeFiles/micro_ros_agent.dir/all] Error 2
make[3]: *** [all] Error 2
make[2]: *** [micro_ros_agent-prefix/src/micro_ros_agent-stamp/micro_ros_agent-build] Error 2
make[1]: *** [CMakeFiles/micro_ros_agent.dir/all] Error 2
make: *** [all] Error 2
---
Failed   <<< micro_ros_agent [10min 2s, exited with code 2]

Summary: 1 package finished [10min 48s]
1 package failed: micro_ros_agent
1 package had stderr output: micro_ros_agent

I have also tried to completely reformat the SD card for the Jetson and start fresh. Same problem. So far I have spent 2 fulls days trying to overcome this problem. I think it is time to throw up my arms and ask for some kind soul out there to provide some insight!


问:
Cramer's rule function in python returns answers with decimal point
I have the following function in python:

```<code>def cramer(coef_matrix, free_coef_matrix):

    num_rows, num_cols = coef_matrix.shape

    if num_rows != num_cols:
        raise Exception("Cannot apply cramer's rule to a non-square matrix")

    determinant = np.linalg.det(coef_matrix)

    if determinant == 0:
        raise Exception("Cannot apply cramer's rule to a matrix with determinant 0")

    solution = num_rows*[0]

    for i in range(num_rows):
        coef_matrix_copy = coef_matrix.copy()
        coef_matrix_copy[:, i] = free_coef_matrix
        current_det = np.linalg.det(coef_matrix_copy)
        solution[i] = current_det / determinant

    return solution
</code>```

But the problem is when I run the function on the input:

```<code>coef_matrix:
[2, 1, 1],
[1, -1, -1]
[1, 2, 1]

free_coef_matrix:
[3, 0, 0]
</code>```

It returns [1.0, -2.0000000000000004, 3.0] instead of [1.0, -2.0, 3.0].
I know that there might be problems related to floating point, but I want to know if there might be a solution?

Body:
I have the following function in python:

def cramer(coef_matrix, free_coef_matrix):

    num_rows, num_cols = coef_matrix.shape

    if num_rows != num_cols:
        raise Exception("Cannot apply cramer's rule to a non-square matrix")

    determinant = np.linalg.det(coef_matrix)

    if determinant == 0:
        raise Exception("Cannot apply cramer's rule to a matrix with determinant 0")

    solution = num_rows*[0]

    for i in range(num_rows):
        coef_matrix_copy = coef_matrix.copy()
        coef_matrix_copy[:, i] = free_coef_matrix
        current_det = np.linalg.det(coef_matrix_copy)
        solution[i] = current_det / determinant

    return solution

But the problem is when I run the function on the input:

coef_matrix:
[2, 1, 1],
[1, -1, -1]
[1, 2, 1]

free_coef_matrix:
[3, 0, 0]

It returns [1.0, -2.0000000000000004, 3.0] instead of [1.0, -2.0, 3.0].
I know that there might be problems related to floating point, but I want to know if there might be a solution?


问:
only one quantity value from a shopping cart order details inserting into mysqli database
I am developing a shopping cart checkout feature and I am trying to insert cart contents into a databas, I was able to do succesfully with the code below, but I am having issues with the fact that only one quantity value from the array of values is inserting into the database, my code is below</p>
```<code>$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart_contents']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$product_id = $row['Product_id'];
$product_name = $row['product_name'];
$product_price = $row['discount_price'];
$qty = $_SESSION['qty_array'][$index];
$subtotal = $product_price * $qty;
$order_id  = $_SESSION['orderID'];

$stmt = $conn -> prepare('INSERT INTO order_details(order_id,product_id,product_name,product_price,qty,subtotal) VALUES (?,?,?,?,?,?)');
         if($order_id!=='' && $product_id!=='' && $product_name!=='' && $product_price!=='' && $qty!=='' && $subtotal!=='' ){
            $stmt -> bind_param('issiii', $order_id, $product_id, $product_name, $product_price, $qty, $subtotal);
$stmt -> execute();
      for($i=0;$i<count($qty);$i++){
foreach ($_SESSION["cart_contents"] as $i){
        $order_id = $order_id[$i];
        $product_id = $product_id[$i];
        $product_name = $product_name[$i];
        $product_price = $product_price[$i];
        $qty = $qty[$i];
        $subtotal = $subtotal[$i];}}}

</code>```

Body:
I am developing a shopping cart checkout feature and I am trying to insert cart contents into a databas, I was able to do succesfully with the code below, but I am having issues with the fact that only one quantity value from the array of values is inserting into the database, my code is below

$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart_contents']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$product_id = $row['Product_id'];
$product_name = $row['product_name'];
$product_price = $row['discount_price'];
$qty = $_SESSION['qty_array'][$index];
$subtotal = $product_price * $qty;
$order_id  = $_SESSION['orderID'];

$stmt = $conn -> prepare('INSERT INTO order_details(order_id,product_id,product_name,product_price,qty,subtotal) VALUES (?,?,?,?,?,?)');
         if($order_id!=='' && $product_id!=='' && $product_name!=='' && $product_price!=='' && $qty!=='' && $subtotal!=='' ){
            $stmt -> bind_param('issiii', $order_id, $product_id, $product_name, $product_price, $qty, $subtotal);
$stmt -> execute();
      for($i=0;$i<count($qty);$i++){
foreach ($_SESSION["cart_contents"] as $i){
        $order_id = $order_id[$i];
        $product_id = $product_id[$i];
        $product_name = $product_name[$i];
        $product_price = $product_price[$i];
        $qty = $qty[$i];
        $subtotal = $subtotal[$i];}}}


问:
how to read the contents of a json file returned from s3 storage as a blob in React
I have successfully retrieved a json file from s3 storage. It is returned as a blob. I am able to turn the blob into text with this code (taken from https://docs.amplify.aws/lib/storage/download/q/platform/js/#monitor-progress-of-download):

```<code>export async function getS3Item(filename)
{
  const result = await Storage.get(filename, { download: true });\
      result.Body.text().then(string => {
      //   // handle the String data return String
      console.log(string)
       });
}
</code>```

but the text is all gibberish (I'm assuming since object is in binary?)... such as: "h�b```f�d`a}��ǀ|@1V ..."

Is there a way I can directly read this as a json object in javascript so that I can extract data from it...?

Optionally, I can download the json file  (which is shown in the link above and I've gotten this to work) -- but I'd prefer not to download it -- just to extract legible data from the file

thanks so much (I'm quite unfamiliar with blobs).

Body:
I have successfully retrieved a json file from s3 storage. It is returned as a blob. I am able to turn the blob into text with this code (taken from https://docs.amplify.aws/lib/storage/download/q/platform/js/#monitor-progress-of-download):

export async function getS3Item(filename)
{
  const result = await Storage.get(filename, { download: true });\
      result.Body.text().then(string => {
      //   // handle the String data return String
      console.log(string)
       });
}

but the text is all gibberish (I'm assuming since object is in binary?)... such as: "h�b```f�d`a}��ǀ|@1V ..."

Is there a way I can directly read this as a json object in javascript so that I can extract data from it...?

Optionally, I can download the json file  (which is shown in the link above and I've gotten this to work) -- but I'd prefer not to download it -- just to extract legible data from the file

thanks so much (I'm quite unfamiliar with blobs).


问:
Async/Await with MongoDB Rust Driver not Waiting for Insert
I am attempting to write an integration test for a utility module where my search function returns a new aggregate pipeline. When the database has 0 collections, this fails with an index out-of-bounds error on accounts[0]. It's acting as if the aggregate pipeline is not waiting for the insert to happen. How do I refactor this to make the aggregate stage wait for the insert?

#[actix_web::test]
async fn test_search_pipeline() {
    let pipeline = vec![doc! { "$match": { "isDeleted": { "$ne": true } } }];

    let mut updated_pipeline = super::search(&pipeline, String::from("foo"));

    let db: Database = connect_to_database().await;
    let accounts_col: Collection<Document> = db.collection("accounts");

    let account_fixture = account::create();

    // Insert a new account in the database
    let new_account = match accounts_col.insert_one(account_fixture, None).await {
        Ok(new_account) => new_account,
        Err(e) => {
            panic!("Unable to insert new account test fixture document: {}", e);
        }
    };

    // Execute the search aggregate pipeline to find the document we just inserted
    let accounts = match accounts_col.aggregate(updated_pipeline, None).await {
        Ok(mut cursor) => {
            let mut accounts: Vec<Document> = Vec::new();

            while let Some(doc) = cursor.next().await {
                match doc {
                    Ok(doc) => accounts.push(doc),
                    Err(e) => panic!("Error iterating through the new account test pipeline cursor : {}", e)
                }
            }

            accounts
        },
        Err(e) => {
            panic!("Unable to execute test search aggregate pipeline: {}", e);
        }
    };

    // Compare the new account id that we inserted with the first search result account id
    let new_account_id: String = new_account.inserted_id.as_object_id().unwrap().to_hex();
    let search_account_id: String = accounts[0].get_object_id("_id").unwrap().to_hex();

    assert_eq!(new_account_id, search_account_id);
}
```
<p>I have tried removing the actual database calls from the match statements and nesting the aggregate stage inside of the Ok arm of the insert Result. Neither of those changes seem to change the result.</p>
<p>account_fixture:</p>
```doc! {
    "name": "ufc0kpu!pgu1QJW3unj",
    "logo": "60e9ca73c500a9001534ad84-logo.png",
    "isActive": true,
    "isDeleted": false,
    "isUnlimited": false,
    "parentAccount": null,
    "credits": 100,
    "isProAccount": true,
    "is360Enabled": true,
    "isResourcesDisabled": false,
    "isEcoPrinting": false,
    "isCoreExtended": false,
    "createdAt": "2021-09-02T12:11:37.995+0000",
}
```
<p>updated_pipeline:</p>
```doc! {
    "$search": {
        "autocomplete": {
            "query": "ufc0kpu!pgu1QJW3unj",
            "path": "name",
            "fuzzy": {
                "maxEdits": 2,
                "prefixLength": 8
            }
        }
    }
}
```
<p>UPDATE: I have tried specifying <code>1</code> instead of <code>majority</code> for the write concern option on the <code>insert_one</code>, and unfortunately, <strong>it still results in a race condition</strong>. I was reading this page on casual consistency when I decided to try the code below. It seems like this should <strong>guarantee</strong> read-after-write consistency, but it does not.</p>
<pre class="lang-rust prettyprint-override"><code>let new_account = match accounts_col.insert_one(account_fixture, {
    let mut options = InsertOneOptions::default();
    options.bypass_document_validation = None;
    options.write_concern = Some(WriteConcern::builder().w(Acknowledgment::Nodes(1)).build());
    options
}).await {
    Ok(new_account) => new_account,
    Err(e) => {
        panic!("Unable to insert new account test fixture document: {}", e);
    }
};
</code>```

Body:
I am attempting to write an integration test for a utility module where my search function returns a new aggregate pipeline. When the database has 0 collections, this fails with an index out-of-bounds error on accounts[0]. It's acting as if the aggregate pipeline is not waiting for the insert to happen. How do I refactor this to make the aggregate stage wait for the insert?

#[actix_web::test]
async fn test_search_pipeline() {
    let pipeline = vec![doc! { "$match": { "isDeleted": { "$ne": true } } }];

    let mut updated_pipeline = super::search(&pipeline, String::from("foo"));

    let db: Database = connect_to_database().await;
    let accounts_col: Collection<Document> = db.collection("accounts");

    let account_fixture = account::create();

    // Insert a new account in the database
    let new_account = match accounts_col.insert_one(account_fixture, None).await {
        Ok(new_account) => new_account,
        Err(e) => {
            panic!("Unable to insert new account test fixture document: {}", e);
        }
    };

    // Execute the search aggregate pipeline to find the document we just inserted
    let accounts = match accounts_col.aggregate(updated_pipeline, None).await {
        Ok(mut cursor) => {
            let mut accounts: Vec<Document> = Vec::new();

            while let Some(doc) = cursor.next().await {
                match doc {
                    Ok(doc) => accounts.push(doc),
                    Err(e) => panic!("Error iterating through the new account test pipeline cursor : {}", e)
                }
            }

            accounts
        },
        Err(e) => {
            panic!("Unable to execute test search aggregate pipeline: {}", e);
        }
    };

    // Compare the new account id that we inserted with the first search result account id
    let new_account_id: String = new_account.inserted_id.as_object_id().unwrap().to_hex();
    let search_account_id: String = accounts[0].get_object_id("_id").unwrap().to_hex();

    assert_eq!(new_account_id, search_account_id);
}

I have tried removing the actual database calls from the match statements and nesting the aggregate stage inside of the Ok arm of the insert Result. Neither of those changes seem to change the result.

account_fixture:

doc! {
    "name": "ufc0kpu!pgu1QJW3unj",
    "logo": "60e9ca73c500a9001534ad84-logo.png",
    "isActive": true,
    "isDeleted": false,
    "isUnlimited": false,
    "parentAccount": null,
    "credits": 100,
    "isProAccount": true,
    "is360Enabled": true,
    "isResourcesDisabled": false,
    "isEcoPrinting": false,
    "isCoreExtended": false,
    "createdAt": "2021-09-02T12:11:37.995+0000",
}

updated_pipeline:

doc! {
    "$search": {
        "autocomplete": {
            "query": "ufc0kpu!pgu1QJW3unj",
            "path": "name",
            "fuzzy": {
                "maxEdits": 2,
                "prefixLength": 8
            }
        }
    }
}

UPDATE: I have tried specifying 1 instead of majority for the write concern option on the insert_one, and unfortunately, it still results in a race condition. I was reading this page on casual consistency when I decided to try the code below. It seems like this should guarantee read-after-write consistency, but it does not.

let new_account = match accounts_col.insert_one(account_fixture, {
    let mut options = InsertOneOptions::default();
    options.bypass_document_validation = None;
    options.write_concern = Some(WriteConcern::builder().w(Acknowledgment::Nodes(1)).build());
    options
}).await {
    Ok(new_account) => new_account,
    Err(e) => {
        panic!("Unable to insert new account test fixture document: {}", e);
    }
};


问:
Error: ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject
I am trying to run tombo v 1.5.1 and it needs numpy. I have installed numpy 1.24.1 but when I am running tombo, it is giving following error:
ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject

Please help!!!

Installed numpy v 1.24.1
pip show numpy
Name: numpy
Version: 1.24.1
When I am running tombo it is giving following error:
ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject

I uninstalled the previously installed numpy and reinstall lower verion with pip install numpy==1.20.3. Then it is giving me following error:
ERROR: Failed building wheel for numpy
Failed to build numpy
ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects

Note: I am using HPC system to install it.


问:
Adaptive time/position series filter in R...?
I'm trying to filter a time/position data series to produce a smoothed plot.  I am measuring depth vs time (mechanical system) where the velocity is changing.  I calculate velocity from the measured depth/time values and can plot velocity vs. depth, but at low speeds, the noise is excessive (for various reasons).  The trend at low speeds is correct, but I'd like to be able to apply a filter that will use an adaptive smoothing routine, i.e. for low speeds (where I have many data points) I need to use a larger smoothing window, and for high speeds (few data points) I need to use a smaller window.

I've looked a bit and have figured out a solution using rollapply() but was wondering if there are other approaches.  In particular, I'm not clear on how to "vectorise" an operation.  I'm a relatively new coder so I'm sorry if my code is a bit amateurish.  My solution is below:

```<code>adapt<-function(x,wmin,wmax) {
# adapt takes a vector of calculated velocities (x), a minimum window size (wmin),
# and a maximum window size (wmax).  It returns a vector of filtered velocities
#
    x<-ifelse(is.na(x),0,x)  # check for na values
    x<-ifelse(is.infinite(1/x),1/wmax,x)  # check for infinite values
    x<-runmed(x,11)  # smooth raw velocities using 11 point window
    wins<-ceiling(ifelse(is.infinite(1/x),wmin,1+wmax/(1+x)^15))  # set window widths
    wins<-ifelse(wins<=wmin,wmin,wins)  # set min windows
    wins<-ifelse(wins>wmax,wmax,wins)  # set max windows
    out<-rollapply(x,width=wins,median)  # apply filter to each element
    out[length(x)]<-0  # set last value to zero
    return(out)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to filter a time/position data series to produce a smoothed plot.  I am measuring depth vs time (mechanical system) where the velocity is changing.  I calculate velocity from the measured depth/time values and can plot velocity vs. depth, but at low speeds, the noise is excessive (for various reasons).  The trend at low speeds is correct, but I'd like to be able to apply a filter that will use an adaptive smoothing routine, i.e. for low speeds (where I have many data points) I need to use a larger smoothing window, and for high speeds (few data points) I need to use a smaller window.

I've looked a bit and have figured out a solution using rollapply() but was wondering if there are other approaches.  In particular, I'm not clear on how to "vectorise" an operation.  I'm a relatively new coder so I'm sorry if my code is a bit amateurish.  My solution is below:

adapt<-function(x,wmin,wmax) {
# adapt takes a vector of calculated velocities (x), a minimum window size (wmin),
# and a maximum window size (wmax).  It returns a vector of filtered velocities
#
    x<-ifelse(is.na(x),0,x)  # check for na values
    x<-ifelse(is.infinite(1/x),1/wmax,x)  # check for infinite values
    x<-runmed(x,11)  # smooth raw velocities using 11 point window
    wins<-ceiling(ifelse(is.infinite(1/x),wmin,1+wmax/(1+x)^15))  # set window widths
    wins<-ifelse(wins<=wmin,wmin,wins)  # set min windows
    wins<-ifelse(wins>wmax,wmax,wins)  # set max windows
    out<-rollapply(x,width=wins,median)  # apply filter to each element
    out[length(x)]<-0  # set last value to zero
    return(out)
}


问:
Encryption issues with Chilkat/Powerbuilder/Soap
I am looking to do the following:

Perform a secured mutual authentication connection with the interface server.

Encrypt the SOAP body for all web service requests

Sign all SOAP requests using the client private certificate, before sending the request via this interface.

I am struggling with how to encrypt the SOAP body.

Using Chilkat.Crypt2 I can encrypt the entire file - however this includes the headers and not what is required.

Looking for some guidance please!